Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8396019
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T20:26:21+00:00 2026-06-09T20:26:21+00:00

I am running on android 3.1 and I have implemented async in my login

  • 0

I am running on android 3.1 and I have implemented async in my login java class. However, after i implement it in, I got the strict mode exception. Why are there this kind of errors?

Login.java

public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputNric;
EditText inputPassword;
TextView loginErrorMsg;


// Progress Dialog
private ProgressDialog pDialog;

// JSON Response node names
//success is the column name of the database - KEY_SUCCESS is we create the name 
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_NAME = "name";
private static String KEY_NRIC = "nric";
private static String KEY_CREATED_AT = "created_at";

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  //  StrictMode.setThreadPolicy(policy);

    // Importing all assets like buttons, text fields
    inputNric = (EditText) findViewById(R.id.loginNric);
    inputPassword = (EditText) findViewById(R.id.loginPassword);
    btnLogin = (Button) findViewById(R.id.buttonLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);

    // login button click event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // starting background task to update case
            new LoginUser().execute();
        }
    });

    /*// Link to Register Screen
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
            RegisterActivity.class);
            startActivity(i);
            finish();
        }
    });*/
}

/**
 * Background Async Task to  Login User
 * */
    class LoginUser extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */        
        protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Logging In ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        }

        /**
        * Logging in
        * */
        protected String doInBackground(String... params) {
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                String nric = inputNric.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                Log.d("Button", "Login");
                JSONObject json = userFunction.loginUser(nric, password);

                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        loginErrorMsg.setText("");
                        String res = json.getString(KEY_SUCCESS); 
                        if(Integer.parseInt(res) == 1){
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_NRIC), json_user.getString(KEY_CREATED_AT));                      

                            // Launch home Screen
                            Intent home = new Intent(getApplicationContext(), AllTabActivity.class);

                            // Close all views before launching home
                            home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(home);

                            // Close Login Screen
                            finish();
                        }else{
                            // Error in login
                            loginErrorMsg.setText("Incorrect username/password");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                }
            });
                return null;
        }

         /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once case deleted
            pDialog.dismiss();

        }
    }

    }

Logcat errors:

08-14 17:46:37.766: E/AndroidRuntime(1208): android.os.NetworkOnMainThreadException
08-14 17:46:37.766: E/AndroidRuntime(1208):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at java.net.InetAddress.getAllByName(InetAddress.java:249)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at com.pivestigator.JSONParser.makeHttpRequest(JSONParser.java:51)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at com.pivestigator.login.library.UserFunctions.loginUser(UserFunctions.java:40)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at com.pivestigator.login.LoginActivity$LoginUser$1.run(LoginActivity.java:112)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at android.os.Handler.handleCallback(Handler.java:587)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at android.os.Looper.loop(Looper.java:132)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at android.app.ActivityThread.main(ActivityThread.java:4025)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at java.lang.reflect.Method.invoke(Method.java:491)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
08-14 17:46:37.766: E/AndroidRuntime(1208):     at dalvik.system.NativeStart.main(Native Method)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T20:26:23+00:00Added an answer on June 9, 2026 at 8:26 pm

    You have doing network operations in runOnUiThread, which will be invoked into event thread, instead you should do as following:

    /**
     * Background Async Task to  Login User
     * */
        class LoginUser extends AsyncTask<String, String, String> {
    
            /**
             * Before starting background thread Show Progress Dialog
             * */        
            protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Logging In ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            }
    
            /**
            * Logging in
            * */
            protected String doInBackground(String... params) {
                // updating UI from Background Thread
                   String nric = inputNric.getText().toString();
                    String password = inputPassword.getText().toString();
                    UserFunctions userFunction = new UserFunctions();
                    Log.d("Button", "Login");
                    JSONObject json = userFunction.loginUser(nric, password);
    
                    // check for login response
                    try {
                        if (json.getString(KEY_SUCCESS) != null) {
                            loginErrorMsg.setText("");
                            String res = json.getString(KEY_SUCCESS); 
                            if(Integer.parseInt(res) == 1){
                                // user successfully logged in
                                // Store user details in SQLite Database
                                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                                JSONObject json_user = json.getJSONObject("user");
    
                                // Clear all previous data in database
                                userFunction.logoutUser(getApplicationContext());
                                db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_NRIC), json_user.getString(KEY_CREATED_AT));                      
    
    runOnUiThread(new Runnable() {
                public void run() {
    
                                // Launch home Screen
                                Intent home = new Intent(getApplicationContext(), AllTabActivity.class);
    
                                // Close all views before launching home
                                home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(home);
    
                                // Close Login Screen
                                finish();
                            }else{
                                // Error in login
                                loginErrorMsg.setText("Incorrect username/password");
                            }
    }
    });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
    
                    return null;
            }
    
             /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog once case deleted
                pDialog.dismiss();
    
            }
        }
    
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have successfully implemented this from android to a java httpservlet on google app
I have PhoneGap app running in Android. When the app starts, it inserts approximately
I have attached an image of google maps running on android 2.3.5. How do
Ok, I have my android game running smooth but can't get it to advance
I have an android recurring service running in background, no Activity running in front
I have the following code running on my Android device. It works great and
I'm learning Android development. I have a basic app running on the Gingerbread emulator,
My application running android ice cream sandwich, after importing roboto.ttf and roboto-bold.ttf fonts in
I just started android and I'm running into some problems. I have created a
Hello have only a few days with Java and android here. I am a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.