Shruti
Shruti

Reputation: 5591

Handle threads on Android UI

In my application I want to check the network status on device,If no network connectivity is detected on device the i want to show a toast saying no network connection and then exit the application.And if the connection is detected on device then i have to load a list from webservice and display it on screen

I have done following code in onCreate function of application.It is running on emulator but not on real device.The reason for this to showANR on device is i am trying to handle so many threads on UI which is not appreciated in android.Please guide me how to do this using AsyncTask.

any code snippet or link to tutorial or suggestions will be helpful to me

boolean connected = false;
            ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
            connected = networkinfo != null && networkinfo.isAvailable()
                    && networkinfo.isConnected();
            Log.v("Message ", connected + "");
            Log.v("Message ", networkinfo.getReason());
            //Toast.makeText(CategoryActivity.this, connected + "", 2000).show();
            //connected = false;
            Log.v("Message 1", connected + "");
            if (connected == false) {
                CategoryActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // Log.v("Message ", connected + "");
                        Toast.makeText(CategoryActivity.this,
                                "No Internet Connection detected on device", 3000).show();
                    }
                });
                Handler handler1 = new Handler();
                handler1.postDelayed(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        finish();
                        System.exit(0);
                    }
                }), 4000);
            } else {
                CategoryArray = new JSONArray();
                final ProgressDialog pd = ProgressDialog.show(
                        CategoryActivity.this, "", "Loading...", false, true);
                pd.setIcon(getResources().getDrawable(R.drawable.icon));
                new Thread() {
                    public void run() {
                        try {
                            sleep(5000);
                            // Log.v("TAG","in try block");
                        } catch (Exception e) {
                            // Log.e("tag", e.getMessage());
                        }
                        pd.dismiss();
                        // Log.v("TAG","progress dismiss");
                    }
                }.start();

                handler.postDelayed(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        CategoryArray = CW
                                .getCategory("http://www.balajeebazaar.com/RestServiceImpl.svc/categorydetails");
                        // TODO: handle exception

                        for (int i = 0; i <= CategoryArray.length() - 1; i++) {
                            try {
                                String[] val = new String[3];
                                Log.v("category array : ",
                                        CategoryArray.getString(i));
                                val = CategoryArray.getString(i).split(",");
                                CategoryID.add(i, val[0]);
                                CategoryList.add(i, val[1]);
                                val = null;
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        adapter = new CategoryListAdapter(CategoryActivity.this,
                                CategoryList);
                        list.setAdapter(adapter);
                    }
                }), 5000);

Thanks

EDIT

ERROR/AndroidRuntime(5486): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception

ERROR/AndroidRuntime(5486): java.lang.RuntimeException: An error occured while executing doInBackground()

ERROR/AndroidRuntime(5486):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
ERROR/AndroidRuntime(5486):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:234)
ERROR/AndroidRuntime(5486):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:258)
ERROR/AndroidRuntime(5486):     at java.util.concurrent.FutureTask.run(FutureTask.java:122)
ERROR/AndroidRuntime(5486):     at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
ERROR/AndroidRuntime(5486):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
ERROR/AndroidRuntime(5486):     at java.lang.Thread.run(Thread.java:1060)
ERROR/AndroidRuntime(5486): Caused by: java.lang.ArrayIndexOutOfBoundsException
ERROR/AndroidRuntime(5486):     at com.ecommerce.balajeebazaar.CategoryActivity$Loader.doInBackground(CategoryActivity.java:181)
ERROR/AndroidRuntime(5486):     at com.ecommerce.balajeebazaar.CategoryActivity$Loader.doInBackground(CategoryActivity.java:1)
ERROR/AndroidRuntime(5486):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-18 18:30:07.582: ERROR/AndroidRuntime(5486): 
                        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
ERROR/AndroidRuntime(5486):     4 more

Upvotes: 0

Views: 1462

Answers (3)

kaspermoerch
kaspermoerch

Reputation: 16580

I suggest you read up on the AsyncTask yourself before applying the solution I have posted below, in order to better understand what is going on.

This is what you need in your Activity (it must replace all the code you posted):

    boolean connected = false;
    ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
    connected = networkinfo != null && networkinfo.isAvailable()
            && networkinfo.isConnected();
    Log.v("Message ", connected + "");
    Log.v("Message ", networkinfo.getReason());
    //Toast.makeText(CategoryActivity.this, connected + "", 2000).show();
    //connected = false;
    Log.v("Message 1", connected + "");
    if (connected == false) {
      Toast.makeText(CategoryActivity.this, "No Internet Connection detected on device", Toast.LENGTH_LONG ).show();
      finish();
    } else {
      new Loader().execute();
    }

This is the AsyncTask which should be an inner class of your Activity:

    private class Loader extends AsyncTask<Void, Void, Void> {
      final ProgressDialog pd;

      @Override
      protected void onPreExecute() {
        pd = ProgressDialog.show( CategoryActivity.this, "", "Loading...", false, true);
        pd.setIcon(getResources().getDrawable(R.drawable.icon));
        super.onPreExecute();
      }

      @Override
      protected Void doInBackground( Void... arg0 ) {
        CategoryArray = new JSONArray();
        CategoryArray = CW.getCategory("http://www.balajeebazaar.com/RestServiceImpl.svc/categorydetails");

        for (int i = 0; i <= CategoryArray.length() - 1; i++) {
          try {
              String[] val = new String[3];
              Log.v("category array : ", CategoryArray.getString(i));
              val = CategoryArray.getString(i).split(",");
              CategoryID.add(i, val[0]);
              CategoryList.add(i, val[1]);
              val = null;
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }

        adapter = new CategoryListAdapter(CategoryActivity.this, CategoryList);

        return null;
      }


      @Override
      protected void onPostExecute( Void result ) {
        pd.dismiss();
        list.setAdapter(adapter);
        super.onPostExecute( result );
      }
    }

Note

I wasn't able to check if the above actually works - but it should put you on the right track.

Upvotes: 1

Jonathan Schneider
Jonathan Schneider

Reputation: 27777

You don't necessarily need an AsyncTask, you can use regular Java threading to accomplish what you need (far easier for a background task like this).

Upvotes: 0

hovanessyan
hovanessyan

Reputation: 31493

A nice tutorial on AsyncTasks and Handlers.

In really short, the idea of AsyncTask - you make a private class which extends AsyncTask in your Activity. Doing this, you automatically get access to this Activities UI Thread from the AsyncTask class.

In AsyncTaks there are a couple of methods you should pay attention to. They are explained here.

What you should know is that only doInBackground() is executed in a separate Thread. Everything else is invoked on the UI thread of the Activity, where your AsyncTask is defined.

Simple scenario:

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
     // stuff
   new MyAsyncTask().execute(); //this should be invoked only once
   }

   private class MyAsyncTask() extends AsyncTask<Void, Void, <TypeOfResult Or Void>> {

    @Override //executed on the UI thread of MyActivity
    protected void onPreExecute() {
        super.onPreExecute();
                   //prepare some stuff
            }

    @Override //executed in a separate Thread. This thread is automatically handled by AsyncTask
    protected <TypeOfResult or Void> doInBackground(Void... params) {

        //long operation
    }

            @Override //executed on the UI thread of MyActivity
    protected void onPostExecute(<TypeOf Result Or Void>) {
        super.onPostExecute(result);
                        // do stuff with result from long operation
    }
   }
}

Upvotes: 0

Related Questions