Android: How to change value of sqlite column - java

I am relatively new to using sqlite in the android world and I currently I my sqlite database set up like the following:
db.execSQL("CREATE TABLES " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER DEFAULT 0, "
+ KEY_PIN + " INTEGER DEFAULT 0);");
And I have the following methods to insert data into the database:
// function to add lockers to database
public long createLockerEntry(String lockerNumber, int status) {
ContentValues cv = new ContentValues();
cv.put(KEY_LOCKERNUMBER, lockerNumber);
cv.put(KEY_STATUS, status);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
// function to create a pin for the locker
public void createPin(String lockerNumber, int pin, int status) {
}
// function to remove pin
public void removePin(String lockerNumber, int pin, int status) {
}
My intentions are to add a pin number for a certain locker number to the KEY_PIN column within the method Create pin and then change the status value to 1. I would assume I would use the where clause statement but I am not completely sure about the syntax or if that is the write approach. Any suggestions?

The method you want is update()
You can read about it by searching for "update" on this page:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
One way to use this would be:
// function to create a pin for the locker
public void createPin(tring lockerNumber, int pin, int status) {
ContentValues cv = new ContentValues()
cv.put(KEY_PIN, pin);
cv.put(KEY_STATUS, status);
ourDatabase.update(DATABASE_TABLE, cv, KEY_LOCKERNUMBER + " = ?"
, new String[] {lockerNumber});
}

Here's an example where I toggle the value of an entry. It is an int value used as binary (i.e. 1 or 0).
The two methods checkAsWildTest, and uncheckAsWildTest.
public void checkAsWildTest(Cursor c, int val) {
assertDbOpen();
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("row selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, val);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
public void uncheckAsWildTest(Cursor c) {
assertDbOpen();
int unchecked = 0;
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("column selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, unchecked);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
I believe you can work with this, and modify it for your purposes.

Related

How to get all data from a single SQLite database column for calculating total price

I'm currently making a shopping app with a shopping cart. I got the listview to display with the proper quantity and price but now have problems with trying to show the total price for checkout. There are 2 problems I'm facing :
How to get data from a whole column, right now I am only able to get data from the first index of the intended column.
When I clear the database/clear the cart, the app crashes, saying there is a null. Probably due to the cursor not able to get the read anything from the database.
CartDatabaseHelper.java getCartPrice() method
public Double getCartPrice() {
String query = "SELECT * FROM " + CartContract.CartEntry.TABLE_NAME + " WHERE Cart_Meal_Price";
SQLiteDatabase dbCart;
dbCart = this.getWritableDatabase();
Cursor cursor = dbCart.rawQuery(query, null);
cursor.moveToFirst();
do{if (cursor!=null) {
Double totalPrice = cursor.getDouble(2);
Double sum =+ totalPrice;
return sum;
} else {
return 0.00;
}}while(cursor.moveToNext());
}
CartDataBaseHelper.java Declaration and Initialization of cart database
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CartDatabase";
public static final String CART_TABLE = "CartTable";
public static final String CREATE_CART_TABLE = "CREATE TABLE " + CartContract.CartEntry.TABLE_NAME + " ( " +
CartContract.CartEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
CartContract.CartEntry.COLUMN_NAME + " TEXT ," +
CartContract.CartEntry.COLUMN_PRICE + " REAL , " +
CartContract.CartEntry.COLUMN_QUANTITY + " REAL ) " ;
SummaryActivity.java getTotalPrice() method
public void getTotalPrice() {
cartDB = new CartDatabaseHelper(this);
double total = cartDB.getCartPrice();
totalprice.setText("Total Price : RM" + total);
}
SummaryActivity.java Clear database onClickListener
clearthedata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int deletethedata = getContentResolver().delete(CartContract.CartEntry.CONTENT_URI, null, null);
cartDB = new CartDatabaseHelper(context);
double total = cartDB.getCartPrice();
if (cartDB != null) {
totalprice.setText("Total Price : RM" + total);
} else {
totalprice.setText("Total Price : RM0.00");
}
}
});
If you want to get the sum of all the values of the column CartContract.CartEntry.COLUMN_PRICE in the table, then you need a query like:
SELECT COALESCE(SUM(price), 0) FROM tablename
Here COALESCE() is used to return 0 just in case the table is empty.
So your code should be:
public double getCartPrice() {
String query = "SELECT COALESCE(SUM(" + CartContract.CartEntry.COLUMN_PRICE + "), 0) FROM " + CartContract.CartEntry.TABLE_NAME;
SQLiteDatabase dbCart = this.getWritableDatabase();
Cursor cursor = dbCart.rawQuery(query, null);
cursor.moveToFirst();
double total = cursor.getDouble(0);
cursor.close();
dbCart.close();
return total;
}
If you want to delete all the rows of the table, then:
SQLiteDatabase dbCart = this.getWritableDatabase();
dbCart.delete(CartContract.CartEntry.TABLE_NAME, null, null);

Adding long number to INTEGER SQLite [duplicate]

This question already has answers here:
"Integer number too large" error message for 600851475143
(8 answers)
Closed 2 years ago.
I'm trying to store a long number (i.e. 9999999999) on a SQLite INTEGER column, and when I try to use ".put" from ContentValues, it doesn't accept, saying it's larger than an integer number.
The interesting thing is that when I tried to create a long variable, I had the same warning.
Bellow there is the code, witch on AndroiStudio gives me the erros:
PS.: sorry for posting it, because there are so many of these kind of question, but I couldn't find a solution looking them.
public class FeedHelperGamer extends SQLiteOpenHelper {
String TAG = "HelperGamer";
//string to create gamerDB
private static final String SQL_CREATE_ENTRIES_Gamer =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_GAMER + " (" +
_ID + " INTEGER PRIMARY KEY," +
COLUMN_GAMER_NAME+ " TEXT," +
COLUMN_GAMER_GAMES + " INTEGER," +
COLUMN_GAMER_HITS + " INTEGER," +
COLUMN_GAMER_POINTS + " INTEGER," +
COLUMN_GAMER_PICTURE + " BLOB," +
COLUMN_GAMEMODE1 + " TEXT," +
COLUMN_GAMEMODE2 + " TEXT," +
COLUMN_GAMEMODE3 + " TEXT," +
COLUMN_GAMEMODE4 + " TEXT," +
COLUMN_GAMEMODE5 + " TEXT)";
private static final String SQL_DELETE_ENTRIES_GAMER =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_GAMER;
// If you change the database schema, you must increment the database version.
public static final int GAMER_DATABASE_VERSION = 1;
public static final String DATABASE_NAME_GAMER = "Gamer.db";
public FeedHelperGamer(Context context) {
super(context, DATABASE_NAME_GAMER, null, GAMER_DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES_Gamer);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES_GAMER);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
//insere novo jogador
public long addNewGamer(String tmpGamerName, byte[] imageBytes) {
final SQLiteDatabase db = this.getWritableDatabase();
long number = 999999999999999; //it's useless just created to test the long variable
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put( COLUMN_GAMER_NAME, tmpGamerName );
values.put( COLUMN_GAMER_GAMES, 0 );
values.put( COLUMN_GAMER_HITS, 0 );
values.put( COLUMN_GAMER_POINTS, 9999999999);
values.put( COLUMN_GAMER_PICTURE, imageBytes );
values.put( COLUMN_GAMEMODE1, modeStateFalse );
values.put( COLUMN_GAMEMODE2, modeStateFalse );
values.put( COLUMN_GAMEMODE3, modeStateFalse );
values.put( COLUMN_GAMEMODE4, modeStateFalse );
long newRoId = db.insert( FeedReaderContract.FeedEntry.TABLE_GAMER, null, values );
return newRoId;
}
You should change this line
long number = 999999999999999;
like below
long number = 999999999999999L;

SQL - How to return a list of data

I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.

Database doesn't save values using overloading methods

I can't understand why is the database either not saving the values I enter or is it the method which I am using to pull all the data not working correctly. It doesn't throw any errors it just doesn't work. Here is the code:
private static final String QUERY_TRIANGLE_CREATE_TABLE =
"CREATE TABLE " + TRIANGLE_TABLE_NAME + " (" + TRIANGLE_COL_ID + " INTEGER PRIMARY KEY, " +
TRIANGLE_VALUE_A + " TEXT, " + TRIANGLE_VALUE_C + "TEXT, " + TRIANGLE_VALUE_B + " TEXT, " + TRIANGLE_RESULT + " TEXT," + TRIANGLE_HISTORY_INFORMATION + " TEXT" + " );";
public void insertTriangleCalc(String a,String b, String c,String d,String e){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_VALUE_C,c);
values.put(TRIANGLE_RESULT,d);
values.put(TRIANGLE_HISTORY_INFORMATION,e);
database.insert("triangle", null, values);
database.close();
}
public void insertTriangleCalc(String a,String b, String c,String d){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_RESULT,c);
values.put(TRIANGLE_HISTORY_INFORMATION,d);
database.insert("triangle", null, values);
database.close();}
public List<Triangle> ObjectRead() {
List<Triangle> valuesList = new ArrayList<>();
String sql = "SELECT * FROM triangle ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
String valueA = cursor.getString(cursor.getColumnIndex("valueA"));
String valueB = cursor.getString(cursor.getColumnIndex("valueB"));
String valueC="0";
try {
} catch (Exception e){
}
String result = cursor.getString(cursor.getColumnIndex("result"));
String history = cursor.getString(cursor.getColumnIndex("history"));
Triangle triangle = new Triangle();
triangle.id = id;
triangle.valueA = valueA;
triangle.valueB = valueB;
triangle.valueC = valueC;
triangle.Result = result;
triangle.history = history;
valuesList.add(triangle);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return valuesList;
}
Can anyone have a look at it and help me figure out what am I not setting up properly. It works for public void insertTriangleCalc(String a,String b, String c,String d) , but not for public void insertTriangleCalc(String a,String b, String c,String d,String e).
Decided to check from top to bottom and the whole thing was happening because of a missing empty space TRIANGLE_VALUE_C + "TEXT, "
<- here. This has now been resolved and it can finally store data correctly.

Using SQLite in Android to get RowID

I am creating an app to record assignments for different classes. Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. Here is a method I made to find the rowid for a certain class.
public int getIdFromClassName(String className){
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
return res.getColumnIndex("id");
}
However, this always returns a value of -1.
Any thoughts on what to change to return the proper rowid value?
EDIT:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + CLASSES_TABLE_NAME + " " +
"(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
);
db.execSQL(
"create table " + ASSIGNMENTS_TABLE_NAME + " " +
"(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
+ " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");
}
Try this query below to create a new column name rowID:
Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);
And after this query you can fetch the real rowid from the rowID column :
while (cursor.moveToNext()) {
long chatRow=cursor.getLong(
cursor.getColumnIndexOrThrow("rowID"));
}
The column returned by your query is called rowid, so you will not find a column called id.
Ensure that you use the same column name in the query and in the call to getColumnIndex.
And the index of this column is always zero; you also need to read the actual value from the column:
int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
return res.getInt(colIndex);
} else {
// not found
}
However, Android has an helper function that makes it much easier to read a single value:
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
res.getColumnIndex("id") is going to get you the column index of the column with the name "id". and since you are getting -1, it cant find it.. are you sure your id column is not "_id"?
To get this to work you should do something like this..
res.getLong(res.getColumnIndex("_id"));
Cursor.getColumnIndex()
Cursor.getLong()
(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's).
You can try this:
public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}
public int getIdFromClassName(String className) {
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
+ CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
if (res != null) {
if (res.moveToFirst()) {
do {
return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
} while (res.moveToNext());
}
} else {
Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
}
}
Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it.

Categories