1

I try to run my android app on a device and my login crashed. the logcat show this error

09-12 21:32:12.289: E/AudioHardwareALSA(149): RE-OPEN AFTER STANDBY:: took 115 msecs
09-12 21:32:12.319: E/AndroidRuntime(4760): FATAL EXCEPTION: main
09-12 21:32:12.319: E/AndroidRuntime(4760): android.os.NetworkOnMainThreadException
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.library.JSONParser.getJSONFromUrl(JSONParser.java:44)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.library.UserFunctions.loginUser(UserFunctions.java:40)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.stts.sparetimetradingsystem.LoginActivity$Login$1.run(LoginActivity.java:125)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Handler.handleCallback(Handler.java:605)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.os.Looper.loop(Looper.java:137)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at android.app.ActivityThread.main(ActivityThread.java:4424)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.lang.reflect.Method.invokeNative(Native Method)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at java.lang.reflect.Method.invoke(Method.java:511)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
09-12 21:32:12.319: E/AndroidRuntime(4760):     at dalvik.system.NativeStart.main(Native Method)

Where did i done wrong?

EDIT

This is my login code where it is inside the async task, and can i know whether is my async task properly coded:

// Background ASYNC Task to login by making HTTP Request
class Login extends AsyncTask<String, String, String> {

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

    // Checking login in background
    protected String doInBackground(String... params) {
        runOnUiThread(new Runnable() {
            public void run() {

                String email = inputEmail.getText().toString();
                String password = inputPassword.getText().toString();
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.loginUser(email, 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) {
                            validUser = true;
                            // 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_EMAIL),
                                    json.getString(KEY_UID),
                                    json_user.getString(KEY_CREATED_AT));
                        } 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 done
        pDialog.dismiss();
        if (validUser == true) {
            loginErrorMsg.setText("");
            // Launch HomePage Screen
            Intent homepage = new Intent(getApplicationContext(),
                    HomepageActivity.class);

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

            // Close Login Screen
            finish();
        }
    }
}
4
  • please switch to async task to do nw operations this is found in android 3.0+ if you try to run network operation in main thread Sep 12, 2012 at 13:35
  • when running NetworkOperations on the UIThread. as mentioned in the Exception name. Sep 12, 2012 at 13:35
  • my login is inside async task already
    – Sarah Phil
    Sep 12, 2012 at 13:37
  • what's the device android version ?
    – Sankar
    Sep 12, 2012 at 13:37

2 Answers 2

2

You are using an AsyncTask but inside your doInBackground, you are actually executing your networking code through:

 runOnUiThread(new Runnable() { }

That's the reason why you end up with this exception, you need to execute your networking code without that. I guess you do it to have a reference to the application context, but it is rather simple just to provide it through the AsyncTask constructor.

7
  • meaning i just have to remove that code inside my doInBackground?
    – Sarah Phil
    Sep 12, 2012 at 13:45
  • yes, you need to remove the runOnUiThread bit and execute the code directly in the doInBackground method.
    – Moystard
    Sep 12, 2012 at 13:46
  • I see that you access your view values (EditText probably) and update them from the AsyncTask. You should do that in the preExecute, postExecute and progressUpdate methods as they are executed in the UI thread. Avoid all these in the doInBackground method.
    – Moystard
    Sep 12, 2012 at 13:50
  • means my getting of user input from the textfields must be in the postExecute?
    – Sarah Phil
    Sep 12, 2012 at 13:53
  • Apparently you need the user input to perform the login, so do it in the preExecute. In the postExecute, you can update the error message if required (you are doing that in the doInBackground method for now), and launch the new activity if the login is successful (you are doing that already).
    – Moystard
    Sep 12, 2012 at 13:55
2

Android is not allowing network calls on main thread from android 3.0(Honeycomb) onwards. So you have to use Asynctask for network calls.

To get rid of this you need to make that network call using AsynTask.

4
  • see my edit. Im new to android. sorry for my knowledge towards it
    – Sarah Phil
    Sep 12, 2012 at 13:39
  • you wrote your application based on 2.3.3, in this android is allowing network calls on main thread(UI). But from android 3.0 onwards it's not allowing network calls on UI thread.so, if you run your app on device running on 3.0 or more you will get this exception
    – Sankar
    Sep 12, 2012 at 13:44
  • hmm so i just remove the runOnUIthread to solve this problem?
    – Sarah Phil
    Sep 12, 2012 at 13:48
  • yes you need to remove the runOnUIthread, then it will execute your operation on asynctask only. It will solve the problem.
    – Sankar
    Sep 12, 2012 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.