Search code examples
javaandroidlistviewfragment

How tp pass data to ListView in Fragment?


I'm trying to pass data from my database to a Fragment ListView but the list puts the data in a single cell .I want the 2 in the same cell.

App's screen

Fragment file:


    DataBaseHelper db ;
    ArrayList<String> listItem;
    ArrayAdapter adapter;
    ListView listweight;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_weight_table, container, false);

        db = new DataBaseHelper(getContext());
        listItem = new ArrayList<>();
        listweight = (ListView) view.findViewById(R.id.lv_weights);
        viewData();
        return view;
    }

    private void viewData(){

        Cursor cursor=db.viewData();
        if(cursor.getCount() == 0)    {
            Toast.makeText(getContext(),"No data to show",Toast.LENGTH_LONG).show();
        }else{
            while (cursor.moveToNext()){
                listItem.add(cursor.getString(1));
                listItem.add(cursor.getString(2));
            }
        }

        adapter = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,listItem);
        listweight.setAdapter(adapter);
    }

Solution

  • You should combine the listItem items into one entry. So instead of adding a new element in your arraylist each time, try combining the entries:

    listItem.add(cursor.getString(1) + ", " + cursor.getString(2));
    

    Good luck!