应用程序崩溃但方法仍然有效?

App Crashes But Method Still Works?

我正在尝试删除列表视图中的项目,但一直收到 ArrayOutOfBoundException,但我的日志显示从我的 Localhost 中成功删除,如果您打开它,它会反映更改...

不确定如何修复导致我的应用程序崩溃的异常?有什么想法吗?

Class 异步任务:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_all_locations);
        // Hashmap for ListView
        profileList = new ArrayList<HashMap<String, String>>();

        deleteLocation = (Button) findViewById(R.id.deleteLocation);
        locationCount = (TextView) findViewById(R.id.locationCount);
        lo = (ListView) findViewById(android.R.id.list);

        //setup adapter first //now no items, after getting items (LoadAllLocations) will update it
        adapter = new SimpleAdapter(
                ViewAllLocations.this, profileList,
                R.layout.locationitem, new String[]{TAG_ID,
                TAG_LATITUDE, TAG_LONGITUDE},
                new int[]{R.id.id, R.id.latitude, R.id.longitude});

        // updating listview
        setListAdapter(adapter);

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

        // getting product details from intent
        Intent i = getIntent();

        // getting product id (pid) from intent
        id = i.getStringExtra(TAG_ID);

        // Get listview
        ListView lo = getListView();

        lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                new DeleteLocation(position).execute();
                Map<String, String> item = profileList.get(position);
                String selectedItemId = item.get(TAG_ID);
                new DeleteLocation(position).execute(selectedItemId);

            }
        });

    }

    /**
     * **************************************************************
     * Background Async Task to Delete Product
     */
    class DeleteLocation extends AsyncTask<String, String, Integer> {

        int deleteItemPosition;

        public DeleteLocation(int position) {
// TODO Auto-generated constructor stub
            this.deleteItemPosition = position;
        }

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //pDialog = new ProgressDialog(ViewAllLocations.this);
            //pDialog.setMessage("Deleting Location...");
            //pDialog.setIndeterminate(false);
            //pDialog.setCancelable(true);
//            pDialog.show();
        }

        /**
         * Deleting product
         */
        protected Integer doInBackground(String... args) {

            String selectedId = args[0];

            // Check for success tag
            int success = 0; //0=failed 1=success
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", selectedId));

                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(
                        url_delete_profile, "POST", params);

                // check your log for json response
                Log.d("Delete Product", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                //if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                // Intent i = getIntent();
                // send result code 100 to notify about product deletion
                //setResult(100, i);

                //you cant update UI on worker thread, it must be done on UI thread
                // Toast.makeText(getApplicationContext(), "Location Deleted",
                // Toast.LENGTH_SHORT).show();
                //finish();
                // }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return success;
        }


        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(Integer result) {
            // dismiss the dialog once product deleted

            if (result == 1) {
                    //success
                   //delete from list and update listview
                profileList.remove(deleteItemPosition);
                adapter.notifyDataSetChanged();
                //pDialog.dismiss();
            } else {
            //failed
            }

        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllLocation extends AsyncTask<String, String, Integer> {
        int success;

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

        /**
         * getting All products from url
         */
        protected Integer doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_all_profile, "GET", params);

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

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

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

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String latitude = c.getString(TAG_LATITUDE);
                        String longitude = c.getString(TAG_LONGITUDE);


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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_LATITUDE, latitude);
                        map.put(TAG_LONGITUDE, longitude);


                        // adding HashList to ArrayList
                        profileList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                    // UserLocation.class);
                    // Closing all previous activities
                    // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    // startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return success;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(Integer result) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            locationCount.setText("" + profileList.size());
            if (result == 1) {
            //success
            //update adapter items
                adapter.notifyDataSetChanged();
            } else {
            //failed
            //launch activity here
            }


        }

    }

LOG:删除成功但还是报错?

04-25 20:08:32.463  22736-23492/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:856)
     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
            at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:144)
            at com.example.ankhit.saveme.ViewAllLocations$DeleteLocation.doInBackground(ViewAllLocations.java:117)
            at android.os.AsyncTask.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:856)
04-25 20:08:32.713  22736-22736/com.example.ankhit.saveme D/AbsListView﹕ unregisterIRListener() is called
04-25 20:08:32.733  22736-23498/com.example.ankhit.saveme D/Delete Product﹕ {"message":"Profile successfully deleted","success":1}

您的问题来自这里

new DeleteLocation(position).execute();
Map<String, String> item = profileList.get(position);
String selectedItemId = item.get(TAG_ID);
new DeleteLocation(position).execute(selectedItemId);

你是运行两个独立的任务,但只有第二个任务被赋予了一个参数。因此,第一个任务

new DeleteLocation(position).execute();

抛出异常,这里

protected Integer doInBackground(String... args) {
    String selectedId = args[0];
    ...
}

args[0] 越界,因为没有参数传递给 execute

第二个任务在不同的线程中完成,并设法在第一个任务的异常返回调用堆栈之前完成,这就是为什么它仍然 "works".