2017-05-21 132 views
1

我有一個應用程序有兩個Intents。首先顯示一些對象,第二個喜歡的對象是第一個對象Intent,但標記爲「最喜歡的」。當我在第二個Intent-最喜歡的時候,我想將未標記的對象變成「常規」對象,然後當我點擊back button時,對象列表刷新並顯示啓用按鈕「添加到最愛」。但它不工作:NotifyDataSetChanged在後退按鈕不起作用

收藏intent

public class FavWashActivity extends Activity{ 

    private RecyclerView mRecyclerView; 
    private RecyclerView.Adapter mAdapter; 
    private RecyclerView.LayoutManager mLayoutManager; 

    private MyAdapter myAdapter; 

    private List<WashLocation> washLocations; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.favorite_wash); 

     mRecyclerView = (RecyclerView) findViewById(R.id.fav_recycler_view); 
     DataBaseHelper dataBaseHelper = new DataBaseHelper(getApplicationContext()); 
     washLocations = dataBaseHelper.getFavouriteWashLocation(); 
     mAdapter = new MyAdapterFavWash(washLocations, this); 
     mRecyclerView.setAdapter(mAdapter); 
     mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 
     myAdapter = new MyAdapter(null, this, null); 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     if ((keyCode == KeyEvent.KEYCODE_BACK)) { 
      onBackPressed(); 
     } 
     return false; 
    } 

    @Override 
    public void onBackPressed() { 
     super.onBackPressed(); 
     myAdapter.notifyDataSetChanged(); 
    } 
} 

而需要被刷新adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { 

    private List<WashLocation> washLocations; 
    private LayoutInflater layoutInflater; 
    private DataBaseHelper dataBaseHelper; 
    private Map<String, Integer> queueToWash; 

    public MyAdapter(List<WashLocation> washLocations, Context context, Map<String, Integer> queueToWash) { 
     layoutInflater = LayoutInflater.from(context); 
     this.washLocations = washLocations; 
     dataBaseHelper = new DataBaseHelper(context); 
     this.queueToWash = queueToWash; 
    } 
+1

你需要刷新'onResume'中的第一個'Activity'而不是'onBackPressed' –

+0

的作品!感謝:D – bielas

+0

在onResume中刷新數據不是一個好方法,因爲如果用戶按回到主頁並返回到您的活動,則刷新冗餘列表,更好的方法是'onActivityResult',如果用戶更改第二個活動中的任何項目,則刷新列表,否則不要刷新數據。 –

回答

0

嘗試是這樣的

  @Override 
      public void onBackPressed() { 
       super.onBackPressed(); 
       washLocations.remove(1); 
       //need to change in arraylist than only you can notify your adapter. 
       //add some data in array list or remove data.than try to notify it. 
       myAdapter.notifyDataSetChanged(); 
      } 

希望這幫助你..如果需要任何幫助,你可以要求它。

+0

但是這個解決方案將永遠刪除第一個元素。什麼時候用戶將在中間刪除? – bielas

+0

@bielas我剛剛舉了一個例子,你需要改變你的arraylist中的東西,而不僅僅是你可以通知你的適配器...如果你想從中間刪除比你需要把你的邏輯爲...實際上你爲什麼想要在onResume()刷新你的列表? –

+0

我想單擊手機上的後退按鈕後刷新它.. – bielas