I need some help with using the database that I created. I need to access the last item in the database. This is my code that gets a single item. How can I change it to only get the last?
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToFirst();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, KEY_ID + " DESC", "LIMIT 1");
if the id uniquely identifies the user then you will be getting only one row as the result for the id you are passing so you dont have to worry about it is the last or first in the database. if it is just that you want the last row in your database then you dont have to pass an id you can do a select * and after retrieving move the cursor to last ie cursor.moveToLast().
Do this if you just want the last row
User getuser() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, null,
null, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
and your call can be like this
User currentUser = db.getUser();
If you are passing an id to get a user details an the id uniquely identifies the user then what you have done will work
Are you perhaps looking for cursor.moveToLast()? This will move the cursor to the last record selected from your query. You can then get the fields values as usual using cursor.getString(n) etc.
You simply need to change a little in your code,
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast(); // Change here
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Try this one:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
and if you want to get the data from last to first use this codes:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
int count = c.getCount();
for(int i = 0; i < count; i++){
c.movetoPrevious();
}
Related
The below code gives me single row using id:
public DataObject getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_PHN, KEY_PTYPE, KEY_PDATE ,KEY_PNAME, KEY_PNOTE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null) cursor.moveToFirst();
DataObject contact = new DataObject(Integer.parseInt(cursor.getString(0)),cursor.getString(1),
cursor.getString(2), cursor.getString(3),cursor.getString(4),cursor.getString(5));
cursor.close();
return contact;
}
but I want is using a string,for eg: if my database is as below, then I want get the whole row, when I say name2 (that means it should return address2 and phno2)
name1 address1 phnno1
name2 address2 phnno2
name3 address3 phnno3
name4 address4 phnno4
I use your example to build my answer.
You can do :
Cursor cursorTable = db.query(CONTACTS,
new String[]{NAME, ADDRESS, PHNNO},
NAME + "= ?",
new String[]{"name2"},
null,
null,
null);
But if you want this to return only information for name2 you have to be sure there is only one row with "name2" as NAME
i have created this method in dbHelper class.
I am calling this method from mainActivity using onClickListener to show column 1 of each row one by one by changing cursor position.
i need to move the cursor to next row each time the button is clicked to show the string in Column1 in a textView.
i am new to android and programming too, so please bear with me.
public String nextData() {
String nQuote = "";
int i=0;
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_IQ };
Cursor resultSet = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
resultSet.movetoPostion(i);
if (i==0||i!=resultSet.getcount()){
resultSet.moveToNext();
nQuote = resultSet.getString(1);
i++;
}
return nQuote;
}
use this,
public String nextData(int position) {
String nQuote = "";
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_IQ};
Cursor resultSet = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (position >= 0 && position < resultSet.getCount()) {
resultSet.moveToPosition(position);
nQuote = resultSet.getString(1);
}
resultSet.close();
return nQuote;
}
I use this function to get specific data from SQlite:
SearchRes getSresultByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
SearchRes searchres = new SearchRes(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
return searchres;
}
And it works just fine, I need to create similar function to test if value is exist in the table, so I tried this:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor == null)
return false;
else
return true;
}
But I always get TRUE. Can you help me figure out what is the problem?
you should not be checking if cursor is null you should be checking if anything exists in the cursor
if(cursor.moveToFirst()){
return true
}else{
return false;
}
You can try Cursor getCount() to check the number of rows in the result of the query.. Following is the sample code:
boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_WIKIRES, new String[] { KEY_ID,
KEY_SNAME, KEY_SJSON }, KEY_SNAME + "=?",
new String[] { name }, null, null, null, null);
if (cursor.getCount() > 0)
return true;
else
return false;
}
answer by #tyczj is also good..
I've got an SQLite database in my Android app. I want to be able to select a random row based on the YEAR column in the database. I'm already able to select a random row from the entire table like so:
public String[] getTEST3RandChVerScrip() {
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, null,
null, null, null, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast();) {
String colStrings[] = new String[3];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
colStrings[2] = cursor.getString(2);
return colStrings;
}
}
return null;
}
But when I try and add a selection argument, the app errors out. Here's where I've added the selection argument:
public String[] getTEST3RandChVerScrip() {
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR = "1964",
null, null, null, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast();) {
String colStrings[] = new String[3];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
colStrings[2] = cursor.getString(2);
return colStrings;
}
}
return null;
}
Is the syntax incorrect in KEY_YEAR = "1964"? If so any idea what it should be?
As per tyczj's answer I've modified the query to:
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR + "=?",
new String[] {"1964"}, null, null, null);
... and I'm still getting an error that says: 06-20 15:18:33.644: E/AndroidRuntime(4758): android.database.sqlite.SQLiteException: near "WHERE": syntax error: , while compiling: SELECT make, model, note FROM provtable Order BY RANDOM() LIMIT 1 WHERE year=?
You shouldn't put order by in the table name area
this.db.query("provtable",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR + "=?",
new String[] {"1964"}, null, null, "RANDOM() LIMIT 1");
it should be
KEY_YEAR+"=1964"
however better syntax wound be to put your selection as KEY_YEAR+"=?" and then you selectionArgs should be new String[] {"1964"}
also post the error
Here is a code/method to find if some name exists in the table or not..
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
I already have a function to get all names in an arrayList. I can call it before calling the above function to solve my problem. But I want to ask about is there any other (straight) way to do it
When you call cursor.moveToFirst() it will return true if there is a valid result there, or false in the case no results are found. If cursor.moveToFirst() returns false, then calling any of the getXXX() methods will fail.
Try something like this:
if( cursor.moveToFirst() )
{
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
}
cursor.close();
Note that the Cursor returned from SQLiteDatabase.query is guaranteed to be non-null.
if (cursor == null)
Toast.makeText(getApplicationContext(), "No Records Exist", Toast.LENGTH_SHORT).show();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if(cursor.moveToFirst()){
do {
Double lat = cursor.getDouble(2);
Double lon = cursor.getDouble(1);
} while (trackCursor.moveToNext());
}
Here is a code for getting all the contacts in a list from the table...
/**
* Getting all the contacts in the database
*/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
Then it is invoked in another function that returns "true" if name is present in the table "false" otherwise...
/**
* checks if name already present in the database
* #param name
* #return
*/
public boolean checkDbData(String name){
List<Contact> contactList =getAllContacts();
boolean checkName = false ;
for(Contact cn: contactList){
String dbName = cn.getName();
if(name.equals(dbName)){
checkName = true ;
}
}
return checkName;
}
And if this function returns "true", then the above given function is invoked to get the contacti.e.
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
Note: we can also get this contact from the contactList, both can be used to get the required contact (i.e. "name" in this case)