Using SQLite in Android to get RowID - java

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.

Related

Data not delete using sqllite database

How to delete specific data using sqlite database via android.
db.delete("tbl_rmd", "rmd_typ = ? ", new String[]{id});
error : index not found
You must determine whether or not the data exists in the sqlite database.
public boolean checkIfRecordExist(String tableName, String columnName, String fieldValue) {
SQLiteDatabase database = this.getReadableDatabase();
String Query = "Select * from " + tableName + " where " + columnName + " =? ";
Cursor cursor = database.rawQuery(Query, new String[]{fieldValue});
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
now modify your code like this...
if (checkIfRecordExist("tbl_rmd", "rmd_typ", id)) {
db.delete("tbl_rmd", "rmd_typ = ? ", new String[]{id});
}

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.

How to pass specific string to get the specific value from database android

I have three columns where trailer_number and trailer_id are strings
id trailer_number trailder_id
1 trailer1 766
2 trailer2 899
3 trailer3 577
Now if I pass the trailer_number, how to get the specific trailer_id.
Say for eg: trailer1 if i pass, how to return the string "766"?
I can do only if that specific string is exist or not but I am cluless how to pass to get the specific id.
public boolean isExist(String strTrailerNumber) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE TRAILER_NUMBER = '" + strTrailerNumber + "'", null);
boolean exist = (cur.getCount() > 0);
cur.close();
db.close();
return exist;
}
Tryout as below :
String query = "SELECT trailder_id FROM TABLE_NAME WHERE TRAILER_NUMBER =" + strTrailerNumber ;
Cursor cursor = database.rawQuery(query,null);
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() != true) {
string trailder_id = cursor.getString(cursor.getColumnIndex("trailder_id")));
}
}
There might be some syntax error in Query, change it. It will work.
use the query
"SELECT trailder_id FROM " + TABLE_NAME + " WHERE TRAILER_NUMBER = '" + strTrailerNumber + "'"
and use
cursor.moveToFirst()
String trailer_id = cursor.getString(0)
to get the trailder_id

android - prevent duplicate insert data in SQLite

I just learned to use sqlite on android. how to prevent duplicate data when it will be inserted .. so, when there is same data entry, it will overwrite the data?
here I attach the code snippet:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FAVORIT_TABLE = "CREATE TABLE " + Constant.favoritDBtable + "("
+ Constant.id_postFav + " INTEGER PRIMARY KEY AUTOINCREMENT," + Constant.titleFav + " TEXT," + Constant.namaPerusahaanFav + " TEXT,"
+ Constant.lokasiFav + " TEXT," + Constant.kriteria_1Fav + " TEXT," + Constant.kriteria_2Fav
+ " TEXT," + Constant.kriteria_3Fav + " TEXT," + Constant.gajiFav + " TEXT," + Constant.img_logoFav
+ " TEXT," + Constant.tanggalFav + " TEXT);";
public String addFavorit(Favorit favorit){
SQLiteDatabase db = this.getWritableDatabase();
// long rows = 0;
ContentValues values = new ContentValues();
values.put(Constant.titleFav, favorit.getTitleFav());
values.put(Constant.namaPerusahaanFav, favorit.getNamaPerusahaanFav());
values.put(Constant.lokasiFav, favorit.getLokasiFav());
values.put(Constant.kriteria_1Fav, favorit.getKriteria_1Fav());
values.put(Constant.kriteria_2Fav, favorit.getKriteria_2Fav());
values.put(Constant.kriteria_3Fav, favorit.getKriteria_3Fav());
values.put(Constant.gajiFav, favorit.getGajiFav());
values.put(Constant.img_logoFav, favorit.getImg_logoFav());
values.put(Constant.tanggalFav, favorit.getTanggalFav());
db.insert(Constant.favoritDBtable, null, values,);
Log.d("Favorit saved: ", "Success 200 OK");
return null;
}
MainActivity.java
#Override
public void onClick(View v) {
if (job.getTitle() != null && job.getLokasi() != null){
saveToFavoritDB();
}
}
private void saveToFavoritDB() {
Favorit favorit = new Favorit();
favorit.setTitleFav(job.getTitle());
favorit.setGajiFav(job.getGaji());
Log.d(TAG, "gaji " + job.getGaji());
db.addFavorit(favorit);
List<Favorit> favList = db.getAllFavorit();
for (Favorit each : favList) {
String log = "ID: " + each.getTitleFav() + ", Name: " + each.getLokasiFav() + ", Phone: " + each.getGajiFav();
Log.d(TAG, "saveToFavoritDB: " + String.valueOf(db.getCountFavorit()));
Log.d(TAG, "Hasil: " + log);
}
}
hope you can help me
Before go through addFavorit method, you can add one method to check whether the data is already exists to prevent duplicate.
boolean check;
check = checkDuplicate(...,...,...,id_post); // check whether data exists
if(check == true) // if exists
{
Toast.makeText(MainActivity.this, " Data Already Exists", Toast.LENGTH_LONG).show();
}else{
db.addFavorit(favorit);
}
public static boolean checkDuplicate(String TableName,String dbfield, String fieldValue, int id_post) {
String Query = ".... WHERE "+ Constant.id_postFav +"="+ id_post; // your query
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Crate a function to check row is in db or not
private static boolean CheckIsInDBorNot(String titleFav) {
String selectQuery = "SELECT * FROM " + Constant.favoritDBtable + " WHERE " + Constant.titleFav +"'"+titleFav "'";
final SQLiteDatabase db = open();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
than check
if (!CheckIsInDBorNot(commentOrderId, commentId)) {
db.insertOrThrow(Constant.favoritDBtable, null, cVal);
}
It will check and insert
Create method IsItemExist() in your DatabaseHelper class and call this method in you activity class like IsItemExist(name,mobile)
public boolean IsItemExist(String name,String mobile) {
try
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT "+NAME+" FROM "+TABLE+" WHERE "+NAME+"=?",new String[]{name});
Cursor cursor1=db.rawQuery("SELECT "+MOBILE+" FROM "+TABLE+" WHERE "+MOBILE+"=?",new String[]{mobile});
if (cursor.moveToFirst() && cursor1.moveToFirst())
{
db.close();
Log.d("Record Already Exists", "Table is:"+TABLE+" ColumnName:"+NAME);
return true;//record Exists
}
Log.d("New Record ", "Table is:"+TABLE+" ColumnName:"+NAME+" Column Value:"+NAME);
db.close();
}
catch(Exception errorException)
{
Log.d("Exception occured", "Exception occured "+errorException);
// db.close();
}
return false;
}

Quotes around strings in sqlite query

I have a db made with this statement:
DATABASE_CREATE = "create table "
+ TABLE_BANDS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text unique not null, " + COLUMN_GENDER + " text, " + COLUMN_POPULARITY + " real not null);";
I add to it a row with this statement:
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\"" + bandName.trim().toLowerCase() + "\"");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
I get insertId > 0, so I think that the insertion was ok.
Then I try to select a row that I just inserted with this code:
public Band getBand(String name) {
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \"" + name.trim().toLowerCase() + "\"", null,
null, null, null);
cursor.moveToFirst();
Band band = getBandFromCursor(cursor);
cursor.close();
return band;
}
But it always returns me a cursor with 0 length.
I tried to remove the quotes around the name, but after it query doent work.
Besides I tried to use a rawQuery, but the result is the same.
Cursor cursor = database.rawQuery("Select * from " + BandsSQLiteOpenHelper.TABLE_BANDS + " where band_name = \"" + name.trim().toLowerCase() + "\"", null);
UPDATE:
I tried single quotes:
Cursor cursor = database.query(BandsSQLiteOpenHelper.TABLE_BANDS,
new String[] {BandsSQLiteOpenHelper.COLUMN_NAME, BandsSQLiteOpenHelper.COLUMN_POPULARITY}, BandsSQLiteOpenHelper.COLUMN_NAME + " = \'" + name.trim().toLowerCase() + "\'", null,
null, null, null);
and
private long addBand(String bandName, String gender) {
ContentValues values = new ContentValues();
values.put(BandsSQLiteOpenHelper.COLUMN_NAME, "\'" + bandName.trim().toLowerCase() + "\'");
values.put(BandsSQLiteOpenHelper.COLUMN_POPULARITY, 1);
values.put(BandsSQLiteOpenHelper.COLUMN_GENDER, "");
long insertId = database.insert(BandsSQLiteOpenHelper.TABLE_BANDS, null,
values);
return insertId;
}
As before insertion is ok, selection returns 0 rows.
When inserting the values, I doubt you need to put the double quotes around the values you insert since you specified in your DB Creation string that the fields are TEXT.
As for your rawQuery, try this:
"SELECT * FROM " + BandsSQLiteOpenhelper.TABLE_BANDS + " WHERE band_name = '" + name.trim().toLowerCase() + "'";
Try single quotes instead of double quotes when using Strings as identifiers in WHERE statements.

Categories