android database adding more than needed - android

private static String[] FROM = { _ID, DESCRIPTION, DATE, TITLE };
//private static String ORDER_BY = _ID + " DESC" ;
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
SQLiteDatabase db = post.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
null, null);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
TextView tv = new TextView(this);
// Stuff them all into a big string
StringBuilder builder = new StringBuilder(
"Saved events:\n" );
while (cursor.moveToNext()) {
// Could use getColumnIndexOrThrow() to get indexes
long id = cursor.getLong(0);
String description = cursor.getString(1);
String date = cursor.getString(2);
String title = cursor.getString(3);
builder.append(id).append(": " );
builder.append(description).append(": " );
builder.append(date).append(": " );
builder.append(title).append("\n" );
}
// Display on the screen
tv.setText(builder);
this.setContentView(tv);
}
So the showEvents function which is supposed to display the database is displaying a larger database than I created. It is showing 19 rows, yet I only called the insertorthrow function twice so it should have two rows, so I don't know how it can have more than 19 rows. I feel the problem may lie in my getEvents() function or showEvents() function which returns the cursor. Help would be appreciated.

Using db shell go to the location and delete the database .

Related

How to write a sqlite query to get specific data?

I want to get the first name, middle name and last name of a student whose userid is used for login. I have written this particular piece of code but it stops my application.
I have used both the ways like database.query() and .rawquery() also.
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
I should get whole name in the string.
You have a number of issues.
Attempting to use String data = cursor.getString(cursor.getColumnIndex("First_Name"));,
will result in an error because you have not moved the cursor beyond BEFORE THE FIRST ROW and the attempt to access the row -1 will result in an exception (the likely issue you have encountered).
you can use various move??? methods e.g. moveToFirst, moveToNext (the 2 most common), moveToLast, moveToPosition.
Most of the Cursor move??? methods return true if the move could be made, else false.
You CANNOT close the database and then access the Cursor (this would happen if the issue above was resolved)
The Cursor buffers rows and then ONLY when required.
That is The Cursor is when returned from the query method (or rawQuery) at a position of BEFORE THE FIRST ROW (-1), it's only when an attempt is made to move through the Cursor that the CursorWindow (the buffer) is filled (getCount() included) and the actual data obtained. So the database MUST be open.
If you want a single String, the full name, then you could use :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
Or alternately :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
the underlying query being SELECT First_Name||" "||Middle_Name||" "||LastName AS fullname FROM student_table; so you concatenate the names as part of the query which returns just one dynamically created column named fullname.

How to get specific value from DB by id

How to get specific value from DB by id.
This is my table: TABLE-RECORDS-(name of table) and KEY-ID , KEY-PRICE ... I'm trying to get KEY-PRICE by KEY-ID and can not. How to do it?
I don't know if this is exactly what you are looking for, but this is the query.
SELECT key-price FROM table-record WHERE key-id='id number you need';
// please change the column names of database if i have mistaken
public Cursor getCursor(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String from[] = {"key-price"};//this is the edit1
String where = "key-id=?";//this is the edit2
String[] whereArgs = new String[]{String.valueOf(id)+""}; //this is the edit3
Cursor cursor = db.query(true, table-records, from, where, whereArgs, null, null, null, null);
return cursor;
}
//just call this function and see the magic
private int getPrice(int id) {
Cursor c = getCursor(id);
int price=-1;
if(c != null)
{
while(c.moveToNext){
//assuming price is an integer
price = c.getInt(0);//edit 4
// use these strings as you want
}
}
return price;
}

android sqlite not update all rows one column

I am new on android development. I have a table with 9 columns who can store products , first is _id autoincrement, and the other two last insertdays and days.
In insertdays i store current date as integer after convert date to int. In the days column i store the number of days to expire a product.
I made 3 methods getDays(), getInsertdate(), expCheck().
The getDays return to expCheck the days for each row, its working
The getInsertdate return to expCheck the inserted date its working
The problem is, when i try to update my database , expCheck() called on onCreate() and onResume() methods, the values of days column for all rows(products) does not updated. With expCheck() method i try to reduce the number of days for each day who pass.
My database table in the photo the last column must reduce by one if pass one day, reduce by 2 each row if pass two days e.t.c ... Can anyone help me !!!
public int getInsertDate(int productId){
int output=0;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projectionG = {
ProductEntry.COLUMN_PRODUCT_INSERTDATE};
Cursor cursor1 = db.query(TABLE_NAME, projectionG, " _id = ?", new String[] {String.valueOf(productId) }, null, null, null, null);
if (cursor1 !=null) {
if (cursor1.moveToFirst()) output = cursor1.getInt(7);
}
cursor1.close();
return output;
}
public int getDays(int productId){
int output=0;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projectionD = {ProductEntry.COLUMN_PRODUCT_DAYS};
Cursor cursor = db.query(TABLE_NAME, projectionD, " _id = ?", new String[] {String.valueOf(productId) }, null, null, null, null);
if (cursor !=null) {
if (cursor.moveToFirst() ) {
output = cursor.getInt(8);
}
}
cursor.close();
return output;
}
public void expCheck(){
//Read current date
Calendar calendar = Calendar.getInstance();
SQLiteDatabase db=mDbHelper.getWritableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
ProductEntry.COLUMN_PRODUCT_DAYS
};
// Perform a query on the products table
Cursor cursor = db.query(
ProductEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null); // The sort order
int j = toJulianDate(calendar.getTime());
Toast.makeText(this, "date is" + j,Toast.LENGTH_SHORT).show();
//Method getInsertDate return the insert date of product to database
int currentInsertdate = getInsertDate(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_INSERTDATE));
// Method getDays return the number of days to expire a product
int currentDays = getDays(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_DAYS));
currentDays = currentDays - (j - currentInsertdate);// calculate the new amount of remaining days to expire th product
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_PRODUCT_DAYS, currentDays);
//update all rows
db.update(TABLE_NAME, values, null, null);
}

row id from database

i am trying to do a query of my database for a string lets call it "Test" and then find out what row that particular string is in and save that number to use. I thought i had this figured out before but now it is not working for some reason and i get an error saying no such column "Test".
here is my code
public String getRow(String value){
ContactDB db = new ContactDB(this);
db.open();
Cursor curs = db.getId(value);
String test = curs.getString(curs.getColumnIndex(db.NAME));
curs.close();
Log.v("Contact", "Row ID: " + test);
db.close();
return test;
}
"Test" is sent into that as value
this is in my database
//---retrieve contact id---
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}
i dont remember changing anything from when i first tested it so i dont know why it wont work now
There are 2 errors that i could notice:
In the query
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
only the ID column is selected whereas you are trying to fetch details for column NAME
String test = curs.getString(curs.getColumnIndex(db.NAME));
include the name column as well in the select clause : something like
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,NAME},where,null,null,null,null);
In the where clause you need to write the condition string excluding "where"
in your case String where contains value "Test". Hence the filter condition should be as
String whereClasue = NAME + " = '" + where + "'";
The query should be something like this:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,PHONE_NUMBER,NAME},NAME + " = '" + where + "'",null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}

Get last inserted value from sqlite database Android

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}
I have tried with MAX, but I must be using it wrong. Is there another way?
Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.
I hope this helps.
Use
SELECT last_insert_rowid();
to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then
SELECT * from SQLITE_SEQUENCE;
will tell you the values for every table.
To get the last row from the table..
Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
Use moveToLast() in Cursor interface.
From android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* #return whether the move succeeded.
*/
boolean moveToLast();
Simple example:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
Or you can get the last row when insertion(Which is #GorgiRankovski have mentioned):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
Also their is a multiple ways you can do this using query:
One is expressed by #DiegoTorresMilano
SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
(If you want each and every value, use * instead of id)
If you want the last_insert_id just afert a insert you can use that :
public long insert(String table, String[] fields, String[] vals )
{
String nullColumnHack = null;
ContentValues values = new ContentValues();
for (int i = 0; i < fields.length; i++)
{
values.put(fields[i], vals[i]);
}
return myDataBase.insert(table, nullColumnHack, values);
}
The insert method returns the id of row just inserted or -1 if there was an error during insertion.
long id = db.insert("your insertion statement");
db is an instance of your SQLiteDatabase.
Try this:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
/**
* #return
*/
public long getLastInsertId() {
long index = 0;
SQLiteDatabase sdb = getReadableDatabase();
Cursor cursor = sdb.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLENAME},
null,
null,
null,
null
);
if (cursor.moveToFirst()) {
index = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return index;
}
I use this
public int lastId(){
SQLiteDatabase db =
this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from resep", null );
res.moveToLast();
return res.getInt(0);
}
In your DbHelper class,
public long getLastIdFromMyTable()
{
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
return st.simpleQueryForLong();
}

Categories

Resources