2017-02-18 115 views
0

我想做文件管理器。這個alghorithm與ArrayAdapter很好地工作,但是當我在SimpleAdapter下重新使用它時,它停止正常工作。主要問題:當我將元素添加到ArrayList時,它被複制。我不知道有什麼問題。幫我。 Thaks。SimpleAdapter故障

onActicityCreated方法:

private final String ATTRIBUTE_NAME_TEXT = "text"; 
private final String ATTRIBUTE_NAME_IMAGE = "image"; 

private String[] from = {ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_IMAGE}; 
private int[] to = {R.id.currPath, R.id.imageView}; 


@Override 
public void onActivityCreated(Bundle savedInstanceState){ 
    super.onActivityCreated(savedInstanceState); 

    Log.d(TAG, "Tab created"); 
    if (savedInstanceState == null) { 
     Log.d(TAG, "SIS == null"); 
     paths.add("/storage/emulated/0/"); 
     paths.add("/storage/extSdCard/"); 

     Map<String, Object> m = new HashMap<>(); 
     ArrayList<Map<String, Object>> data = new ArrayList<>(); 
     for(int i = 0; i < paths.size(); i++){ 
      m.put("text", paths.get(i)); 
      m.put(ATTRIBUTE_NAME_IMAGE, R.mipmap.ic_launcher); 
      data.add(m); 
     } 
     MySimpleAdapter adapter = new MySimpleAdapter(getActivity(), data, R.layout.item, from, to); 
     setListAdapter(adapter);//Creating a primary form of application 
    } 
    else{ 
     Log.d(TAG, "SIS != null"); 
     currentPath = savedInstanceState.get(KEY_PATH).toString(); 
     paths = savedInstanceState.getStringArrayList(KEY_LIST); 

     Map<String, Object> m = new HashMap<>(); 
     ArrayList<Map<String, Object>> data = new ArrayList<>(); 
     for(int i = 0; i < paths.size(); i++){ 
      m.put(ATTRIBUTE_NAME_TEXT, paths.get(i)); 
      m.put(ATTRIBUTE_NAME_IMAGE, R.mipmap.ic_launcher); 
      data.add(m); 
     } 
     MySimpleAdapter adapter = new MySimpleAdapter(getActivity(), data, R.layout.item, from, to); 
     setListAdapter(adapter); 
    } 
} 
+1

您每次通過'for'循環使用相同的'Map'實例。您可能的意思是每次在循環的頂部創建一個新的。 –

+1

哦,狗屎。謝謝你。我怎麼沒有注意到? –

回答

1

就關閉這個問題,因爲在由麥克的評論中提到,你需要爲循環的每一次迭代創建地圖的新實例。

for(int i = 0; i < paths.size(); i++){ 
    Map<String, Object> m = new HashMap<>(); 
    m.put(ATTRIBUTE_NAME_TEXT, paths.get(i)); 
    m.put(ATTRIBUTE_NAME_IMAGE, R.mipmap.ic_launcher); 
    data.add(m); 
}