0

Possible Duplicate:
android.os.NetworkOnMainThreadException

When I run the my android application, I got android.os.NetworkOnMainThreadException, what is the reason for that.how do I fix It.this is my code

public class Login extends Activity {

private Button btnLogin;
private EditText txtusername;
private EditText txtPassword;
public String username;
public String password;
public boolean doLogin = false;
Intent intent;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.login);


    btnLogin = (Button) findViewById(R.id.btnLogin);
    txtusername = (EditText) findViewById(R.id.txtuserName);
    txtPassword = (EditText) findViewById(R.id.txtPassword);
    btnLogin.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            username = txtusername.getText().toString();
            password = txtPassword.getText().toString();

            if (username.equals("") || password.equals("")) {

                AlertDialog alert = new AlertDialog.Builder(Login.this)
                        .create();
                alert.setMessage("Username or Password can not be Empty");
                alert.setButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                            }
                        });

                alert.setIcon(R.drawable.loginlogo);
                alert.show();

            }

            else {

                HttpAsync httpasync = new HttpAsync();

                httpasync.execute(new String[] { "http://www.diskonbanget.com/bni/login/login.php" });

            }

        }

    });

}

private class HttpAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String str = null;
        try {

            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://www.diskonbanget.com/bni/login/login.php");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs
                    .add(new BasicNameValuePair("username", username));
            nameValuePairs
                    .add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request

            HttpResponse response = httpclient.execute(httppost);

            str = inputStreamToString(response.getEntity().getContent())
                    .toString();

        } catch (Exception e) {
            return str;
        }
        return str;
    }

    @Override
    protected void onPostExecute(String result) {
        String str = result;

        if (str.toString().equalsIgnoreCase("false")) {

            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Please enter valid username & Password");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            alert.setIcon(R.drawable.loginlogo);
            alert.show();

        }

        else if (str.toString().equalsIgnoreCase("null")) {
            AlertDialog alert = new AlertDialog.Builder(Login.this)
                    .create();
            alert.setMessage("Can not Connect to the server.please make sure your internet is Switch on  ");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alert.setIcon(R.drawable.loginlogo);
            alert.show();
        }

        else {

            intent = new Intent(Login.this, MainMenu.class);
            intent.putExtra("photo", str);
            intent.putExtra("username", str);   
            getApplicationContext().startActivity(intent);

        }

    }

}

private StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        return total;

    } catch (Exception e) {

        return null;
    }

}

please someone help me.android version3.2, try to run using XOOM2 emulator

Community
  • 1
  • 1

2 Answers2

3

The reason is that your login method makes an http connection in the ui thread, you should do it in a separate thread or use an AsynchTask..

You can pass the context to the task, and then:

protected void onPostExecute(Void result) {
   Intent showContent = new Intent(context, yourActivity.class);
   context.startActivity(showContent);
}
Nermeen
  • 15,883
  • 5
  • 59
  • 72
  • I got what you are saying also.Thanks for the answer –  Oct 05 '12 at 10:22
  • how can I call to start activity from my async thread class I tried in onPostExecute(String result) method but I give me android:os.NetWorkom Main Thread exception. if you can please help me –  Oct 11 '12 at 09:51
  • All your http calls must be done in doInBackground method, to start new activity (i updated my answer) – Nermeen Oct 11 '12 at 09:59
  • it also gives me a error. I edited my code above.please check it.give me a solution –  Oct 11 '12 at 10:28
  • what is the error and where.. – Nermeen Oct 11 '12 at 10:31
  • Error place:else part at onPostExecute(String result) method (when start to call new activity) Error:android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? –  Oct 11 '12 at 10:40
  • remove getApplicationContext() add call it using startActivity(intent); – Nermeen Oct 11 '12 at 11:13
  • it doesn't work. I don't know what to do.............OsNetworkMainThread exception again –  Oct 11 '12 at 12:05
2

I dont advise it though but you can use this for test. Refer to @imran khan for good practice.
Add this in your onCreate() method to bypass the checking.

if( Build.VERSION.SDK_INT >= 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy); 
}
Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
  • I used this one.it's works fine.is there any problem if I use this method? –  Oct 05 '12 at 08:43
  • Well I have used it on my application which is in the market. There is no problem in the method, just it is disliked to load data from the internet using the main thread, and google add the StrictMode not long ago. A good practice to get data from the net is to use Asynch Task or service so you dont have to worry if the response from the server takes time. – Lazy Ninja Oct 05 '12 at 09:11
  • Is this method to response time?. sry for my stupid question –  Oct 05 '12 at 09:59
  • No question is stupid if your intention is to seek knowledge. This method is just to bypass the process of checking if the internet request is done in a main thread or not. It has nothing to do with the request itself. – Lazy Ninja Oct 05 '12 at 10:03
  • Now , I have question, previously I have used 3.2 as my target version. now I want to change it 2.2 . when I change to 2.2, above method is not allowed. it gives error. what should I do for avoid that one.please help me –  Oct 11 '12 at 06:55
  • Using AsynchTask will work for all versions – Nermeen Oct 11 '12 at 07:28
  • Yes StrictMode is not defined in 2.2. I added a condition. Please See my edit.That worked for me in all versions. – Lazy Ninja Oct 11 '12 at 08:00
  • @Lazy :I am developing for 2.2 ,so I can not implement it in my code. because StrickMode methods doesn't declare.above edit version not allow in my 2.2 version,anyway thanks for your effort. –  Oct 11 '12 at 08:20
  • @Lahiru you are right! If you add this to your manifest file, all you have to do is to ignore the warnings; . But like I said before using AsynchTask is better. – Lazy Ninja Oct 11 '12 at 08:40
  • Not ignoring the warnings, you just disable the errors check if your are using eclipse. – Lazy Ninja Oct 11 '12 at 09:04
  • i added to my manifest file & still does not allow me to add above code –  Oct 11 '12 at 09:21
  • Hmm it is weird! Are you using Eclipse? Eclipse will show it as errors but you can disable the errors checking. It is working on my project, should be work with yours too. – Lazy Ninja Oct 11 '12 at 09:42
  • I'm using eclipse.it doesn't allow me to disable the error. I'm very unlucky, i used async method, it also gives me error....:(( –  Oct 11 '12 at 12:08
  • Okay start a new question with the asynchtask. It is not difficult. – Lazy Ninja Oct 12 '12 at 00:52