Get data from database Android

Sunny picture Sunny · May 21, 2013 · Viewed 15k times · Source

I have a page which can retrieve user data from database but after whole day of trying, I am only able to get the table column name but not the value inside.

this is my code to create database

 public static final String LASTLOGIN = "lastuser"; 
 public static final String USER_ID = "suser_id";
 public static final String USER_NAME = "suser_name";
 public static final String USER_PASSWORD = "spassword";
 public static final String PRIME_ID = "id";

 private static final String TABLE_USER = 
         "create table "+ LASTLOGIN+" ("
        +PRIME_ID+" integer primary key autoincrement, "
        + USER_ID + " text, "
        + USER_NAME +" text, "
        +USER_PASSWORD+" text); ";

and here is the function implemented to get user data

public Cursor getuser()
{
    String[] columns = new String[]{PRIME_ID, USER_NAME, USER_PASSWORD};
    Cursor cursor = sqLiteDatabase.query(
           LASTLOGIN, columns, null, null, null, null, PRIME_ID +" DESC");
    Log.d("TAG", columns[1]);
    return cursor;
}

and here is my code to display the result

mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();

cursor = mySQLiteAdapter.getuser();
String[] resultvalue = new String{
         SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();

and the toast result only show the column name but not the value inside, is there any mistake i made? and I want to set limit to 1, but where to set it?

Thanks for helping me

Answer

s_bei picture s_bei · May 21, 2013

the way you try reading the values is completly wrong. you create an array

String[] resultvalue = new String[]{
                       SQLiteAdapter.PRIME_ID,
                       SQLiteAdapter.USER_NAME,
                       SQLiteAdapter.USER_PASSWORD};

after that you read the values 0 and 1 from this array. Your toast works absolutly correctly becouse inside this array you define the column names!

If you want to show the values from your query do it this way:

    while(cursor.moveToNext()){
            Integer str1 = str 1 + cursor.getInteger(1);
            String str2 =str2 + cursor.getString(2);
       Toast.makeText(this, str1 + str2, Toast.LENGTH_LONG).show();
    }

or a better way receiving the correct index:

cursor.getInteger( cursor.getColumnIndex(SQLiteAdapter.PRIME_ID) );
cursor.getString( cursor.getColumnIndex(SQLiteAdapter.USER_NAME) );