Search code examples
androidmultithreadinghttpconnection

NetworkConnection on Main Thread and Validation


I am warned not to use network operations on main thread.

But i have such a case;

I need to check the value whether it is exist on the database or not,

if yes i will proceed to another activity.

But i am taking an exception. Pls help me to solve this My updated code

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.initial);




    if(!isNetworkAvailable())
    {
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.customlayoutnetconnection);

        Button dialogButton = (Button) dialog.findViewById(R.id.Ok);
        Button dialogButton2 = (Button) dialog.findViewById(R.id.OpenCon);


        dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
                finish();
            }});

        dialogButton2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                ConnectivityManager manager = (ConnectivityManager)getSystemService(InitialActivity.CONNECTIVITY_SERVICE);


                Boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();


                Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

                if(is3g){
                    Toast.makeText(context, "3G", Toast.LENGTH_LONG);
                }else if(isWifi){
                    Toast.makeText(context, "wifi", Toast.LENGTH_LONG);
                }else{
                    Toast.makeText(context, "nothing", Toast.LENGTH_LONG);

                    startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }

            }});
        dialog.show();
    }


    lost = (Button) findViewById(R.id.imlost);
    lost.setOnClickListener(this);

    looking = (Button) findViewById(R.id.imlookingfor);
    looking.setOnClickListener(this);

    about = (Button) findViewById(R.id.about);
    about.setOnClickListener(this);

    howto = (Button) findViewById(R.id.howto);
    howto.setOnClickListener(this);



}




@Override
public void onClick(View v) {


    if(v==lost)
    {

        Intent i = new Intent(getApplicationContext(),IamLostActivity.class);


        startActivity(i);
    }

    else if(v==looking)
    {
        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.customlayout);

        Button dialogButton = (Button) dialog.findViewById(R.id.Find);

        code  = (EditText) dialog.findViewById(R.id.codeToFind);

        code.requestFocus();

        dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                if(code.getText().toString().contentEquals(""))
                {

                    final Dialog dialog2 = new Dialog(context);
                    dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog2.setContentView(R.layout.customlayoutinfo);

                    TextView tv = (TextView) dialog2.findViewById(R.id.customInfo);

                    tv.setText(context.getString(R.string.BlankField));

                    Button dialogButton2 = (Button) dialog2.findViewById(R.id.Ok);

                    dialogButton2.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            dialog2.dismiss();

                            } }); 
                        dialog2.show();
                }


                else 
                {

                    findFriend = new Runnable() {
                        @Override
                        public void run() {

                            httpclnt = new DefaultHttpClient();

                            httppst = new HttpPost(url);

                            try {   

                                nameValuePairs = new ArrayList<NameValuePair>(1);
                                nameValuePairs.add((new BasicNameValuePair("code", code.getText().toString())));

                                httppst.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                                ResponseHandler<String> responseHandler = new BasicResponseHandler();

                                response = httpclnt.execute(httppst, responseHandler);

                                //message = response;
                            }
                            catch (ClientProtocolException e) {
                                Toast.makeText(InitialActivity.this, "Client protocol exception ", Toast.LENGTH_LONG).show();
                            } catch (IOException e) {
                                Toast.makeText(InitialActivity.this, "IO exception "+e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                       }

                    };

                    Thread thread = new Thread(null, findFriend, "FindFriend");
                    thread.start();

                                if(response.contentEquals(","))
                                {


                                    final Dialog dialog4 = new Dialog(context);
                                    dialog4.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                    dialog4.setContentView(R.layout.customlayoutinfo);

                                    TextView tv = (TextView) dialog4.findViewById(R.id.customInfo);

                                    tv.setText(context.getString(R.string.CheckCorrectness));

                                    Button dialogButton2 = (Button) dialog4.findViewById(R.id.Ok);

                                    dialogButton2.setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                            dialog4.dismiss();

                                            } }); 
                                        dialog4.show();
                                }
                                else
                                {
                                    Intent in = new Intent(getApplicationContext(),IamLookingForActivity.class);

                                    in.putExtra("message", response.toString());

                                    startActivity(in);
                                }

                    };

}

            }
        );



        Button dialogButton2 = (Button) dialog.findViewById(R.id.Cancel);
        dialogButton2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
      }

    else if(v==about)
    {
         final Dialog dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.customlayoutabout);

            ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.kodatolye);

            Button dialogButton2 = (Button) dialog.findViewById(R.id.Back);

            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    final Dialog dialog2 = new Dialog(context);
                    dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog2.setContentView(R.layout.customlayoutinfo);

                    TextView tv = (TextView) dialog2.findViewById(R.id.customInfo);

                    tv.setText("www.kodatolye.com");
                    Button dialogButton3 = (Button) dialog2.findViewById(R.id.Ok);


                    dialogButton3.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            dialog2.dismiss();


                            } }); 
                    dialog2.show();

                    } }); 

            dialogButton2.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    dialog.dismiss();

                    } }); 
                dialog.show();

    }
    else if(v==howto)
    {


        final Dialog dialog2 = new Dialog(context);
        dialog2.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog2.setContentView(R.layout.customlayouthowto);


        Button dialogButton3 = (Button) dialog2.findViewById(R.id.Back);



        dialogButton3.setOnClickListener(new OnClickListener() {
            @Override
        public void onClick(View v) {

                dialog2.dismiss();

            } }); 
        dialog2.show();

    }
}



}

Solution

  • You must not execute networking code on the main thread. Likewise, you must not try to update the UI from anything other than the main thread. You are (correctly) starting a separate thread for the networking operation, but you aren't waiting for it to finish. You should move the code that starts if(response.contentEquals(...)) into a Runnable that is not run until the networking activity is complete and you have a response. You can then post the Runnable to the main thread through a Handler to start the new activity (or display an error message, as appropriate). You might want to display a dialog telling the user to wait before starting the networking thread.

    An AsyncTask does most of this bookkeeping work for you, making it all a bit easier. See the blog post Painless Threading for more info.