-3

I want to fetch data using cursor which is stored in our table events But I am unable to fetch that data. How could I do so please give me suitable and simple answer only.

This is my Database class, in which I have created my database table representation and methods to perform action on them.

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "students.db";
    public static final String Table_Name = "STUDENTINFO";

    public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
       super(context, DATABASE_NAME, factory, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

    public void onCreate(SQLiteDatabase db)
    {
       String Query = "CREATE TABLE " + Table_Name + "( id INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, CONTACT TEXT, EMAIL TEXT );";
       db.execSQL(Query);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXIST" + Table_Name);
        onCreate(db);
    }

}
Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54

2 Answers2

1

From the code above, you don't appear to have any data in the database, you just have an empty table. To enable data to be added you could add the following method to the Databasehelper class.

public void insertRow(String name, String contact, String email) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put("NAME",name);
    cv.put("CONTACT",contact);
    cv.put("EMAIL",email);
    db.insert(Table_Name,null,cv);
}

To get all rows from the table add the following method to you DatabaseHelper class:-

public Cursor getAllRows() {
    SQLiteDatabase db = this.getWritableDatabase();

    return db.query(Table_Name,null,null,null,null,null,null);
}

To add some data you could use the following in an activity (perhaps it's called MainActivity and this could go in the onCreate method)

    int anyoldvalue_asnotused_justpasseed = -12345;
    // Note can't use DatabaseHelper.DATABASE_VERSION as it's private.
    DatbaseHelper dbhlpr = new DatabaseHelper(this,
        DatabaseHelper.DATABASE_NAME,
        null,
        anyoldvalue_asnotused_justpasseed);

    dbhlpr.insertRow("Fred","whatever","Fred@nowhere.com");
    dbhlpr.insertRow("Bert","more whatever","Bert@noemail.com");
    // mimic the above to add more data

Note! this will add two rows every time the App is started. You'd typically mimic the above in an activity that allows the data to be input and then submitted.

To get the data you could use the following (obviously after the data has been added):-

    // Now access that data using the getAllRows instance method
    // which returns a Cursor named csr
    Cursor csr = dbhlpr.getAllRows();
    // Traverse the Cursor outputting all columns to the Log
    while (csr.moveToNext()) {
        Log.d("MYDATA",
                "Name is " + csr.getString(csr.getColumnIndex("NAME")) +
                        " Contact info is " + 
                        csr.getString(csr.getColumnIndex("CONTACT")) +
                        " Email is " +
                        csr.getString(csr.getColumnIndex("EMAIL")) +
                        " id is " +
                        Long.toString(csr.getLong(csr.getColumnIndex("id"))));
    }

This would output the data to the log e.g. :-

09-10 12:51:14.075 4170-4170/? D/MYDATA: Name is Fred Contact info is whatever Email is Fred@nowhere.com id is 1
09-10 12:51:14.075 4170-4170/? D/MYDATA: Name is Bert Contact info is more whatever Email is Bert@noemail.com id is 2

However I would advise some making some changes.

1) change the DatbaseHelper constructor in the DatabaseHelper class to only need what needs to be passed (i.e. just the context) so change:-

    public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
       super(context, DATABASE_NAME, factory, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

to

    public databaseHelper(Context context)
    {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

and change the following in MainActivity from

DatbaseHelper dbhlpr = new DatabaseHelper(this,
    DatabaseHelper.DATABASE_NAME,
    null,
    anyoldvalue_asnotused_justpasseed);

to

DatbaseHelper dbhlpr = new DatabaseHelper(this);

2) remove the keyword AUTOINCREMENT , there is very no need for this as INTEGER PRIMARY KEY will result in an incrementing unique id. See here for an explanation SQLite Autoincrement .

3) As it is considered better practice to use column names to access columns it would probably be best to change column names to be defined as DatabaseHelper class variables, like DATABASE_NAME and Table_Name have been defined. In doing so, use _id rather than id. The reason is that if you use CursorAdapters for ListViews and Spinners, the adapters require a column named _id and it should really be the unique id. So adopting this now may save some bother in the future


Here's the complete code after changes above have been made.

NOTE you should either UNISTALL the APP or CLEAR the APP DATA before rerunning the APP (alternately as onUpgrade calls onCreate you could increase the database version number)

The reason is that column id will be changed to _id (and also have AUTOCOMPLETE removed) and that the onCreate method only runs automatically if no database exists i.e. onCreate DOES NOT RUN every time the App is started (unless forced to do so according to code).

So here's the changed code :-

DatabaseHelper.java :-

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "students.db";
    public static final String TABLENAME = "STUDENTINFO";
    public static final String IDCOLUMNNAME = "_id";
    public static final String NAMECOLUMNNAME = "NAME";
    public static final String CONTACTCOLUMNNAME = "CONTACT";
    public static final String EMAILCOLUMNNAME = "EMAIL";

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        SQLiteDatabase DB = this.getWritableDatabase();
    }

    public void onCreate(SQLiteDatabase db)
    {
        String Query = "CREATE TABLE " + TABLENAME + "(" +
                IDCOLUMNNAME + " INTEGER PRIMARY KEY," +
                NAMECOLUMNNAME + " TEXT," +
                CONTACTCOLUMNNAME + " TEXT," +
                EMAILCOLUMNNAME + " TEXT " +
                ");";
        db.execSQL(Query);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXIST " + TABLENAME);
        onCreate(db);
    }

    public void insertRow(String name, String contact, String email) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put(NAMECOLUMNNAME,name);
        cv.put(CONTACTCOLUMNNAME,contact);
        cv.put(EMAILCOLUMNNAME,email);
        db.insert(TABLENAME,null,cv);
    }

    public Cursor getAllRows() {
        SQLiteDatabase db = this.getWritableDatabase();

        return db.query(TABLENAME,null,null,null,null,null,null);
    }
}

MainActivity.java (if this is the name of your activity) :-

    // Get and instance of the DatbaseHelper class named dbhlpr
    DatabaseHelper dbhlpr = new DatabaseHelper(this);

    // Call the instances inertRow method to add some data
    dbhlpr.insertRow("Fred","whatever","Fred@nowhere.com");
    dbhlpr.insertRow("Bert","more whatever","Bert@noemail.com");

    // Now access that data using the getAllRows instance method
    // which returns a Cursor named csr
    Cursor csr = dbhlpr.getAllRows();
    // Traverse the Cursor outputting all columns to the Log
    while (csr.moveToNext()) {
        Log.d("MYDATA",
                "Name is " + csr.getString(csr.getColumnIndex(DatabaseHelper.NAMECOLUMNNAME)) +
                        " Contact info is " +
                        csr.getString(csr.getColumnIndex(DatabaseHelper.CONTACTCOLUMNNAME)) +
                        " Email is " +
                        csr.getString(csr.getColumnIndex(DatabaseHelper.EMAILCOLUMNNAME)) +
                        " id is " +
                        Long.toString(csr.getLong(csr.getColumnIndex(DatabaseHelper.IDCOLUMNNAME))));
    }
}
MikeT
  • 51,415
  • 16
  • 49
  • 68
0

Simplest Answer: Learn best practices first, just take a day to learn how to properly write and use SQLite goes a long way:

https://www.udacity.com/course/android-basics-data-storage--ud845

Easiest Answer: Use the Schematic Annotation Library

https://github.com/SimonVT/schematic

Shortest Answer: Have a nice day.

Andrew Lam
  • 1,371
  • 17
  • 35