2013-01-21 39 views
2

我有兩個活動 - 一個顯示來自SQLite的數據,另一個在那裏添加數據。我可以用標籤在它們之間切換。問題是,如果我添加一個新項目,我不知道如何刷新列表,因爲它在不同的活動類中,我無法在添加類中訪問它。這怎麼解決?添加新的不同活動後刷新SQLite列表

這裏是我的兩個類:

列表:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_1); 

    final ShoppingSQL shoppingSQL = new ShoppingSQL(this); 
    final List<ShoppingData> list = shoppingSQL.getAll(); 

    final ArrayAdapter<ShoppingData> adapter = new ArrayAdapter<ShoppingData>(
      this, android.R.layout.simple_list_item_1, list); 
    setListAdapter(adapter); 

    this.getListView().setLongClickable(true); 
     this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() { 
      public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { 
       shoppingSQL.delete((int)list.get(position).getId()); 
       adapter.remove(list.get(position)); 
       adapter.notifyDataSetChanged(); 
       return true; 
      } 
     }); 
} 

地址:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_2); 
} 

public void ButtonOnClick(View v) { 
    ShoppingSQL shoppingSQL = new ShoppingSQL(this); 

    ShoppingData data = new ShoppingData(); 
    data.setName("test"); 

    shoppingSQL.add(data); 

    Dialog d = new Dialog(this); 
    d.setTitle("Added!"); 
    d.show(); 
} 

我也有一點sidequestion。在我的第一個(列表)活動中,當我在「onLongClick」中訪問它們時,Eclipse使每個變量都是最終的 - 爲什麼是這樣並且可以避免?此外,對於我應該關注什麼以及如何讓我的代碼更好或者我犯的任何其他錯誤發表任何評論都會非常好。

+0

使用cursor.setNotificationUri,contentResolver.notifyChange,也許cursor.registerContentChangeObserver – njzk2

+0

從匿名類訪問時,您需要變量最終或更廣泛的範圍。通常,您可以擁有這些實例成員。或者,您可能會注意到id是作爲參數提供的(不需要獲取(位置).getId,並且適配器也被傳遞。您可以將其轉換爲避免參考其他引用。 – njzk2

+0

有添加活動觸發一個事件,並讓另一個拿起這個效果並刷新? – Zlatko

回答

2

我會保持簡單。只需將添加類的意圖發送到List類,然後您的列表將再次使用新項目填充。

+0

我把這個添加: 意圖我=新的意圖(這,FirstActivity.class); startActivity(i); 它工作。將我的背部送回列表並重新加載所有內容。謝謝! :) – user1985273

+0

至少使用本地BroadcastManager。否則,由於進程間通信而產生很多開銷。 – Dan

+0

Intent intent = new Intent(); intent.setAction(「de.vogella.android.mybroadcast」); sendBroadcast(intent); 是否這樣? – user1985273

1

你想要使用的是連接到你的SQLite DB的CursorLoader(見http://developer.android.com/reference/android/content/CursorLoader.html)。然後,您可以使用適配器與CursorLoader同步的ListView。這通過使用偵聽器模式自動完成(或多或少)。

在添加數據的活動中,您需要通知所有監聽者數據已更改。通常,您通過致電notifyChange(請參閱http://developer.android.com/reference/android/content/ContentResolver.html#notifyChange%28android.net.Uri,%20android.database.ContentObserver,%20boolean%29)來完成此操作。

您可能還想考慮實現自己的內容提供者。

+1

也謝謝你,我必須表示我不明白你說了什麼,而且soulreaver的anwser對我來說更簡單,但仍然非常感謝你的努力。當我更好的在Java /機器人,並確定它會幫我:) – user1985273

+0

CursorLoaders是Andoids標準模式用於監聽底層數據源的變化。對於一個很好和清晰的代碼,你應該閱讀一些關於這個主題的教程。它真的幫助我瞭解發生了什麼。 – Dan