gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:36:59 27 4
gpt4 key购买 nike

我正在尝试删除 ListView 中的项目,但不断收到 ArrayOutOfBoundException 但我的日志显示从我的本地主机成功删除,如果您重新打开它,它会反射(reflect)更改...

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

具有异步任务的类:

  @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
}


}

}

日志:删除成功但仍然出错?

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$3.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$1.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$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.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

第二个任务是在不同的线程中完成的,并设法在第一个任务的异常传递回调用堆栈之前完成,这就是它仍然“有效”的原因。

关于java - 应用程序崩溃但方法仍然有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29869527/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com