executing rawquery with WHERE Clause from another Activity to recieve Table Values - android

I am having a problem in SQLiteDatabase. I want to access the database table created in one Activity from another Activity.However when I use WHERE clause the query is not executing.
I am referring sambleDB from CropInfoListclass.
These are some codes.
String[] item = {getIntent().getExtras().getString("item")};
Cursor c = CropInfoList.sampleDB.rawQuery("SELECT * FROM "+ TableName +" WHERE "+ name +"=?", item);
String Name = c.getString(c.getColumnIndex("name"));
String Type = c.getString(c.getColumnIndex("type"));

Related

Sql Query to retrieve a particular data from particular column and row in android?

I want to fetch phone number linked to particular email in the database. I am not able to find the query for it or how
public String getContactNumber(String email){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_USER_MOBILE_NUMBER + " FROM " + TABLE_USER + " WHERE " + email + " = " + COLUMN_USER_EMAIL;
Cursor cursor = db.rawQuery(query,null);
//What to put here to extract the data.
String contact = cursor.getString(get);
cursor.close();
return contact;
}
to extract the data. Completely a beginner
Try this ..
public List<String> getMyItemsD(String emailData) {
List<String> stringList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT COLUMN_USER_MOBILE_NUMBER FROM " + USER_TABLE_NAME + " WHERE email= " + emailData;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
String name = (c.getString(c.getColumnIndex("Item_Name")));
stringList.add(name);
c.moveToNext();
}
}
return stringList;
}
public String getContactNumber(String email){
String contact = "";
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_USER_MOBILE_NUMBER + " FROM " + TABLE_USER + " WHERE " + email + " = " + COLUMN_USER_EMAIL;
Cursor cursor = db.rawQuery(query,null);
if(cursor.getCount()>0) {
cursor.moveToNext();
contact = cursor.getString(cursor.getColumnIndex(COLUMN_USER_MOBILE_NUMBER));
}
//What to put here to extract the data.
cursor.close();
return contact;
}
From this method you get phone number value of that email which you pass any other method easily.
I'd suggest the following :-
public String getContactNumber(String email){
String contact = "NO CONTACT FOUND"; //<<<<<<<<<< Default in case no row is found.
SQLiteDatabase db = this.getWritableDatabase(); //<<<<<<<<<< Generally getReadable gets a writable database
String[] columns_to_get = new String[]{COLUMN_USER_MOBILE_NUMBER};
String whereclause = COLUMN_USER_EMAIL + "=?";
String[] whereargs = new String[]{email};
Cursor cursor = db.query(TABLE_USER,columns_to_get,whereclause,whereargs,null,null,null);
//What to put here to extract the data.
if (cursor.moveToFirst()) {
contact = csr.getString(csr.getColumnIndex(COLUMN_USER_MOBILE_NUMBER));
}
cursor.close();
return contact;
}
The above does assumes that there will only be 1 row per email (which is most likely).
Explanations
A default value is set so that you can easily tell if an invalid/non-existent email is passed (you'd check the return value if need be (might be easier to simply have "" and check the length as a check)).
getReadableDatabase has been replaced with getWritableDatabase as unless there are issues with the database a writable database will be returned, as per :-
Create and/or open a database. This will be the same object returned
by getWritableDatabase() unless some problem, such as a full disk,
requires the database to be opened read-only. In that case, a
read-only database object will be returned. If the problem is fixed, a
future call to getWritableDatabase() may succeed, in which case the
read-only database object will be closed and the read/write object
will be returned in the future.
getReadableDatabase
Note no real problem either way;
The recommended query method has been used instead of the rawQuery method. This has distinct advantages, it builds the underlying SQL and also offers protection against SQL injection (just in case the email passed is input by a user).
this version of the method takes 7 parameters :-
The table name as a string
The columns to be extracted as an array of Strings (aka String array). null can be all columns.
The where clause less the WHERE keyword with ?'s to represent arguments (see next). null if no WHERE clause.
The arguments to be applied (replace ?'s 1 for 1) as a String array. null if none or no WHERE clause.
The GROUP BY clause, less the GROUP BY keywords. null if no GROUP BY clause.
The HAVING clause, less the HAVING keyword. null if no HAVING clause.
The ORDER BY clause, less the ORDER BY keywords. null if no ORDER BY clause.
SQLiteDatabase - query
- Note there are 4 query methods (see link for the subtle difference, I believe this is the most commonly used)
The data extraction is the new code. When a Cursor is returned it is at a position BEFORE THE FIRST ROW, so you need to move to a valid row. So the moveToFirst* method is suitable (note that if a move cannot be made by a move method that it will return false, hence how you can say if (cursor.moveToFirst())). The data is then extracted from the appropriate column use the **getString method, which takes an int as an argumnet for the column offset (0 in this case). However, using hard coded values can lead to issues so the getColumnIndex method is used to get the offset according to the column name (-1 is returned if the named column is not in the Cursor).

SQLite Querying with user defined data

I have a query that joins 2 tables get the required data on my android, what picture here is the user clicks on an item and the item's ID is used to query the right data in the Database, I know I can simply use database.query() but it according to my research it is used for simply database querying only, in my case I should use rawQuery() which provides more power of the database. below is my query which links table 1 to table 2 to get the users name from table one and user last name from table 2 if the foreign key is the same as user key
Assume this is my query:
String sQuery = SELECT table1.ID, table2.userlastname FROM table1, table2 WHERE "+table1.ID = table2.foreign;
If i try to specify the user id like below it gets all data in the database table which means i should replace id with "=?" but how do I do this when I am dealing which such a query, one that uses db.rawQuery() instead of db.query()
`private Object userInfo(int id)
{
String sQuery = SELECT table1.ID, table2.userlastname
FROM table1, table2 WHERE "+table1.ID = id;
}`
Basically you replace the parameter by question marks '?' and pass them through a String array in the order they appear in the query.
String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign;
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);
it did not work until I joined table 2 like:
`String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);`

Android: How to access results from Cursor when INNER JOIN is performed?

I am using INNER JOIN on two tables,table1 and table2, from my SQLite Database.
How do I access the results(columns of both tables) from the cursor? The two tables have 2 columns with same name.
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
You can specify column names instead of using '*'.
String query = SELECT table1.id AS ID,table2.column2 AS c2,...... FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
and then access using column name ID,c2 etc .
while (cursor.moveToNext()) {
String c2 = cursor.getString(cursor.getColumnIndex("c2"));
int id = cursor.getInt(cursor.getColumnIndex("ID"));
..............
.............
}
Editing the broken link : Check rawQuery methid here http://www.vogella.com/tutorials/AndroidSQLite/article.html
and here http://www.codota.com/android/methods/android.database.sqlite.SQLiteDatabase/rawQuery for different examples
You can access the result as you would with any other query.
The only difference is that there is a chance to name conflicts, same column name on both tables. In order to solve those conflict you would need to use the table name as a prefix.
For example
Long id = c.getLong(c.getColumnIndex(tableName1 + "." + idColumnName));
If this approach doesn't work. You should write your query as follows:
String query = SELECT table1.id AS table1_id FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
Cursor c = newDB.rawQuery(query, null);
And another general note, it is better not to use "Select *..." it is preferred to write explicitly which column you would like to select.
Cursor c=databseobject.functionname() //where query is used
if(c.movetofirst()) {
do {
c.getString(columnindex);
} while(c.movetoNext());
}
I have used the following to do an inner join:
public Cursor innerJoin(Long tablebId) {
String query = SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id WHERE name like '%c%';
return database.rawQuery(query, null);
}
You can Iterate your cursor as below:
Cursor cursor = innerJoin(tablebId);
String result = "";
int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT);
cursor.moveToFirst();
do{
result = result + cursor.getString(index_CONTENT) + "\n";
}while(cursor.moveToNext());
Hope this works for you
If you know the column name then you can find it like below,
long id = cursor.getLong(cursor.getColumnIndex("_id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
if you just want to see all the columns name of the returned cursor then you can use String[] getColumnNames() method to retrieve all the column names.
Hope this will give you some hint.

Android get value of any column from any cursor giving the corresponding id

I have created Cursor from any database table. It consists value of _id and corresponding name. For further operation, I need the value of "name" for any specific "_id". How it is possible using the Cursor.
String selecttSqlStr2 = "SELECT * FROM Tablename WHERE TRIM(QST_Id) = '" + _id;
Cursor c = datasource.execSelectSQL(selecttSqlStr);//datasource is object for opening database
c.moveToFirst();
String name=c.getString(c.getColumnIndex("name"));
Very Simple you can get it by either of following way
String id = cursor.getString( cursor.getColumnIndex("id") ); // id is column name in db
or
String id = cursor.getString( cursor.getColumnIndex(0)); // id is first column in db

passing parameter of _id and updating SQLitedatabase

I'm trying to update an SQLite table using the row id as my where statement. I'm getting the row _id from a row shown in a listview and passing to another activity with this statement:
Cursor cursor = (Cursor) nurseTableAdapter.getItem((int)id);
showAssignments.putExtra("Nurse", cursor.getInt(cursor.getColumnIndex("_id")));
The receiving activity receives the parameter:
nurse = extras.getString("Nurse");
and passes it as a parameter to my DbCommunicator class:
updateAssignments.updateNurseAssignments(listItemsArray, nurse);
and my DbCommunicator class does this with it:
public void updateNurseAssignments(String[] choices, String nurseId) {
// set parameter variables
//int nurseIdToInt = Integer.parseInt(nurseId);
//String strFilter = "_id=" + nurseIdToInt;
//String where = "_id=?";
String[] whereArgs = {String.valueOf(nurseId)};
Log.i(TAG, "value of whereArgs is " + whereArgs[0]);
// set content values
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(KEY_FIRST_ASSIGNMENT, choices[0]);
cvUpdate.put(KEY_SECOND_ASSIGNMENT, choices[1]);
cvUpdate.put(KEY_THIRD_ASSIGNMENT, choices[2]);
cvUpdate.put(KEY_FOURTH_ASSIGNMENT, choices[3]);
cvUpdate.put(KEY_FIFTH_ASSIGNMENT, choices[4]);
cvUpdate.put(KEY_SIXTH_ASSIGNMENT, choices[5]);
// update database
sqldb.update(NURSE_TABLE, cvUpdate, KEY_NURSE_ROWID + "= ?", whereArgs);
}
I'm getting no errors, but the table is not updating. I've only found one similar example in Stack Overflow, and have tried to incorporate some of that here, but still having problems. Suggestions appreciated.

Categories

Resources