1

我正在开发一个 android 应用程序,但我不明白为什么我一直在这个类中得到一个空指针异常。我有一个列表视图和一个基本适配器,我认为我的代码是正确的,但显然不是。我需要帮助来解决这个问题,并将感谢所有提供的帮助。下面是 logcat 错误和 java 代码。

10-20 00:17:39.342: E/AndroidRuntime(24078): FATAL EXCEPTION: AsyncTask #1
10-20 00:17:39.342: E/AndroidRuntime(24078): java.lang.RuntimeException: An error occured while executing doInBackground()
10-20 00:17:39.342: E/AndroidRuntime(24078):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.lang.Thread.run(Thread.java:864)
10-20 00:17:39.342: E/AndroidRuntime(24078): Caused by: java.lang.NullPointerException
10-20 00:17:39.342: E/AndroidRuntime(24078):    at **com.creation.joopn.VListActivity$LoadVenues.doInBackground(VListActivity.java:150)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at com.creation.joopn.VListActivity$LoadVenues.doInBackground(VListActivity.java:1)**
10-20 00:17:39.342: E/AndroidRuntime(24078):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-20 00:17:39.342: E/AndroidRuntime(24078):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

班级

public class VListActivity extends Activity {

    TextView name;
    String my_id, my_type;
    ListView list;
    VListAdapter adapter;

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> venueList;

    // url to get all products list
    private static String Venue_URL = "http://www.createinv.com/list/myVenues.php";

    // JSON Node names
    static final String TAG_SUCCESS = "success";
    static final String KEY_VENUES = "venues";
    static final String KEY_ID = "venue_id";
    static final String KEY_NAME = "venue_name";
    static final String KEY_ADDRESS = "street";
    static final String KEY_CITY = "city";
    static final String KEY_STATE = "state";
    static final String KEY_ZIP = "zip";
    static final String KEY_NUMBER = "phone_number";
    static final String KEY_BIO = "bio";

    JSONArray venues = null;

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

        SharedPreferences sp = 
                PreferenceManager.getDefaultSharedPreferences(this);

        my_id = sp.getString("my_id", null);
        my_type = sp.getString("my_type", null);

        new LoadVenues().execute(); 
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    class LoadVenues extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(VListActivity.this);
            pDialog.setMessage("Loading Venues. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("my_id", my_id));
            params.add(new BasicNameValuePair("my_type", my_type));
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(Venue_URL, "POST", params);

            // Check your log cat for JSON reponse
            Log.d("Venues: ", json.toString());

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

                if (success == 1) {
                    // products found
                    // Getting Array of venues
                    venues = json.getJSONArray(KEY_VENUES);

                    // looping through All venues
                    venueList = new ArrayList<HashMap<String, String>>();

                    for (int i = 0; i < venues.length(); i++) {

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject c = venues.getJSONObject(i);

                        // adding each child node to HashMap key => value
                        map.put(KEY_ID, c.getString(KEY_ID));
                        map.put(KEY_NAME, c.getString(KEY_NAME));
                        map.put(KEY_ADDRESS, c.getString(KEY_ADDRESS));
                        map.put(KEY_CITY, c.getString(KEY_CITY).concat(", "));
                        map.put(KEY_STATE, c.getString(KEY_STATE));
                        map.put(KEY_ZIP, c.getString(KEY_ZIP));
                        map.put(KEY_NUMBER, c.getString(KEY_NUMBER));

                        // adding HashList to ArrayList
                        venueList.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) { 
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    adapter = new VListAdapter(VListActivity.this, venueList);
                    list = (ListView)findViewById(R.id.list);
                    list.setAdapter(adapter);       
                }
            });
        }
    }

    public class VListAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        private Context context;

        public VListAdapter(Context context, ArrayList<HashMap<String,String>> venueList){

            inflater = LayoutInflater.from(context);
            this.context = context;
        }

        public int getCount() {
            return venueList.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            View vi=convertView;
            if(convertView==null)
                vi = inflater.inflate(R.layout.activity_homelist, null);

            TextView venue_id = (TextView)vi.findViewById(R.id.venue_id);
            TextView name = (TextView)vi.findViewById(R.id.name);
            TextView address = (TextView)vi.findViewById(R.id.address1);
            TextView city = (TextView)vi.findViewById(R.id.city);
            TextView state = (TextView)vi.findViewById(R.id.state);
            TextView zip = (TextView)vi.findViewById(R.id.zip);
            TextView number = (TextView)vi.findViewById(R.id.phnumber);

            HashMap<String, String> vlist = new HashMap<String, String>();
            vlist = venueList.get(position);

            // Setting all values in listview
            venue_id.setText(vlist.get(VListActivity.KEY_ID));
            name.setText(vlist.get(VListActivity.KEY_NAME));
            name.setOnClickListener(new myOnClickListener(position));
            address.setText(vlist.get(VListActivity.KEY_ADDRESS));
            city.setText(vlist.get(VListActivity.KEY_CITY));
            state.setText(vlist.get(VListActivity.KEY_STATE));
            zip.setText(vlist.get(VListActivity.KEY_ZIP));
            number.setText(vlist.get(VListActivity.KEY_NUMBER));

            return vi;
        }

        public class myOnClickListener implements OnClickListener{
            private int position;
            public myOnClickListener(int position){
                this.position=position;
            }
            @Override
            public void onClick(View v) {

                HashMap<String, String> update = new HashMap<String, String>();
                update = venueList.get(position); 
                Log.d("Testing Click", update.get(VListActivity.KEY_ID));

                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(VListActivity.this);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("venue_id", update.get(VListActivity.KEY_ID));
                edit.commit();

                Intent in = new Intent(VListActivity.this, VenueProfileActivity.class); 
                startActivity(in);
            }
        }
    }
4

1 回答 1

1

ListView将您的文件更改layout为如下所示

<ListView android:id="@+id/list" <!-- change the id like this -->
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:divider="#dddddd" 
    android:dividerHeight="1dp" > </ListView> 

如果您正在扩展,您拥有它的方式会起作用,ListActivity但由于您只是在扩展,Activity您不需要声明id那种方式。你只是给它你自己的id

最初的问题似乎只需要使用“Project --> Clean ...”来清理项目,然后再次运行项目,因为NPE给定的代码没有意义。此外,runOnUiThread不需要也不应该使用,onPostExecute()因为该方法已经在UI Thread.

于 2013-10-20T04:56:32.673 回答