自定义适配器java.lang.NullPointerException onPostExecute

时间:2013-03-28 13:52:11

标签: android list listview ui-thread custom-adapter

我有一个应用程序,它从数据库中检索数据并使用CustomListView显示它。当应用程序要显示ListView时,它会使用此日志崩溃:

    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)

这是我遇到问题的活动:

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);
                }
            });

        }



    }


} 

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;

    }



}

我已经在Google上搜索过,如果你需要展示视觉对象,必须使用UI线程,但我不知道出了什么问题。

1 个答案:

答案 0 :(得分:1)

首先,不需要显式调用runOnUiThread(),因为onPostExecute()已经与UI线程同步。

然后我认为你在这一行得到 NPE

Context context = getApplicationContext();

将上下文分配给 NULL 。由于您的AsyncTask是Activity类的内部类,因此您无需调用getApplicationContext()。你不应该在其他情况下调用它有更好的方法。 Activity从Context扩展,因此您只需使用返回Context的 ActivityName.this

所以用这一行改变你的:

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

现在它应该有效。让我知道。

更新

  

按照您的建议完成,NPE现在位于lv.setAdapter(适配器)

现在,您的ListView很可能已分配到 NULL 。我认为你应该在执行AsyncTask之前初始化它:

lv = (ListView)findViewById(R.id.listView1);
new LoadAllProducts().execute();