1

I beginner in android development, getting error in following code. i am calling asyn method for http request.Its giving me java.lang.RuntimeException error occured while executing doInBackground()

private class PostAlert extends AsyncTask<String, Integer, JSONArray>{

    private ProgressDialog progressDialog;

    @Override
    protected JSONArray doInBackground(String... params) {
        // TODO Auto-generated method stub
        JSONArray menuitemArr = null;
        String url=params[0];

        System.out.println("fsfsddddf"+params[0]);
        ControlDashboard obj = new ControlDashboard();
        try{
        JSONObject aobj = obj.getJSONFromUrl(url);

            JSONObject array = aobj.getJSONObject("alert_list");    
             menuitemArr = array.getJSONArray("array");

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

        return menuitemArr;
    }

    @Override
    protected void onPostExecute(JSONArray menuitemArr) {
        // TODO Auto-generated method stub
        super.onPostExecute(menuitemArr);
        if (menuitemArr.length() == 0) {
            startActivity(new Intent("com.example.mysampleapp.ABOUT"));
            //Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
        }else{
        name = new String[menuitemArr.length()];
        alert = new String[menuitemArr.length()];
        date = new String[menuitemArr.length()];
        for (int i = 0; i < menuitemArr.length(); i++) { 
            // printing the values to the logcat 
            try {
                name[i] =  menuitemArr.getJSONObject(i).getString("name").toString();
                alert[i] = menuitemArr.getJSONObject(i).getString("message").toString(); 
                date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

        } 
        ListView list = (ListView) findViewById(R.id.listView3);
        ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
        String[] columnTags = new String[] {"col1", "col2", "col3"};
        int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
        for(int i=0; i<name.length; i++)
        {
         HashMap<String,String> map = new HashMap<String, String>();
             map.put("col1", name[i]);
             map.put("col2", alert[i]);
             map.put("col3", date[i]);
         mylistData.add(map);
        }
        SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
        list.setAdapter(arrayAdapter);      
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(Alert.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("please wait...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        //progressDialog.dismiss();
    }



}

Error when i run my android application.

12-17 13:22:48.035: W/dalvikvm(1160): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
12-17 13:22:48.045: E/AndroidRuntime(1160): FATAL EXCEPTION: AsyncTask #2
12-17 13:22:48.045: E/AndroidRuntime(1160): java.lang.RuntimeException: An error occured while executing doInBackground()
12-17 13:22:48.045: E/AndroidRuntime(1160):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-17 13:22:48.045: E/AndroidRuntime(1160):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)

json request class:

public class ControlDashboard extends Activity {
    public static DefaultHttpClient httpClient;

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            jObj = null;
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }



}
7
  • see my edit answer and just copy/past PostAlert class if still facing same issue Commented Dec 17, 2012 at 8:14
  • @ρяσѕρєя K not working for me :( Commented Dec 17, 2012 at 10:06
  • @ρяσѕρєя K i have updated the question have a look Commented Dec 17, 2012 at 10:11
  • my code looking fine post full latest logcat result.maybe you have some other issue and make sure you are getting json from server or not Commented Dec 17, 2012 at 10:13
  • @ρяσѕρєя K i have added a json request class have a look Commented Dec 17, 2012 at 10:16

2 Answers 2

3
 startActivity(new Intent("com.example.mysampleapp.ABOUT"));

or

   ListView list = (ListView) findViewById(R.id.listView3);

here you are trying to access UI elements from Background Thread means from AsyncTask doInBackground which is not possible

solution move all ui related code in onPostExecute for updating ui after doInBackground complete

you can see here how we update UI from onPostExecute after when doInBackground execution complete

EDIT : or just use this PostAlert AsyncTask class :

private class PostAlert extends AsyncTask<String, Integer, JSONArray>{

        private ProgressDialog progressDialog;

        @Override
        protected JSONArray doInBackground(String... params) {
            // TODO Auto-generated method stub
           JSONArray menuitemArr=null;
            String url=params[0];
            System.out.println("fsfsddddf"+url);

        //  System.out.println("fsfsddddfobj"+obj);
            try{

            JSONObject aobj = obj.getJSONFromUrl(url);
            System.out.println("fsfsf"+aobj);

                JSONObject array = aobj.getJSONObject("alert_list");    
                menuitemArr = array.getJSONArray("array");

            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       
            return menuitemArr;
        }

        @Override
        protected void onPostExecute(JSONArray menuitemArr) {
            // TODO Auto-generated method stub

                if (menuitemArr.length() == 0) {
                    startActivity(new Intent("com.example.mysampleapp.ABOUT"));
                    //Toast.makeText(Alert.this, "No Alerts", Toast.LENGTH_LONG).show();
                }else{
                name = new String[menuitemArr.length()];
                System.out.println("name"+name);
                alert = new String[menuitemArr.length()];
                date = new String[menuitemArr.length()];
                for (int i = 0; i < menuitemArr.length(); i++) { 
                    // printing the values to the logcat 
                    name[i] =  menuitemArr.getJSONObject(i).getString("name").toString(); 
                    alert[i] = menuitemArr.getJSONObject(i).getString("message").toString(); 
                    date[i] = menuitemArr.getJSONObject(i).getString("date").toString();
                } 
                ListView list = (ListView) findViewById(R.id.listView3);
                ArrayList<HashMap<String, String>> mylistData = new ArrayList<HashMap<String, String>>();
                String[] columnTags = new String[] {"col1", "col2", "col3"};
                int[] columnIds = new int[] {R.id.alert1, R.id.alert2, R.id.alert3};
                for(int i=0; i<name.length; i++)
                {
                 HashMap<String,String> map = new HashMap<String, String>();
                     map.put("col1", name[i]);
                     map.put("col2", alert[i]);
                     map.put("col3", date[i]);
                 mylistData.add(map);
                }
                SimpleAdapter arrayAdapter = new SimpleAdapter(Alert.this, mylistData, R.layout.alert_view,columnTags,columnIds);
                list.setAdapter(arrayAdapter);      
                } 
            }

            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progressDialog = new ProgressDialog(Alert.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("please wait...");
            progressDialog.setCancelable(false);
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(100);
            progressDialog.setProgress(0);
            progressDialog.show();
            System.out.println("fsgsgsg");
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            progressDialog.setProgress(values[0]);  
        }



    }
}

http://developer.android.com/reference/android/os/AsyncTask.html

Sign up to request clarification or add additional context in comments.

Comments

1

You are setting ListAdapter in Background which should not be done as it is UI thread task. Change your entire code in doInBackground() to onPostExecute() except for getJsonFromUrl(url). you can return the jsonobject from doInBackground() which you can get in onPostExecute() as result parameter. Still you get that runtime error in onPostExecute() too then you just right this line listview.setAdapter() in

runOnUIThread(new Runnable(){
public void run()
{

}
});

I hope its clear and it will work for you.

1 Comment

@user1841413 write entire doInBackground() code in try and catch with Exception. print the stack trace e and find out what kind of exception you are getting. and also check once you gave Internet permission in manifest file that might be the reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.