thomaspane
thomaspane

Reputation: 35

Android ListView not loading values from SQLite

I am trying to load values from a database into a listview, but the listview doesn't seem to be showing the data. I first have a comment class which is in charge of getters and setters for the columns in the db.

package com.example.sqlite;

public class Comment {
    private long id;
    private String name;
    private float itemPrice;

    public long getId( ) {
        return id;
    }

    public void setId( long id ) {
        this.id = id;
    }

    public float getItemPrice() {
        return itemPrice;
    }
    public void setItemPrice(float price) {
        this.itemPrice = price;
    }

    public String getName( ) {
        return name;
    }

    public void setName( String comment ) {
        this.name = name;
    }

    // Will be used by the ArrayAdapter in the ListView.
    @Override
    public String toString( ) {
        return name;
    }
}

I load the values into the db with a onClick command. The issue seems to be with this line here Comment comment = cursorToComment(cursor); where comment is having null values instead of the values from the db. If I try doing cursor.getString(0-2) then the actual values from the db are being printed to the console. I am not sure what exactly is happening. I don't get any errors either. I have found the source of the problem, I think, but am not sure how to solve it. THe full CommentsDataSource class is listed below so you can have some context to how the list of comments is implemented.

package com.example.sqlite;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CommentsDataSource {

    // Database fields
    //Used toe xecute commands on db.
    private SQLiteDatabase database;
    //Opening up the mysqlhelper which is in charge of opening up connection and maintaining
    private MySQLiteHelper dbHelper;
    //Holds all the values from the database
    private String[] allColumnsItems = { MySQLiteHelper.id, MySQLiteHelper.ITEMS_COLUMN_NAME,
            MySQLiteHelper.ITEMS_PRICE };

    //Creating the default constructor
    public CommentsDataSource(Context context) {
        //Give context to the class that manages the connection
        dbHelper = new MySQLiteHelper(context);
    }

    //Opening up the connction to the db
    public void open() throws SQLException {
        //Open the db for reading and writing
        database = dbHelper.getWritableDatabase(); //getWritableDatabase is what opens the connection
    }

    //Closing the database
    public void close() throws SQLException {
        dbHelper.close();
    }

    //Creating and commiting comment
    public Comment createComment(String comment, float price) {
        //Insert into comments values('')
        ContentValues values = new ContentValues();
        //Load the column id and value into ContentValues
        values.put(MySQLiteHelper.ITEMS_COLUMN_NAME, comment);
        values.put(MySQLiteHelper.ITEMS_PRICE, price);
        //Now insert into table
        long insertID = database.insert(MySQLiteHelper.TABLE_ITEMS, null, values);
        if(insertID == -1) {
            System.out.println("JSDLFJLSJDFL");
        }
        //Create a cursor to keep track of results. When creating cursors they equal database.query
        Cursor cursor =  database.query(MySQLiteHelper.TABLE_ITEMS, allColumnsItems, MySQLiteHelper.id + " = " + insertID, null, null, null, null);
        //Move cursor tot he front
        cursor.moveToFirst();
        //Return the comment which is added to listview
        return cursorToComment(cursor);
    }


    public List<Comment> getAllComments() {
        //Select * from comments
        List<Comment> comments = new ArrayList<Comment>();
        //Fetching the results of query into cursor
        Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS, allColumnsItems, null, null, null, null, null);
        //Move to front of cursor
        cursor.moveToFirst();
        //Iterate through cursor
        while(!cursor.isAfterLast()) {
            Comment comment = cursorToComment(cursor);
            //Add results to arraylist
            System.out.println(comment);
            comments.add(comment);
            System.out.println(cursor.getString(2));
            cursor.moveToNext();
        }
        cursor.close();
        System.out.println(comments);
        return comments;
    }

    public Comment cursorToComment(Cursor cursor) {
        Comment comment = new Comment();
        comment.setId(cursor.getLong(0));
        comment.setName(cursor.getString(1));
        comment.setItemPrice(cursor.getFloat(2));
        return comment;
    }

}

EDIT: More information about the database. Its named menu and has one table within it called items. THis table has three attributes id, title, price.

package com.example.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

    //Creating the items table
    public  static final String TABLE_ITEMS = "items";
    public static final String id = "_id";
    public  static final String ITEMS_COLUMN_NAME = "name";
    public  static final String ITEMS_PRICE = "price";



    private static final String DATABASE_NAME  = "menu";
    private static final int DATABASE_VERSION  = 1;

    // create table comments(
    //   _id integer primary key autoincrement,
    //   comment text not null );
    private static final String TABLE_CREATE_ITEMS = "create table "
            + TABLE_ITEMS + "(  " + id  + " integer primary key autoincrement, "
            +ITEMS_COLUMN_NAME + " text, "
            + ITEMS_PRICE + " real not null );";

    public MySQLiteHelper( Context context ) {
        super( context, DATABASE_NAME, null, DATABASE_VERSION );
    }

    @Override
    public void onCreate( SQLiteDatabase database ) {
        //Create the items table
        database.execSQL( TABLE_CREATE_ITEMS );
        //Create the combos table
        //database.execSQL(TABLE_CREATE_COMBO);
    }
    @Override
    public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {

    }

}

Upvotes: 2

Views: 62

Answers (2)

MikeT
MikeT

Reputation: 56983

I believ that the issue is that the setName setter is incorrect (you set the name using name which is null, when you should be using comment which is the variable passed to the setter).

Using :-

/*
public void setName( String comment ) {
    this.name = name;
}
*/


public void setName( String comment ) {
    this.name = comment; //<<<<< CHANGED to use variable passed
}

Using the following to test :-

public class MainActivity extends AppCompatActivity {

    CommentsDataSource cds = new CommentsDataSource(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cds.open();
        cds.createComment("A",10.55f);
        cds.createComment("B",20.55f);
        cds.createComment("C",30.55f);

        List<Comment> comments = cds.getAllComments();
        for (Comment c: comments) {
            Log.d("COMMENTINFO","ID=" + c.getId() + " NAME = " + c.getName() + " PRICE = " + c.getItemPrice() );
        }
    }
}

results in :-

2019-12-18 15:12:28.754 I/System.out: A
2019-12-18 15:12:28.754 I/System.out: 10.55
2019-12-18 15:12:28.754 I/System.out: B
2019-12-18 15:12:28.754 I/System.out: 20.55
2019-12-18 15:12:28.754 I/System.out: C
2019-12-18 15:12:28.754 I/System.out: 30.55
2019-12-18 15:12:28.754 I/System.out: [A, B, C]
2019-12-18 15:12:28.755 D/COMMENTINFO: ID=1 NAME = A PRICE = 10.55
2019-12-18 15:12:28.755 D/COMMENTINFO: ID=2 NAME = B PRICE = 20.55
2019-12-18 15:12:28.755 D/COMMENTINFO: ID=3 NAME = C PRICE = 30.55

Instead of :-

2019-12-18 15:17:15.830 I/System.out: null
2019-12-18 15:17:15.830 I/System.out: 10.55
2019-12-18 15:17:15.830 I/System.out: null
2019-12-18 15:17:15.830 I/System.out: 20.55
2019-12-18 15:17:15.831 I/System.out: null
2019-12-18 15:17:15.831 I/System.out: 30.55
2019-12-18 15:17:15.831 I/System.out: [null, null, null]
2019-12-18 15:17:15.832 D/COMMENTINFO: ID=1 NAME = null PRICE = 10.55
2019-12-18 15:17:15.832 D/COMMENTINFO: ID=2 NAME = null PRICE = 20.55
2019-12-18 15:17:15.832 D/COMMENTINFO: ID=3 NAME = null PRICE = 30.55

Upvotes: 2

Md. Enamul Haque
Md. Enamul Haque

Reputation: 1026

I think you are using same open() method before calling getAllComments()

But writing in database and reading in database are not same.

you have to call

dbHelper.getReadableDatabase();

So you can create a method like

//Opening up the connction to the db
public void read() throws SQLException {
    //Open the db for reading
    database = dbHelper.getReadableDatabase();
}

Call this method before calling getAllComments()

Need to modify in Comment Model:

public void setName( String comment ) {
    //this.name = name;
    //Change this to 
    this.name = comment;
}

Otherwise you will not get commet it will stay null.

Upvotes: 1

Related Questions