I have following table
private static final String DB_TABLE = "create table user (id integer primary key autoincrement, "
+ "username text not null, password text not null, tel text not null, info text not null, job text);";
How can I fetch data using cursor and convert it to string? because I am getting null Should I have set gets?
I have to fetch job and info by username and password?
Cursor theUser = dbHelper.fetchUser(thisUsername, thisPassword);
if (theUser != null) {
// How here also fetch a info and job in String?
startManagingCursor(theUser);
if (theUser.getCount() > 0) {
//saveLoggedInUId(theUser.getLong(theUser.getColumnIndex(DatabaseAdapter.COL_ID)), thisUsername, thePassword.getText().toString());
stopManagingCursor(theUser);
theUser.close();
// String text = dbHelper.getYourData();
Intent i = new Intent(v.getContext(), InfoActivity.class);
startActivity(i);
}
//Returns appropriate message if no match is made
else {
Toast.makeText(getApplicationContext(),
"You have entered an incorrect username or password.",
Toast.LENGTH_SHORT).show();
// saveLoggedInUId(0, "", "");
}
stopManagingCursor(theUser);
theUser.close();
}
else {
Toast.makeText(getApplicationContext(),
"Database query error",
Toast.LENGTH_SHORT).show();
}
}
private static final String LOGIN_TABLE = "user";
//Table unique id
public static final String COL_ID = "id";
//Table username and password columns
public static final String COL_USERNAME = "username";
public static final String COL_PASSWORD = "password";
private static final String KEY_PHONE = "tel";
private static final String INFO = "info";
private static final String JOB = "info";
public Cursor fetchUser(String username, String password) {
Cursor myCursor = database.query(LOGIN_TABLE,
new String[] { COL_ID, COL_USERNAME, COL_PASSWORD },
COL_USERNAME + "='" + username + "' AND " +
COL_PASSWORD + "='" + password + "'", null, null, null, null);
if (myCursor != null) {
myCursor.moveToFirst();
}
return myCursor;
}
thank you in advance!!!
Update:
String name = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_USERNAME));
String phone = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String tel = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.KEY_PHONE));
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO));
String job = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.JOB));
String id = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.COL_ID));
How can I wrote request fir this one:
public Cursor fetchAllUsers() {
return database.query(LOGIN_TABLE, new String[] { COL_ID, COL_USERNAME,
COL_PASSWORD }, null, null, null, null, null);
}
To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.
Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table.
A Cursor needs to be closed with the close() method call when you are finished with it.
Your code should look something like this to get the info column, but please note in your question that the JOB and INFO columns have the same string, so they'll return the same column index until you fix that
String info = theUser.getString(theUser.getColumnIndex(DatabaseAdapter.INFO))
Related
I want to create a android sqlite table with only one single row, for insert or update and read, how can i do that, cause i only know how to create mulitiple row
the table contain only 1 single row , is for user insert data and store , when read the data will come out , and last the update mean it will override the data which in that row.
this is my DBHelperNote.java
public static final String TABLE_GOAL = "goal";
public static final String GOAL_ID= "goal_id";
public static final String GENDER = "gender";
public static final String AGE = "age";
public static final String HEIGHT = "height";
public static final String WEIGHT = "weight";
public static final String GOAL = "goal";
private static final String CREATE_TABLE_GOAL = "CREATE TABLE " + TABLE_GOAL + " (" +
GOAL_ID + " INTEGER PRIMARY KEY, " +
GENDER + " text not null, " +
AGE + " text not null, "+
HEIGHT + " text not null, "+
WEIGHT + " text not null, "+
GOAL + " text not null "+
" );";
this is SQLControlerWeight.java
public void insertGoal(String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.insert(DBHelperNote.TABLE_GOAL, null, cv);
}
public Cursor readGoal() {
String[] allColummn = new String[] {
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
Cursor c = database.query(DBHelperNote.TABLE_GOAL, allColummn, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
this actually is the method to read data put but it is from array mean multiple row , but i don't Know how to change it to only call one row
dbconnection = new SQLControlerWeight(this);
dbconnection.openDatabase();
Cursor cursor = dbconnection.readGoal();
String[] from = new String[]{
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
int[] to = new int[]{
R.id.goal_id,
R.id.field_gender,
R.id.field_age,
R.id.field_height,
R.id.field_weight,
R.id.field_goal,
};
As you will be having GOAL_ID ones inserted you can modify you insert function as
public void insertGoal(String goal_id, String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
if (goal_id != null){
cv.put(DBHelperNote.GOAL_ID, goal_id);
}
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.replace(DBHelperNote.TABLE_GOAL, null, cv);
}
Modification done is changed insert to replace, which will make sure if primary key value is provided and row exists with that id then it will replace the existing row without creating new one. Most important is the if condition for checking whether goal_id is null or not, if null then don't provide that in contentvalue.
Modify the if condition properly for proper comparison for Goal_id as i have just used the one i can visualize from your question content.
Use RawQuery method its little bit easier.
c1 = db.rawQuery("select * from Table_Name", null);
c1.moveToFirst();
do {
str = c1.getString(c1.getColumnIndex("FieldName"));
ab.add(str);
} while (c1.moveToNext());
I have the following database config
public static final String ST_ID = "s_id";
public static final String ST_NAME = "s_name";
public static final String ST_COURSE = "s_course";
public static final String DBCREATE_STUDENTDB = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME+" ("
+ "s_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "s_name VARCHAR, "
+ "s_course VARCHAR);";
public static final int VERSION = 1;
Now I am trying to get the individual id
final ContentResolver resolver = getContentResolver();
final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE };
Cursor cursor = resolver.query(StudentDataProvider.studentTableUri, projection, null, null, null);
if (cursor.moveToFirst()) {
do {
Log.wtf("ID", ""+cursor.getString(cursor.getColumnIndex(StudentDB.ST_ID)));
} while (cursor.moveToNext());
}
I am getting error on this.
10-02 07:14:29.788: E/AndroidRuntime(2252): java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
however the following code works for other column
Log.wtf("List", ""+cursor.getString(cursor.getColumnIndex(StudentDB.ST_COURSE)));
what is the problem?
You didn't add your ID in your Projection Change it to :
final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE,StudentDB.ST_ID};
final String[] projection = { StudentDB.ST_NAME, StudentDB.ST_COURSE };
If no ID in your projection, the cursor don't have any field called so.
Do this:
final String[] projection = { StudentDB.ST_ID, StudentDB.ST_NAME, StudentDB.ST_COURSE };
#Sardor Dushamov, was right too, if ID is autoincrement, use getInt not getString.
See your projection String[], you didn't add the StudentDB.ST_ID
I have a table in my DB, which consists from following fields: id, group_id, uri_id, name, phone.
In my DB manager file I have a function to check if a uri_id exists in group. This is the function:
public boolean is_contact_in_group(String uri_id, int group_id)
{
SQLiteDatabase db = db_helper.getReadableDatabase();
Cursor mContactsCursor = db.query(Constants.TABLE_NAME_GROUP_CONTACTS, null,
"group_id="+group_id+"&contact_uri_id="+uri_id, null, null, null, null);
if(mContactsCursor.moveToFirst())
{
mContactsCursor.close();
db.close();
return true;
} else {
mContactsCursor.close();
db.close();
return false;
}
}
For now In my activity I just want to log the output:
private void add_new_contact(String uri_id, String name, String number)
{
int group_id = curr_group_id;
String contact_uri_id = uri_id;
String contact_name = name;
String contact_phone = number;
Log.i(DEBUG_TAG, "Is contact exist: "+manager.is_contact_in_group(contact_uri_id, group_id));
}
However every time I get false, even if there is a record with a certain group_id and uri_id.
Why is it happening and how to fix it?
I'd imagine it's because your WHERE clause is wrong.
Change
"group_id="+group_id+"&contact_uri_id="+uri_id
to
"group_id="+group_id+" AND contact_uri_id="+uri_id
Try with this.
Cursor mContactsCursor = db.query(Constants.TABLE_NAME_GROUP_CONTACTS, null,
"group_id = " + group_id + " & contact_uri_id = " + uri_id, null, null, null, null);
Your Query has not white spaces between sentences.
I'm trying to check for a valid user. But I'm getting the following Exception:
no such column: ABC(Code 1):, while compiling: SELECT _id, username, password
FROM MyTable1 WHERE username=ABC
The code is as follows:
public int checkUser(String userName, String password) {
int check = -1;
int id = 2;
String psword = new String();
Cursor cursor = database.query(TABLE_NAME, allColumns, COLUMN_USER_NAME + "=" + userName, null, null, null, null);
cursor.moveToFirst();
Log.v(TAG, "After CURSOR!!");
psword = cursor.getString(cursor.getColumnIndex(COLUMN_PASSWORD));
Log.v(TAG, "pasword: " + psword);
if (psword.equals(password)) {
check = 1;
}
return check;
}
What am I doing wrong?? Please help
If username is varchar/text type then
Cursor cursor = database.query(TABLE_NAME, allColumns, COLUMN_USER_NAME
+ "=" + '"+userName+"', null, null, null, null);
This is sample login function
public boolean checkUser(String username, String password) throws SQLException
{
String whereClause = " USERNAME = '"+userName+"' ";
try {
open();// dbopen
Cursor cursor = db.query(TABLE_NAME, allColumns,whereClause, null, null, null, null);
}catch(Exception e){
}
}
or
public boolean checkUser(String username, String password) throws SQLException
{
Cursor mCursor = database.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
You should add quotes around userName. You want the rows that match the string value "ABC" or 'ABC' I don't remember which quotes. If you don't put quotes you are matching with the column named ABC.
And you should use prepares statements instead. That would avoid you many problems.
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
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) );
Please note when retrieving data from a database, you store it in a Cursor in the memory and hence can only access it using that particular Cursor object, which you have used in the following line of code.
Cursor cursor = mySQLiteAdapter.getuser();
The Following line retrieves the column names and not the values.
String[] resultvalue = new String[]{SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
So the following is doing what you have asked it to do, retrieve column names not values
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
You need something like following:
if(cursor.getCount() != 0)
{
while(cursor.moveToNext())
{
resultvalue [0] = csr.getString(0);
resultvalue [1] = csr.getString(1);
//....
}
}
Hope this helps
here is my solution:
final String TABLE_NAME = "table_name";
String selectQuery = "SELECT Column FROM "+TABLE_NAME+" WHERE column='"+some_value+"'";
SQLiteDatabase db = this.openDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = new String[cursor.getCount()];;
int i = 0;
if (cursor.moveToFirst()) {
do {
i=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
} while (cursor.moveToNext());
}
cursor.close();