How to check existing SQLite db in Android - java

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 :)

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 insert data to a table that includes a foreign key in Android

I have a dictionary database and want to insert words to MyList table. But the words have to exist in Words table because MyList has foreign key. I have already written a code but it returns empty object. What is the wrong with that? Or is there an another way to do it? please help
Database
db.execSQL("CREATE TABLE IF NOT EXISTS \"Words\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT\n" +
");");
db.execSQL("CREATE TABLE \"MyList\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT,\n" +
"\tFOREIGN KEY(\"Id\") REFERENCES \"Words\"(\"Id\")\n" +
");");
my methods
public String InsertWordToList(DbConnection data,String kelime){
Word yeni=null;
SQLiteDatabase db= data.getWritableDatabase();
ContentValues values= new ContentValues();
String msg;
Boolean bool = ifExists(kelime,db);
if(bool){
msg= "kelime zaten var";
}
else {
yeni = FindWord(kelime, db);
if(yeni!=null){
Log.e("yeni id",Integer.toString(yeni.getId()));
values.put("Id", yeni.getId());
values.put("Name", yeni.getName());
values.put("Mean", yeni.getMean());
db.insertOrThrow("MyList", null, values);
msg="kelime eklendi";
}
else msg="kelime databasede kayırlı değil";
}
db.close();
return msg;
}
public Word FindWord( String kelime, SQLiteDatabase db){
Word w=null;
Cursor c = db.rawQuery("SELECT * FROM Words WHERE Name = ?", new String[] {kelime});
while (c.moveToNext()){
w = new Word(c.getInt(c.getColumnIndex("Id"))
,c.getString(c.getColumnIndex("Name"))
,c.getString(c.getColumnIndex("Mean")));
}
c.close();
if(w!=null){
return w;}
else return null;
}
public Boolean ifExists (String kelime, SQLiteDatabase db) {
Word w=null;
Cursor c = db.rawQuery("SELECT * FROM Words WHERE Name = ?", new String[] {kelime});
while (c.moveToNext()){
w = new Word(c.getInt(c.getColumnIndex("Id"))
,c.getString(c.getColumnIndex("Name"))
,c.getString(c.getColumnIndex("Mean")));
}
c.close();
if(w!=null) return true;
else return false;
}

Cannot Fetch a Data From Database

First of all i'm new to Android Development.
I'm having some issues with fetching data from database. Whenever i try to fetch a data, the cursor is being empty.
Here is my code:
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> List = new ArrayList<Word>();
if(cursor != null){
cursor.moveToFirst();
while (cursor.moveToNext()){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return List;
}
The size of the cursor is always 1 but the size of the "List" variable is always 0.
I didn't understand the problem, thanks for helping me.
You are shifting the cursor position twice. Just remove the line cursor.moveToFirst(); The moveToNext method is sufficient as it moves to the first position on the first iteration.
you can use this code:
1-If you need first row:
if(cursor != null){
cursor.moveToFirst();
if(cursor.isAfterLast() == false){
List.add(new Word(cursor.getString(cursor.getPosition())));
}
}
2- if you need several rows :
if(cursor != null){
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
List.add(new Word(cursor.getString(cursor.getPosition())));
cursor.moveToNext();
}
}
I checked everything but your recommendations didn't worked. Just to be sure: I want to fetch all rows.
Try like this
public ArrayList<Word> getWords(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
ArrayList<Word> list = new ArrayList<Word>();
if(cursor != null){
while (cursor.moveToNext()){
list.add(new Word(cursor.getString(cursor.getPosition())));
}
}
cursor.close();
db.close();
return list;
}
I just realised that the program does not go into the while loop in the code that i given above. I think there is a problem with database.
I used that query to create database:
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME_TURKISH + " TEXT, " +
COLUMN_NAME_ENGLISH + " TEXT, " +
COLUMN_NAME_GERMAN + " TEXT, " +
COLUMN_NAME_FRENCH + " TEXT, " +
COLUMN_NAME_ARABIC + " TEXT, " +
COLUMN_NAME_RUSSIAN + " TEXT, " +
COLUMN_NAME_SPANISH + " TEXT, " +
COLUMN_NAME_ITALIAN + " TEXT)";
I feel like a idiot because i forgot to type the database name at the constructor method like that:
Old
super(context, null, null, 1);
Now
super(context, "database", null, 1);
Thanks for your help!

Select a row and get data (Android Studio SQLlite)

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"));
}

Categories