2015-01-11 48 views
0

我使用的是一個列表視圖來加載其中的所有數據庫項目,它的工作原理。問題是每次我記得那個活動我的listview被填充了我的重複項目。 此處的代碼:Android上的重複項目列表視圖

public class UserActivity extends ActionBarActivity{ 

public static ArrayList<String> ArrayofName = new ArrayList<String>(); 
private ListView listView; 

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

    DataHandler db = new DataHandler(this); 
    List<Data> items = db.getTitle(); 

    listView = (ListView) findViewById(R.id.listView1); 

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ArrayofName); 

    listView.setAdapter(adapter); 
} 

例如,如果我插入項目「Facebook」它將被插入我的數據庫內,當我調用UserActivity它會加載數據庫內容(在這種情況下Facebook項目),並顯示其所有內容在我的listView。問題是當我這樣做我的listView顯示我2 Facebook項目。如果我有2項,當我記得UserActivity它會顯示我4項。

怎麼了? 感謝

回答

1

問題是與

public static ArrayList<String> ArrayofName = new ArrayList<String>(); 

它不應該是靜態否則這將是一次裝箱,它不會初始化在下次活動recreate.Remove static關鍵字寫像這個 -

public ArrayList<String> ArrayofName = new ArrayList<String>(); 

OR 確保ArrayList在您從數據庫中填充填充時沒有元素。

1

解決辦法有兩個:

1)從

public static ArrayList<String> ArrayofName = new ArrayList<String>(); 

取出static關鍵字如果您不能刪除該關鍵字因任何原因,使用的解決方案2)。

2.)在添加新條目之前,調用ArrayList的方法clear()

+0

我必須遵循2)解決方案,因爲我需要聲明ArrayList靜態。我在添加新條目之前調用clear()方法,但是當我添加項目時,我的listView只顯示最後一個插入,因爲調用清除它清除所有列表 – xXJohnRamboXx