I am using the following, where AuthorName column value i want to find on the basis of AuthorID. catid is an array that contains AuthorID
public Cursor Authorname(String[] catid) {
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
}
but it return IllegalArgumentException. Can anybody help me to short out this. Thanks in advance.
You can use only one query to get all the users. Here's an example.
private static final String QUERY = "SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID IN %ids";
public Cursor Authorname(String[] catid) {
// Build the string with all the IDs, e.g. "(1,2,3,4)"
StringBuilder ids = new StringBuilder();
ids.append("(");
for(int i = 0; i < catid.length; i++) {
ids.append(String.valueOf(catid[i]);
if (i < catid.length - 1) {
ids.append(",");
}
}
ids.append(")");
// Use the string with the ids in the query
String finalQuery = QUERY.replaceAll("%ids", ids.toString());
// Execute the query
return myDataBase.rawQuery(finalQuery);
}
Change your query
myDataBase.rawQuery("SELECT AuthorName FROM AUTHOR_NAME WHERE AuthorID = ?",catid);
as below
cursor = myDataBase.query("AUTHOR_NAME",
new String[] {"AuthorName"}, "AuthorID IN(?)", catid, null, null, null);
Try the above Solution hope it works for you.
Related
I have the following function in android studio, which is supposed to return a sqlite cursor.
The problem comes in the selectionArgs argument. Whenever I am passing more than one value to it, it returns a cursor with 0 records.
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
String strArgs = mySqliteHandler.getWhereColArgsFromJsonString(strListWhere);
Log.d(TAG, "qqqq9: " + strArgs);
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
String[] strSelectArgs = { strArgs };
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, strSelectArgs, null, null, null, null);
Log.d(TAG, "qqqq9: " + csrResult.getCount());
return csrResult;
}
The value in strColsToReturn is animal_class = ? and province_name = ?
The value in strArgs is Bird, KwaZulu-Natal
So I want it to be animal_class = 'Bird' and province_name = 'KwaZulu-natal'
When I only pass one value it works, for example
The value in strColsToReturn is animal_class = ?
The value in strArgs is Bird
Can anyone assist?
EDIT: the following code works:
public Cursor getCursor(String strListWhere, String strTable, String strCols) {
String strColsToReturn = mySqliteHandler.getWhereColNamesFromJsonString(strListWhere);
List<String> arrWhere = new ArrayList<String>();
arrWhere = mySqliteHandler.getWhereArray(strListWhere);
String[] finalValue = new String[ arrWhere.size() ];
arrWhere.toArray( finalValue );
String strTableName = strTable;
String[] strColumnsToReturn = { strCols };
String strSelectWhere = strColsToReturn ;
Cursor csrResult = sqLiteDatabase.query(true, strTableName, strColumnsToReturn, strSelectWhere, finalValue, null, null, null, null);
return csrResult;
}
The value for strColumnsToReturn should be an array with the names of the columns that you want returned, like:
new String[] {column1, column2, column3}
where column1, column2, column3 are strings.
The value for strSelectWhere should be the string:
"animal_class = ? and province_name = ?"
and the value of strSelectArgs should be a string array with the parameters that you pass to each of the ? placeholders of strSelectWhere:
new String {"Bird", "KwaZulu-Natal"}
You can find more here
Using following query to get column data:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
return strR;
}
In Activity, I am trying to read returned strR :
String string = mydb.getR("1400");
Toast.makeText(SyncAll.this, string, Toast.LENGTH_SHORT).show();
But in Toast, I am getting my Select query itself instead of Record, like this:
SELECT col_no FROM tracking where col_id = '1400' ORDER BY col_no DESC LIMIT 1
May I know ! Where I am doing mistake ?
I tried the same way suggested by prosper k above, and finally got the solution:
public String getR(String str) {
String strR = "SELECT col_no FROM tracking where col_id = '"+str+"' ORDER BY col_no DESC LIMIT 1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(strR, null);
if (cursor != null)
cursor.moveToFirst();
strR = cursor.getString(0);
return strR;
}
You're calling the function getR, which is returning the string value strR.
I'm assuming that mydb is an extended object from class SQLiteOpenHelper, and that you have followed the documentation here https://developer.android.com/training/basics/data-storage/databases.html then you'll have to execute the query like:
Cursor cursor = null;
try {
SQLiteDatabase db = this.getWritableDatabase();
synchronized(this) {
cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
col_no = cursor.getInt(0);
}
}
} finally {
if (null != cursor)
cursor.close();
}
return col_no;
I am new with android.
I just wanted to take the count of number of rows in table against particular user in DB (uid is column in db).
For this purpose i made following function:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid=?";
Cursor c = ourDB.rawQuery(query,uid);
}
But its giving me error:
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
also want to know how can i be able to return count from this?
Please help me.
you should use this WAY:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if(c.getCount()>0)
c.moveToFirst();
do{
int id = c.getInt(0);
}while(c.moveToNext());
}
Try this way
public int getCount(int uid){
try{
String query = "select count(*)'count' from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if (c.moveToFirst()) {
return Integer.parseInt(cursor.getString(0));
}
}catch (Throwable e) {
e.printStackTrace();
}
return 0;
}
change your query to:
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid;
Cursor c = ourDB.rawQuery(query);
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
Clearly states you are passing int instead of expected String[]
Cursor c = ourDB.rawQuery(query,new String[]{ uid });
use the query as :
"SELECT * FROM <DB_NAME> WHERE uid="+uid
and then use the getCount() method on the cursor
like :
Cursor csr = db.rawQuery("above query string here");
int count = csr.getCount();
I have a database name "CUED" (sqlite Android)it have a table HELLO which contain a column NAME I can get the value to String from that column.
Let me show you my code section
myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null);
Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null);
while(crs.moveToNext())
{
String uname = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
}
It will print the value one by one. Now what I need is that I want to get the column values from database and so that I can store it in a String Array.
You already did the hard part... the array stuff is pretty simple:
String[] array = new String[crs.getCount()];
int i = 0;
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array[i] = uname;
i++;
}
Whatever, I always recommend to use collections in cases like this:
List<String> array = new ArrayList<String>();
while(crs.moveToNext()){
String uname = crs.getString(crs.getColumnIndex("NAME"));
array.add(uname);
}
In order to compare the arrays, you can do things like this:
boolean same = true;
for(int i = 0; i < array.length; i++){
if(!array[i].equals(ha[i])){
same = false;
break;
}
}
// same will be false if the arrays do not have the same elements
String[] str= new String[crs.getCount()];
crs.movetoFirst();
for(int i=0;i<str.length();i++)
{
str[i] = crs.getString(crs.getColumnIndex("NAME"));
System.out.println(uname);
crs.movetoNext();
}
Enjoy it
This is my code that returns arraylist contains afield value:
public ArrayList<String> getAllPlayers() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title
+ " from " + table, new String[] {});
ArrayList<String> array = new ArrayList<String>();
while (cur.moveToNext()) {
String uname = cur.getString(cur.getColumnIndex(title));
array.add(uname);
}
return array;
}
I have an application where I want to use the values returned from an SQL query against a database in my application. I want to use attach these values to a uri that links to a script on remote host. I am doing a call to the method to retrieve the values, after which I will now extract them. The issue is that I am facing a challenge in going about this. I know a bit of php and what I want in android is done like this in php:
....(preceding code)...$row['email'];
and I can now assign a variable e.g. $email=$row['email'];
How can I do this in android?
I don't want a cursor returned, just the values of the columns as strings.
Below is my code (I will need help to retrieve the password column)
public String[] selectAll()
{
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
if(cursor.getCount() >0)
{
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
str[i] = cursor.getString(cursor.getColumnIndex("email"));
i++;
}
return str;
}
else
{
return new String[] {};
}
}
I need help on inserting the "password" column so that it will be returned with the email.
try this way
String[][] str = new String[cursor.getCount()][cursor.getColumnCount()];
while (cursor.moveToNext())
{
for(int j=0;j<cursor.getColumnCount();j++)
str[i][j] = cursor.getString(j); /// may be this column start with the 1 not with the 0
i++;
}
you need to store this in two dimenstion array for row wise and column wise
but if this will give only one result everytime
String[] str = new String[cursor.getColumnCount()]; // here you have pass the total column value
while (cursor.moveToNext())
{
str[0] = cursor.getString(cursor.getColumnIndex("email"));
str[1] = cursor.getString(cursor.getColumnIndex("password"));
}
You should change your design like this
public Cursor selectAll() {
Cursor cursor = db.query(DB_TABLE_NAME, new String[] { "email","password"},null, null, null, null,null);
return cursor;
}
and use the selectAll function like this
Cursor cursor=selectAll();
String[] mail = new String[cursor.getCount()];
String[] pass = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext())
{
mail[i] = cursor.getString(cursor.getColumnIndex("email"));
pass[i] = cursor.getString(cursor.getColumnIndex("password"));
i++;
}