So I followed a tutorial regarding sqlite and android studio and how to save data into a database and being able to view this data later on. The tutorial only showed how to save one value to the database. But how can I save multiple values to this array?
This is the method where the data is added to the array:
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
listData.add("Id :"+ data.getString(0)+"\n");
listData.add("Value :"+ data.getString(1)+"\n");
listData.add("Note :"+ data.getString(2)+"\n");
listData.add("Category :"+ data.getString(3)+"\n");
listData.add("Payment :"+ data.getString(4)+"\n\n");
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
As soon as I try to add more than one value to the Listview the app crashes. This is my list view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Do I have to change anything here to be able to add muliple values? I'm completly new to android stuido and java, so there might be just one stupid mistake I am not able to see.
Instead of adding each column as a new item in the list concatenate all the column values of each row and add it to the list, so each item of the list contains 1 row of the table.
So change your while
loop to this:
String row;
while(data.moveToNext()){
row = "Id :"+ data.getString(0)+"\n" +
"Value :"+ data.getString(1)+"\n"+
"Note :"+ data.getString(2)+"\n"+
"Category :"+ data.getString(3)+"\n"+
"Payment :"+ data.getString(4);
listData.add(row)
}