Select a row and get data (Android Studio SQLlite) - java

I have a table with two columns (productname and answer).
When I enter a number, the cursor needs to go to that row and get that data.
For example, if I give 5 as a number to QuestionID,
the c1 cursor should go to the 5th cell in column productname and
the c2 cursor should go to the 5th cell in column answer.
Please look at the code below...
public void getexactrow(String QuestionID){
this._QuestionID=QuestionID;
SQLiteDatabase db = getWritableDatabase();
String colomn1 = "SELECT " +COLUMN_PRODUCTNAME+ " FROM " + TABLE_PRODUCTS + " WHERE 1";
String colomn2 = "SELECT " +COLUMN_ANSWER+ " FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c1 = db.rawQuery(colomn1, null);
Cursor c2 = db.rawQuery(colomn2, null);
c1.move(Integer.parseInt(_QuestionID));
c2.move(Integer.parseInt(_QuestionID));
if (c1.getString(c1.getColumnIndex("productname")) != null) {
_SendQuestion = c1.getString(c1.getColumnIndex("productname"));
}
if (c2.getString(c2.getColumnIndex("answer")) != null) {
_SendAnswer = c2.getString(c2.getColumnIndex("answer"));
}
}

Update the code with taking in example below code, using single cursor and removing where clause with 1 as value
public void getexactrow(String QuestionID){
SQLiteDatabase db = getWritableDatabase();
String colomn1 = "SELECT " +COLUMN_PRODUCTNAME+ ","+COLUMN_ANSWER+" FROM " + TABLE_PRODUCTS;
Cursor c1 = db.rawQuery(colomn1, null);
c1.move(Integer.parseInt(QuestionID));
if (c1.getString(c1.getColumnIndex("productname")) != null) {
_SendQuestion = c1.getString(c1.getColumnIndex("productname"));
}
if (c1.getString(c1.getColumnIndex("answer")) != null) {
_SendAnswer = c1.getString(c1.getColumnIndex("answer"));
}

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

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.

How to check existing SQLite db in Android

I want to check SQLite database table record . Whether table row is exist then update or delete my table row or.When I run my app the table row insert duplicate.How to avoid it . I want to insert newly record when I run first time , when open the activity second time my database is update. I have tried but db is not show record there.Please help me.Thanks to appreciates
Here is my code
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id = ?",
new String[]{_id});
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
My fragment code
if(jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if(dbhelper.Exists(str_CompanyId))
{
Log.e("Row is Already ","Exist");
}
else
{
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data insert into ", " Company Table Succesively !!! = ");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Use below method
public boolean isIDExist(String _id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Company, new String[] { KEY_your_id}, KEY_your_id + "=?" ,
new String[] { String.valueOf( _id)}, null, null, null, null);
if (cursor != null){
if(cursor.getCount() == 0){
cursor.close();
db.close();
return false;
}else{
cursor.close();
db.close();
return true;
}
}
return false;
}
Change your code to this
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id ='"+ String _id + "'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return true;
}
I think the simplest way to do this is to create a Primary Key in the table, and then use INSERT OR REPLACE command instead of just using INSERT.
INSERT OR REPLACE will automatically REPLACE the existing row when it encounters a Primary Key violation, with the new data being inserted.
In this case, you can have OrgId as the Primary Key and if you have some record like:
ORGID ORGNAME
1 ABC
and you insert like INSERT OR REPLACE INTO ORG_MASTER(1,'EFG'), the table will now have one row like
ORGID ORGNAME
1 EFG
Hope this helps :)

Categories