Domanda

I've an activity (MainActivity) that is supposed to do a version check of my up with a server and allow the users to login into accounts. the problem is that both the functions use network connection (obvously), they work with a 3g connection but i try to use a wifi connection the app throws NetworkOnMainThread exception. the even more strange thing (to me at least) is that this problem only occurs with this activity, all other activity can access both 3g and wifi and they uses the same Class as MainActivity. how can it be?

MainActivity:

public class MainActivity extends Activity implements OnTaskCompleted{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        try {
            version=Float.parseFloat(getApplicationContext().getPackageManager().
                    getPackageInfo(getApplicationContext().getPackageName(), 0).versionName);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(!isOnline()){
            //prevent user to go further
        }else{      
            String url="/*mydomain*//version_check.php";
            PostRequest post=new PostRequest(url,null,MainActivity.this,"version");
            post.execute(url);
        }

        //LOGIN CODE
    }

    @Override
    public void onTaskCompleted(Object return_value, String type) {
        if(type.equals("version")){
            float latest=Float.parseFloat((String)return_value);
            if(version<latest){
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);                
                 alertDialogBuilder.setMessage("update app!!!");
                    alertDialogBuilder.setNegativeButton("not now",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            // if this button is clicked, close
                            // current activity
                            finish();
                        }
                      });
                    alertDialogBuilder.setPositiveButton("update now!",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, close
                                // current activity
                                //go to playstore
                            }
                          });

                        // create alert dialog
                        alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
            }
        }
        if(type.equals("login")){
            //login response handling


    }

    public boolean isOnline(){
        ConnectivityManager cm=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo=cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }

}

PostRequest code: public class PostRequest extends AsyncTask {

private HttpClient client;
private HttpPost request;
public String result, type;
private OnTaskCompleted listener;
public HttpResponse response;

public PostRequest(String url, List<NameValuePair> nameValuePairs, OnTaskCompleted listener, String type){
    this.client=new DefaultHttpClient();
    this.request = new HttpPost(url);
    this.listener=listener;
    this.type=type;



    try {
        if(nameValuePairs!=null)
            request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }


@Override
protected HttpResponse doInBackground(String... params) {

    try {

        response = client.execute(request);
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){

        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return response;
}

@Override
protected void onPostExecute(HttpResponse result) {
            //if the response doesn't contain a json
    if(type.equals("mod_database")||type.equals("version")||type.equals("push")){
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        out = new ByteArrayOutputStream();
        try {
            response.getEntity().writeTo(out);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(listener!=null)
            listener.onTaskCompleted(out.toString(),type);
        return;
    }
        //the response contain a json
    ReadJson jsonR=new ReadJson(type);
    Object obj=jsonR.read(response);
    listener.onTaskCompleted(obj, type);    
}

}

StackTrace:

02-20 17:15:57.305: E/AndroidRuntime(13460): FATAL EXCEPTION: main
02-20 17:15:57.305: E/AndroidRuntime(13460): android.os.NetworkOnMainThreadException
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:220)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:183)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:155)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:175)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.entity.BasicHttpEntity.writeTo(BasicHttpEntity.java:129)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:101)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at org.apache.http.conn.BasicManagedEntity.writeTo(BasicManagedEntity.java:126)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:78)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:1)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask.finish(AsyncTask.java:631)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.os.Looper.loop(Looper.java:137)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at android.app.ActivityThread.main(ActivityThread.java:4856)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.lang.reflect.Method.invokeNative(Native Method)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at java.lang.reflect.Method.invoke(Method.java:511)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
02-20 17:15:57.305: E/AndroidRuntime(13460):    at dalvik.system.NativeStart.main(Native Method)
È stato utile?

Soluzione

FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException

at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:78)
at it.stepapp.clienti.PostRequest.onPostExecute(PostRequest.java:1)

Do not do network operations in onPostExecute() as that runs in the main thread.

Whatever you are doing at line 78 of PostRequest.java (you can identify that, we can't) is ultimately a network operation. You need to do that in the doInBackground() method instead.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top