Home » Android » java – Cursor Array into ListView but multiple columns-Exceptionshub

java – Cursor Array into ListView but multiple columns-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I currently get cursor data via a database query, put each selection into an array to then show in one of my three list views.

public void insertData() {
    ListView listView = (ListView) findViewById(R.id.listWorkouts1);
    ListView listView2 = (ListView) findViewById(R.id.listWorkouts2);
    ListView listView3 = (ListView) findViewById(R.id.listWorkouts3);
    SQLiteController db = new SQLiteController(this);
    String username = ma.id;
    //populate an ArrayList<String> from the database and then view it
    ArrayList<String> theList1 = new ArrayList<>();
    ArrayList<String> theList2 = new ArrayList<>();
    ArrayList<String> theList3 = new ArrayList<>();
    ArrayList<String> finalList = new ArrayList<>();
    Cursor data = db.getUserListContents(username);

    if (data.getCount() == 0) {
        Toast.makeText(this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            theList1.add(data.getString(0));
            theList2.add(data.getString(1));
            theList3.add(data.getString(2));

            ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList1);
            listView.setAdapter(listAdapter);

            ListAdapter listAdapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList2);
            listView2.setAdapter(listAdapter2);

            ListAdapter listAdapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList3);
            listView3.setAdapter(listAdapter3);
        }
    }
}

enter image description here

The issue is the user can separately scroll through each of the three listviews.

How can I only use one listView but separate the data to be seen in separate columns?

At default, it lists everything under the previous value.

Each While loop performed I want that data to be shown on the same line, not one under the other.

Any help is appreciated.

How to&Answers:

You can use RecyclerView with a GridLayoutManager in your case. Here is a basic implementation example. You can also look into this tutorial as well.

Instead of separate lists, you can actually create an object and pass the list of that object into your adapter to load the items from there. For example, consider the following class.

public class Workout {
    public String name;
    public String date;
    public String weight;
}

Now when reading values from the cursor, create an object of Workout class and create a List<Workout> and then modify your adapter to pass this list.

I hope I could give you an idea of implementing this gracefully.