androidarraylisthashmapsimpleadapter

Trouble with SimpleAdapter


I wanna to make file manager. This alghorithm worked well with ArrayAdapter but when I redid it under SimpleAdapter it stopped working correctly. The main problem: when I add the element to ArrayList it's duplicated. I don't know what's the problem. Help me. Thaks.

onActicityCreated method:

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);
    }
}

Solution

  • Just to close this question, as mentioned in the comments by Mike, you need to create a new instance of Map for every iteration of the loop.

    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);
    }