Android:how to start activity from async task in android

1.2k views Asked by At

In my android application , I want to start activity class from async-task.this a login pahe class. It gives error in else part in onPostExecute(String result)(when start in new activity). error :Android - android.os.NetworkOnMainThreadException I used several method to fix this but I'm unable to fix this one. please some one gives me a help

public class Login extends Activity {

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


@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 intent = new Intent(Login.this, MainMenu.class);
            intent.putExtra("photo", str);
            intent.putExtra("username", username);  
            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;
    }

}

this is my LogCat

10-11 18:37:52.540: E/AndroidRuntime(2858): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bni.www/com.bni.www.MainMenu}: android.os.NetworkOnMainThreadException



10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1026)
10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-11 19:00:45.498: E/AndroidRuntime(2925):     at android.os.Looper.loop(Looper.java:132)

 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.lang.reflect.Method.invokeNative(Native Method)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.lang.reflect.Method.invoke(Method.java:491)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at dalvik.system.NativeStart.main(Native Method)
 10-11 19:00:45.498: E/AndroidRuntime(2925): Caused by: android.os.NetworkOnMainThreadException
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.InetAddress.getAllByName(InetAddress.java:249)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:217)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.URLConnection.getContent(URLConnection.java:197)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at java.net.URL.getContent(URL.java:613)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at com.bni.www.MainMenu.onCreate(MainMenu.java:48)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.app.Activity.performCreate(Activity.java:4411)
  10-11 19:00:45.498: E/AndroidRuntime(2925):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
 10-11 19:00:45.498: E/AndroidRuntime(2925):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1781)
  10-11 19:00:45.498: E/AndroidRuntime(2925):   ... 11 more 
  10-11 19:01:22.538: I/Process(2925): Sending signal. PID: 2925 SIG: 9
  10-11 19:12:24.357: D/dalvikvm(2998): GC_FOR_ALLOC freed 43K, 3% free 6404K/6595K, paused 111ms
  10-11 19:12:24.377: I/dalvikvm-heap(2998): Grow heap (frag case) to 7.295MB for 1031504-byte allocation
  10-11 19:12:24.489: D/dalvikvm(2998): GC_FOR_ALLOC freed <1K, 3% free 7411K/7623K, paused 86ms
2

There are 2 answers

0
vfcosta On

Make sure to not access network in main thread at MainMenu class (create another AsyncTask for code at line 48).

NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

1
WillingLearner On

Your code might work on 2.2 since it doesnt restrict us from using network on the ui thread.

Use asynctask for network operations