2016-11-09 5 views
-1

リストビュー内のオブジェクトをクリックしてトリガされた別のアクティビティでリストからオブジェクトを削除しようとしていますが、削除が成功してもリストビューを更新できないようです。リストビューと別のアクティビティで削除後にリストビューを更新する

アクティビティー:削除するため

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

startActivityForResultを使用し、2つのアクティビティ間の通信のために ")(notifydatasetchanged"

+0

私が持っています。それは動作しません:) – kennyYice23

0

をアダプタの機能を使用します(インテントの意図、int requestCode)。あなたの特定のケースで

、リストビューでどこかにあなたの活動のintを宣言します。

// Can be any value of your choosing 
private static final int REQUEST_CODE = 112; 

あなたのListViewのonItemClickListenerの内部では、代わりにstartActivity(意図)を呼び出すの、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

+0

まあ、それの問題は、私のリストビューは、アクティビティ内のクラスにあることです。したがって、私はonActivityResultメソッドをオーバーライドできず、アクセスできないためアダプタを使用することはできません。それをグローバルにして親に入れると、私のリストはnullになります。 – kennyYice23

+0

あなたの配列アダプタとリストビューは、何らかの方法で宣言されるべきです。 –

+0

さて、私はあなたのソリューションを試しましたが、それは私のために働いていません – kennyYice23

関連する問題