I have went through many related threads and i was not successful yet .
I dont know where i am going wrong , i have the following method to get the rows .
public Cursor getallrows (String fid , String sid , String bid , String pid , String limit)
{
return db.query(DATABASE_ALLPENLIST, new String[] {"rowpos","Peninnerid","issampled","onesymbol","twosymbol","threesymbol","foursymbol","fivesymbol","buildingid","farmid","sampleid","penid"}, "farmid = "+fid+" and sampleid = "+sid+" and buildingid = "+bid+" and penid = "+pid , null, null, null,"RANDOM()",limit);
}
but the above method returns me the correct number of rows mentioned in the limit but not in the Random order , it is returning the first n rows mentioned in the limit variable .
Is this RANDOM() case-sensitive ? But i have also tried with Random() and "RANDOM() LIMIT "+limit in the place of 7th parameter .
Thanks in Advance .
This query should work with return random rows based off if the limit variable is of string type or you can be explicit with it like this:
db.query(DATABASE_ALLPENLIST,
new String[] {"rowpos","Peninnerid","issampled","onesymbol","twosymbol","threesymbol","foursymbol","fivesymbol","buildingid","farmid","sampleid","penid"},
"farmid = "+fid+" and sampleid = "+sid+" and buildingid = "+bid+" and penid = "+pid ,
null,
null,
null,
"RANDOM()",
"1");
or try raw query:
db.rawQuery("Select rowpos, Peninnerid , issampled, onesymbol, twosymbol, threesymbol, foursymbol, fivesymbol, buildingid, farmid, sampleid, penid From " + DATABASE_ALLPENLIST + " Order By RANDOM() LIMIT ?", new String[] {limit});
Doumentation to this API: Link
Related
I am trying to get this id from a table that has a column called "name". I tried various codes I found but I keep getting an empty cursor, which results in the exception:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
The last code I tried is
Cursor cursor = db.rawQuery( "select * from " + TABLE_NAME + " where name='"+name+"'", null );
cursor.moveToFirst();
int countryId = cursor.getInt(cursor.getColumnIndex("id"));
I'd love to get some guidance. If some information is missing I'll provide it.
Thanks!
First, use the recommended and safe way to supply the argument name, by using a ? placeholder:
Cursor cursor = db.rawQuery( "select * from " + TABLE_NAME + " where name=?", new String[] {name} );
Then use the result of the method moveToFirst() to check if the Cursor contains any row(s):
int countryId = -1;
if (cursor.moveToFirst()) {
countryId = cursor.getInt(cursor.getColumnIndex("id"));
}
Finally check the value of countryId.
A negative value means that the name was not found.
Of course this code will work if there are columns id and name in the table.
I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)
I got stuck in a very strange issue. Where i am able to update the db Values when when trying to fetching the rows corresponding to that values i am not getting anything.
In this database, i inserted these rows, the date were 29, june for the last two rows, but when i updated these dates to 15, and tried to fetch the rows corresponding to that date
String where = COL_DATE + " = ?";
String[] args = {"15"};
Cursor cursor = db.query(TABLE_DAILY_EXPENSE, null, where, args, null, null, null);
Then Log.d(TAG, "Cursor count= " + cursor.getCount());gives 0`
Where as by fetching through month, it gives count = 2.
So i concluded, that somewhere after updating the fields, its not matching that updated field for fetching that corresponding row. But why this is happening?? No Idea.
`
The value in the database is a number.
The value you are searching for is a string, which is different.
The Android database API allows only strings as parameters in most places, so you have to insert the number directly into the SQL command:
String where = COL_DATE + " = " + 15;
String[] args = null;
I have database which contains "date" column and "item" column.
I want that user could update specific row in the database.
I trying to do it with update method in SQLiteDatabase class.
My problem is that i dont know how to make update method find exactly the row i want.
I saw some example that use it with parameters from one word.
like this:
ourDatabase.update(tableName, cvUpdate, rowId + "=" + item , null);
My problem is that i want to update the row that have specific item and date. so the name of the item alone is not enough.
I tried this code below but its didnt work, hope youll can help me.
public void updateEntry(String item, String date) throws SQLException{
String[] columns = new String[]{myItem, myDate};
Cursor c = ourDatabase.query(tableName, columns, null, null, null, null, null);
long position;
ContentValues cvUpdate = new ContentValues();
cvUpdate.put(date, myDate);
cvUpdate.put(item, myExercise);
int itemAll = c.getColumnIndex(myItem);
int dateAll = c.getColumnIndex(myDate);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if (c.getString(itemAll).equals(myItem) && c.getString(dateAll).equals(myDate))
{
position = c.getPosition();
break;
}
}
ourDatabase.update(tableName, cvUpdate, rowId + "=" + position , null);
}
First, the columns String[] is supposed to contain column names, such as "_ID", or whatever are the column names you have used. Given that you compare the content of the column myItem with the object myItem, I assume there is a confusion somewhere here.
Secondly, rowId and position are different things in SQL, especially if you delete rows, as the row id usually is autoincrement, and especially since your query is not explicitely sorted. Replacing c.getPosition() by c.getLong(c.getColumnIndex(ID_COLUMN)) would make more sense.
Thirdly, sql is nice because you can query it. For example, rather than get all items and loop to find the matching date and item, you can :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
Cursor c = ourDatabase.query(tableName, columns, whereClause, whereArgs, null, null, null);
instead of your for loop.
Forthly, you can even make the query in the update :
String whereClause = ITEM_COLUMN + " = ? and " + DATE_COLUMN + " = ?";
String[] whereArgs = new String[] { item, date };
ourDatabase.update(tableName, cvUpdate, whereClause, whereArgs);
Extra tip: use full caps variable names for contants such as column names, it help with readability.
I'd like to get the total of all records. I'd be getting the records from my meal_serving. I'd like to add up all the values. For example, please check this:
Meal Serving
1st row - 8
2nd row - 2
3rd row - 3
Total is: 13
This is what I've got:
public String getTotal() {
String[] column =
new String[]{ KEY_SERVING, "sum(meal_serving)" };
Cursor c =
ourDatabase.query( DATABASE_TABLE, column, null, null, null, null, null );
String result = "";
int iSERVING = c.getColumnIndex( KEY_SERVING );
for ( c.moveToFirst(); ! c.isAfterLast(); c.moveToNext() ){
result = result + c.getString( iSERVING );
}
return result;
}
But only the last record is showing. What's wrong?
You'll need to do
String[]{ "sum(meal_serving) as " + KEY_SERVING };
Instead of your current column string array. That will generate the sum and name it so you can retrieve it.
You might need to make up a unique name if KEY_SERVING is one of your other columns too.