简体   繁体   中英

Android - Listview stays empty

I am currently having a problem implementing a listview in a fragment. I used a Hashmap then converted into an arrayList as follows:

     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View myView = inflater.inflate(
            R.layout.fragment_portfolio, container, false);
    ListView listview = (ListView) myView.findViewById(R.id.listview);

    List<HashMap<String, Integer>> fillMaps = new ArrayList<>();
    HashMap<String, Integer> portfoliodata = new HashMap<>();
    portfoliodata.put("Test", 23);
    fillMaps.add(portfoliodata);
    SimpleAdapter adapter = new SimpleAdapter(getActivity().getApplicationContext(), fillMaps, R.layout.my_adapter_item, new String[] { "AAA","BBB" },
            new int[] { android.R.id.text1, android.R.id.text2 });
    listview.setAdapter(adapter);
    return myView;
}

Yet, the result is always a totally blank fragment. Any idea why it is doing so and how I could solve this?

Thank you in advance

getActivity() doesn't exist inside method onCreateView(), because you don't have the Activity's context yet.

You can probe to move your code to onResume() method.

*And remember that you have to connect each column with your data , something like that:

ListView listview;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    View myView = inflater.inflate(
        R.layout.fragment_portfolio, container, false);

    listview = (ListView) myView.findViewById(R.id.listview);

    return myView;
} 

@Override
public void onResume() {
    // create the grid item mapping
    String[] from = new String[] {"AAA","BBB"};
    int[] to = new int[] {android.R.id.text1, android.R.id.text2};

    List<HashMap<String, String>> fillMaps = new ArrayList<>();
    HashMap<String, String> portfoliodata = new HashMap<>();
    portfoliodata.put("AAA", "Text SampleA");
    portfoliodata.put("BBB", "Text SampleB");
    fillMaps.add(portfoliodata);

    SimpleAdapter adapter = new SimpleAdapter(getActivity(), fillMaps, 
        R.layout.my_adapter_item, from, to);
    listview.setAdapter(adapter);
}

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM