0

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.

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! But for some reason the app still crashses when I try to open the listview.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.