0

我有一个应用程序,它从数据库中检索数据并使用 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 Thread 是必要的,但我不知道出了什么问题。

4

1 回答 1

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(adapter)

现在,很可能您的 ListView 已分配给NULL. 我认为您应该在执行 AsyncTask 之前对其进行初始化:

lv = (ListView)findViewById(R.id.listView1);
new LoadAllProducts().execute();
于 2013-03-28T13:55:49.180 回答