sheetal
sheetal

Reputation: 199

Fatal Exception:Async Task #1

I am trying to get data from mysql database and load it into listview ,but not able to do it because the app crashes after the progress dialog appears.The logcat shows error as An error occured while executing doInBackground().Please help me,this is my java file

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import org.apache.http.NameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

     public class CompScience extends ListActivity{

  // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://10.0.2.2/books/get_all_books.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "computerscience";
    private static final String TAG_PID = "bid";
    private static final String TAG_NAME = "title";
    private static final String TAG_DESCRIPTION = "author";

    // products JSONArray
    JSONArray computerscience = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comp_science);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();
        // on seleting single product
        // launching  Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                //String description = ((TextView) view).getText().toString();
                Intent i = new Intent(CompScience.this,List1.class);
            //  i.putExtra("description", description);


                startActivity(i);
            }

        });
    }


     class LoadAllProducts extends AsyncTask<String, String, String> {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(CompScience.this);
                    pDialog.setMessage("Loading...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
                protected String doInBackground(String... args) {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    // getting JSON string from URL
                    JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
                    // Check your log cat for JSON reponse
                    Log.d("All Products: ", json.toString());

                    try {
                        // Checking for SUCCESS TAG
                        int success = json.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            // products found
                            // Getting Array of Products
                            computerscience = json.getJSONArray(TAG_PRODUCTS);

                            // looping through All Products
                            for (int i = 0; i < computerscience.length(); i++) {
                                JSONObject c = computerscience.getJSONObject(i);

                                // Storing each json item in variable
                                String id = c.getString(TAG_PID);
                                String name = c.getString(TAG_NAME);
                                String description = c.getString(TAG_DESCRIPTION);

                                // creating new HashMap
                                HashMap<String, String> map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(TAG_PID, id);
                                map.put(TAG_NAME, name);
                                map.put(TAG_DESCRIPTION, description);

                                // adding HashList to ArrayList
                                productsList.add(map);
                            }
                        } else {
                            Log.e(TAG_PRODUCTS, "No products found");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    return null;
                }

                /**
                 * After completing background task Dismiss the progress dialog
                 * **/
                protected void onPostExecute(String file_url) {
                    // dismiss the dialog after getting all products
                pDialog.dismiss();
                    // updating UI from Background Thread
                    runOnUiThread(new Runnable() {
                        public void run() {
                            /**
                             * Updating parsed JSON data into ListView
                             * */
                            ListAdapter adapter = new SimpleAdapter(
                                    CompScience.this, productsList,
                                    R.layout.list_item, new String[] { TAG_PID,
                                            TAG_NAME,TAG_DESCRIPTION},
                                    new int[] { R.id.bid, R.id.title,R.id.author });
                            // updating listview
                            setListAdapter(adapter);
                        }
                    });

                }



            }

This is the logcat

    04-08 02:59:40.928: E/AndroidRuntime(2224): FATAL EXCEPTION: AsyncTask #1
    04-08 02:59:40.928: E/AndroidRuntime(2224): java.lang.RuntimeException: An error occured while executing doInBackground()
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.lang.Thread.run(Thread.java:841)
    04-08 02:59:40.928: E/AndroidRuntime(2224): Caused by: java.lang.NullPointerException
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:94)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at com.example.dashboard.CompScience$LoadAllProducts.doInBackground(CompScience.java:1)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    04-08 02:59:40.928: E/AndroidRuntime(2224):     ... 3 more

Browser response:

    {
    "computerscience": [
        {
            "bid": "1",
            "title": "Electronic Principles",
            "author": "Albert Malvino & David J Bates"
        },
        {
            "bid": "2",
            "title": "Electronic Circuits",
            "author": "RD Sudhakar"
        },
        {
            "bid": "3",
            "title": "Digital Principles & Applications",
            "author": "Leach, Malvino, Saha"
        }
    ],
    "success": 1
}

Upvotes: 1

Views: 134

Answers (3)

Pphoenix
Pphoenix

Reputation: 1473

You have a NullpointerException at line 94:

Log.d("All Products: ", json.toString());

This means that the object json is equal to null (nothing) and trying to call a method from an object that is nothing will throw an error. Check why jParser.makeHttpRequest(url_all_products, "GET", params); returns null, maybe a parameter is wrong? When it returns a valid result the AsyncTask won't fail again :)

Upvotes: 1

YasirSE
YasirSE

Reputation: 161

Please look at your doinbackground method, you are writing

 List<NameValuePair> params = new ArrayList<NameValuePair>();
                    // getting JSON string from URL
                    JSONObject json = jParser.makeHttpRequest(url_all_products,  "GET",params);

Where params are only declared , No params is defined. It all depends on how you are sending params with request in jParser.makeHttpRequest method. I think if this request need params then define some params, or send empty string if no params required. Thanks

Upvotes: 0

Waseem Arain
Waseem Arain

Reputation: 1177

Try That:

List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        params.add(new BasicNameValuePair(TAG_APPID, appID));
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
                params);
        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

There pas your required parametrs:

params.add(new BasicNameValuePair(TAG_APPID, appID));

From: How to connect Android with PHP, MySQL

Upvotes: 1

Related Questions