user3738248
user3738248

Reputation: 81

AsyncTask still giving networkOnMainThreadException

public class WelcomeActivity extends Activity {

class Retrieve extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("some link");
    try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("username","someUser"));
        nameValuePairs.add(new BasicNameValuePair("password","somepass"));
        nameValuePairs.add(new BasicNameValuePair("method","checkLogin"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //Execute HTTP Post
        HttpResponse response = httpClient.execute(httpPost);
        //  Log.v("response", response.toString());
        Log.d("hi","hello");
        //  Log.d("response",response.toString());
    }catch(Exception e){
        Log.e("YOUR_APP_LOG_TAG","I got an error",e);
    }
    return null;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    new Retrieve().execute();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.welcome, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
        return super.onOptionsItemSelected(item);
    }
}

The class Retrieve is for sending the POST request to the server, but I don't understand why it is still being treated as executed on main thread instead of the async task.

I have looked at previous questions concerning Async usage but keep getting this error:

   12-25 13:31:57.310    1782-1782/com.example.dalvir.quizapp E/YOUR_APP_LOG_TAG﹕ I got an error
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at com.example.dalvir.quizapp.WelcomeActivity.onCreate(WelcomeActivity.java:44)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

Any help is much appreciated!

Upvotes: 1

Views: 118

Answers (2)

bhans
bhans

Reputation: 51

If you are using SDK version >= 3,

add this line of code in your onCreate() method before calling your AsyncTask:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
    .detectDiskReads()   
    .detectDiskWrites()   
    .detectNetwork() 
    .penaltyLog()   
    .build());

Hope this helps :)

Upvotes: 0

Vikas
Vikas

Reputation: 4301

You may be targeting your SDK equal to or higher than api level 11. Try changing it to api level 8 or other api level below 11. You might find your solution here:

Error while publishing photo on facebook wall using android facebook sdk

Upvotes: 1

Related Questions