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
Related
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))
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());
im constructing an android application which use a large pre populated datbase of 910,000 records which includes 4 columns. These columns are windspeed, latitude, longitude and _id. What im trying to do is construct an sqlite query that finds a lav value in the latitude column and long (longitude) value in the longitude and the windspeed at which these two columns meet.
So the table would look something like this:
_id..............Latitude..................Longitude..............WindSpeed
1..................-9.4869363.............61.3704805..............7
2.................-7.6257292...............60.9958851..............8
3.................-9.4869363................60.9958851..............10
so if i was use the above table the lat value i would want to find would -9.4869363 and the long value would be 60.9958851 and thus the windspeed would be the line that both of these meet e.g from the table line 3 and thus the wind speed is 10
To do this ive tried using this line of code but i dont think it is correct
public class MyDatabase extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "WindSpeed.sqlite";
private static final int DATABASE_VERSION = 1;
private static final String LAT_VAL = "Latitude";
private static final String LONG_VAL = "Longitude";
private static final String WIND_SPEED= "Speed10m";
private static final String ROW_ID= " _id";
double lat= 3.52;
double Long = 65.42;
public MyDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getWindSpeed2(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {WIND_SPEED,};
String sqlTables = "noabl_10m_out";
String whereClause = "LAT_VAL = ? AND LONG_VAL = ?";
String[] whereArgs = new String[] {
"lat",
"Long"
};
qb.setTables(sqlTables);
Cursor d = qb.query(db, sqlSelect, whereClause, whereArgs,
null, null, null);
d.moveToFirst();
return d;
}
}
Is this wrong, ive searched far and wind and i just keep getting confused tbh so any help would be massive thanks
It seems that you are not using the column names but instead the variable names.
Try to change the whereClause to:
String whereClause = LAT_VAL + "=? AND " + LONG_VAL + "=?";
Also the whereArgs to:
String[] whereArgs = new String[] {
String.valueOf(lat),
String.valueOf(Long)
};
There are many mistakes in your code and I'm starting to think that you have no idea what you're doing.. Unnecessary comma here:
String [] sqlSelect = {WIND_SPEED,};
Change
String whereClause = "LAT_VAL = ? AND LONG_VAL = ?";
to
String whereClause = LAT_VAL+" = ? AND "+LONG_VAL+" = ?";
and
String[] whereArgs = new String[]
{
"-9.4869363",
"60.9958851"
};
to
String[] whereArgs = new String[]
{
"lat",
"Long"
};
LAT_VAL and LONG_VAL are variable that you use to store the columns name so they should be outside the quotes and whereArgs needs to contain the values that you want to compare
I have the following query that returns a Cursor based on how many records have an awayreasontypeid of '2'. It works fine.
How can i run the same query but return a Cursor of all the records that have an awayreasontypeid of either '2' or '0'?
// table AwayReason column names
public static final String C_AWAYREASON_ID_INDEX = BaseColumns._ID;
public static final String C_AWAYREASON_ID = "awayreasonid";
public static final String C_AWAYREASON_NAME = "awayreasonname";
public static final String C_AWAYREASON_TYPE_ID = "awayreasontypeid";
public Cursor queryCarerAwayReasons(){
SQLiteDatabase db = dbhelper.getReadableDatabase();
String[] carer = { "2" };
Cursor c = db.rawQuery("SELECT * FROM " + DBHelper.TABLEAWAYREASON + " WHERE awayreasontypeid = ?", carer);
return c;
}
Thanks in advance
Matt
You can use IN:
String[] carer = { "2", "0" };
Cursor c = db.rawQuery("SELECT * FROM " + DBHelper.TABLEAWAYREASON + " WHERE awayreasontypeid IN (?,?)", carer);
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();