我正在尝试通过单击ListView中的对象触发的另一个活动从列表中删除对象,但即使删除成功,我似乎也无法更新ListView。
使用ListView的活动:
public class YourList extends AppCompatActivity {
String name;
String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_list);
Bundle intent = getIntent().getExtras();
token = intent.getString("tokenID");
name = intent.getString("nameIDagain");
TextView welcome = (TextView) findViewById(R.id.welcomeListText);
welcome.setText("Welcome to your list, " + name);
System.out.println(token);
}
@Override
protected void onStart() {
super.onStart();
ReadTask task = new ReadTask();
task.execute("http://api.evang.dk/v2/catches?token=" + token);
}
private class ReadTask extends ReadHttpTask {
@Override
protected void onPostExecute(CharSequence charSequence) {
List<Catch> catches;
ArrayAdapter<Catch> arrayAdapter;
catches = new ArrayList<>();
try {
JSONArray array = new JSONArray(charSequence.toString());
System.out.println(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Integer id = obj.getInt("id");
String angler_name = obj.getString("name");
String email = obj.getString("email");
String dateTime = obj.getString("datetime");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date jsonDate = sdf.parse(dateTime);
String fishingMethod = obj.getString("fishing_method");
String fishBreed = obj.getString("breed");
String length = obj.getString("length");
String weight = obj.getString("weight");
String weather = obj.getString("weather");
String location = obj.getString("location");
Double latitude = obj.getDouble("latitude");
Double longitude = obj.getDouble("longitude");
Catch fishCatch = new Catch(id, angler_name, jsonDate, fishingMethod, fishBreed, length, weight, weather, location, latitude, longitude);
catches.add(fishCatch);
}
ListView listView = (ListView) findViewById(R.id.yourFishList);
arrayAdapter = new ArrayAdapter(YourList.this, android.R.layout.simple_list_item_1, catches);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener((parent, view, position, id) -> {
Intent intent = new Intent(getBaseContext(), YourDetailsCatch.class);
intent.putExtra("YourCatch", catches.get((int) id));
intent.putExtra("token", token);
startActivity(intent);
});
//newAdapter = new Adapter();
//listView.setAdapter(newAdapter);
arrayAdapter.notifyDataSetChanged();
} catch (JSONException ex) {
ex.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
删除活动:
public class YourDetailsCatch extends AppCompatActivity {
private Catch fishCatch;
private String token;
int id;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_details_catch);
intent = getIntent();
fishCatch = (Catch) intent.getSerializableExtra("YourCatch");
token = intent.getStringExtra("token");
id = fishCatch.getID();
System.out.println(id);
TextView anglerName = (TextView) findViewById(R.id.yournameOfAngler);
anglerName.setText(fishCatch.getAngler_name());
EditText breed = (EditText) findViewById(R.id.yourfishBreedDetail);
breed.setText(" " +fishCatch.getBreed());
EditText method = (EditText) findViewById(R.id.yourfishMethodDetail);
method.setText(fishCatch.getSpearfishing());
EditText weight = (EditText) findViewById(R.id.yourfishWeightDetail);
weight.setText(" " +fishCatch.getWeight());
EditText length = (EditText) findViewById(R.id.yourfishLengthDetail);
length.setText(" " +fishCatch.getLength());
EditText location = (EditText) findViewById(R.id.yourfishLocationDetail);
location.setText(" " + fishCatch.getLocation());
EditText latitude = (EditText) findViewById(R.id.yourfishLatitudeDetail);
String parseLatitude = Double.toString(fishCatch.getLatitude());
latitude.setText(" " +parseLatitude);
EditText longitude = (EditText) findViewById(R.id.yourfishLongitudeDetail);
String parseLongitude = Double.toString(fishCatch.getLongitude());
longitude.setText(" " +parseLongitude);
EditText weather = (EditText) findViewById(R.id.yourfishWeatherDetail);
weather.setText(" " + fishCatch.getWeather());
EditText dataTime = (EditText) findViewById(R.id.yourfishDateTimeDetail);
String str = String.format(String.valueOf(fishCatch.getDateTime()));
dataTime.setText(" " +str);
}
public void deleteCatch(View view) {
DeleteCatchTask deleteCatchTask = new DeleteCatchTask();
deleteCatchTask.execute("http://api.evang.dk/v2/catches/" + id + "?token=" + token);
AlertDialog.Builder alert = new AlertDialog.Builder(YourDetailsCatch.this);
alert.setTitle("Success");
alert.setMessage("Deletion Successful");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
private class DeleteCatchTask extends AsyncTask<String, Void, CharSequence> {
@TargetApi(Build.VERSION_CODES.CUPCAKE)
@Override
protected CharSequence doInBackground(String... params) {
String urlString = params[0];
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
int responseCode = connection.getResponseCode();
if(responseCode / 100 != 2){
String responseMessage = connection.getResponseMessage();
throw new IOException("HTTP response code: " + responseCode + " " + responseMessage);
}
} catch (MalformedURLException e) {
cancel(true);
String message = e.getMessage() + " " + urlString;
Log.e("Catches", message);
return message;
} catch (IOException ex) {
cancel(true);
Log.e("Catches", ex.getMessage());
return ex.getMessage();
}
return null;
}
}
}
答案 0 :(得分:0)
使用适配器的功能&#34; notifydatasetchanged()&#34;
答案 1 :(得分:0)
对于两个活动之间的通信,请使用startActivityForResult(Intent intent,int requestCode)。
在您的特定情况下,使用ListView在Activity中的某处声明一个int:
// Can be any value of your choosing
private static final int REQUEST_CODE = 112;
在listView的onItemClickListener中,不要调用startActivity(intent),而是调用startActivityForResult:
Intent intent = new Intent(getBaseContext(), YourDetailsCatch.class);
intent.putExtra("YourCatch", catches.get((int) id));
intent.putExtra("token", token);
startActivityForResult(intent, REQUEST_CODE);
现在在您的DeleteActivity中,一旦项目被删除,您可以使用setResult()方法通过ListView通知Activity:
Intent intent = new Intent("deletedId", id);
setResult(RESULT_OK, intent);
finish();
上述意图包含已删除项目的ID,并已传递回ListActivity。我们现在需要在ListActivity中选择它:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE = resultCode == RESULT_OK && data != null){
int id = data.getIntExtra("deletedId", 0);
// Add logic to remove item from your list
// Notify adapter of new changes
adapter.notifiyDataSetChanged();
}
}
有关更详细的说明和示例,请阅读官方文档:https://developer.android.com/training/basics/intents/result.html