0

I have a an application which retrieves data from a database and displays it with a CustomListView. When the app is going to show the ListView it crashes with this log:

    03-28 13:22:16.963: E/AndroidRuntime(853): java.lang.NullPointerException
03-28 13:22:16.963: E/AndroidRuntime(853):  at com.gabriele.tesina.Leggi_Pizzaiolo$LoadAllProducts$1.run(Leggi_Pizzaiolo.java:162)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.app.Activity.runOnUiThread(Activity.java:4644)
03-28 13:22:16.963: E/AndroidRuntime(853):  at com.gabriele.tesina.Leggi_Pizzaiolo$LoadAllProducts.onPostExecute(Leggi_Pizzaiolo.java:156)
03-28 13:22:16.963: E/AndroidRuntime(853):  at com.gabriele.tesina.Leggi_Pizzaiolo$LoadAllProducts.onPostExecute(Leggi_Pizzaiolo.java:1)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.os.AsyncTask.finish(AsyncTask.java:631)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.os.Looper.loop(Looper.java:137)
03-28 13:22:16.963: E/AndroidRuntime(853):  at android.app.ActivityThread.main(ActivityThread.java:5039)
03-28 13:22:16.963: E/AndroidRuntime(853):  at java.lang.reflect.Method.invokeNative(Native Method)
03-28 13:22:16.963: E/AndroidRuntime(853):  at java.lang.reflect.Method.invoke(Method.java:511)
03-28 13:22:16.963: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-28 13:22:16.963: E/AndroidRuntime(853):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-28 13:22:16.963: E/AndroidRuntime(853):  at dalvik.system.NativeStart.main(Native Method)

This is the activity where I have the problem:

public class Leggi_Pizzaiolo extends Activity
{
    // Progress Dialog
    private ProgressDialog pDialog;
    public List list = new LinkedList();
    // 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/tesina/Leggi_Pizzaiolo.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "Esito";
    private static final String TAG_PRODUCTS = "comande";
    private static final String TAG_PID = "ID";
    private static final String TAG_NAME = "Nome";
    private static final String TAG_TABLE = "Tavolo";
    public ListView lv;
    // products JSONArray
    JSONArray products = null;

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

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

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

        // Get listview
        lv = (ListView)findViewById(R.id.listView1);

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> 
    {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Leggi_Pizzaiolo.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        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
                    products = json.getJSONArray(TAG_PRODUCTS);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        int Tavolo= c.getInt(TAG_TABLE);

                        list.add(new Comanda(name, id, Tavolo));

                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            Listino.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } 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 listview
            runOnUiThread(new Runnable() 
            {
                public void run() 
                {
                    Context context = getApplicationContext();
                    ComandaCursorAdapter adapter = new ComandaCursorAdapter(context, R.layout.comanda_cuoco, list);
                    lv.setAdapter(adapter);
                }
            });

        }



    }


} 

And the CustomAdapter Comanda:

public class ComandaCursorAdapter extends ArrayAdapter<Comanda>
{

    public ComandaCursorAdapter(Context context, int comandaCuoco, List list) {
        super(context, comandaCuoco, list);
        // TODO Auto-generated constructor stub
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.comanda_cuoco, null);

        TextView Nome = (TextView)convertView.findViewById(R.id.Comanda);
        TextView Tavolo = (TextView)convertView.findViewById(R.id.Tavolo);
        TextView Codice = (TextView)convertView.findViewById(R.id.Codice);

        Comanda c = getItem(position);

        Nome.setText(c.getNome());
        Tavolo.setText(c.getTavolo());
        Codice.setText(c.getCodice());

        return convertView;

    }



}

I've searched on Google and UI Thread is necessary if you need to show visive objects, but I don't know what is wrong.

Eulante
  • 309
  • 2
  • 4
  • 15

1 Answers1

1

At first there is no need to explicit call runOnUiThread() because onPostExecute() is already synchronized with UI Thread.

Then i think you are getting NPE at this line:

Context context = getApplicationContext();

where context is assigned to NULL. Since your AsyncTask is inner class of your Activity class you don't need to call getApplicationContext(). You shouldn't call it also in other cases there are better ways. Activity extends from Context so you can simply use ActivityName.this that returns Context.

So change yours with this line:

new ComandaCursorAdapter(Leggi_Pizzaiolo.this, R.layout.comanda_cuoco, list);

and now it should works. Let me know.

Update:

Done as you suggested, the NPE now is on lv.setAdapter(adapter)

Now, most likely your ListView is assigned to NULL. I think you should initialise it before you are executing AsyncTask:

lv = (ListView)findViewById(R.id.listView1);
new LoadAllProducts().execute();
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • Done as you suggested, the NPE now is on lv.setAdapter(adapter). I don't know why. – Eulante Mar 28 '13 at 14:02
  • Solved. I had to adjust other things related to the textView and now it works! Thank you so much sir. Ps: can I mail you to talk about android devolping? Thank you. – Eulante Mar 28 '13 at 14:25
  • @Eulante you are welcome. So... you can but now i have not much time to talking about but if it will be a small issue and if i will have a time(now i have to work on app for my bachelor thesis where some functionality is a little hardcore) so i try to reply :) – Simon Dorociak Mar 28 '13 at 14:34
  • No just some mail exchange about issue related to the Android Dev world! Feel free to reply when you have time and if you want :) – Eulante Mar 28 '13 at 14:36