Domanda

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

È stato utile?

Soluzione

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); 
}

Altri suggerimenti

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);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top