insert JSON array data in database table - java

I've searched all around the web for a similar question as what i want but i couldn't find any.
So, I made an app where i get news data from JSON and display it in a list, it's all good, but now i want to add something to it, when there is no internet connection i want to display the latest list viewed. to do this i thought of storing the JSON arraylist in a databases and update it whenever the news change while there's a connection so when there's no connection it'll display the data in the database.
the thing is I'm kind of lost on how to do this..
I made a java class called NewsDBHelper where i create my database and table.
public class NewsDBHelper extends SQLiteOpenHelper {
public static final String LOG_TAG = NewsDBHelper.class.getSimpleName();
private static final String DATABASE_NAME = "news.db";
private static final int DATABASE_VERSION = 1;
public NewsDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_PRODUCTS_TABLE = "CREATE TABLE " + Contract.NewsEntry.TABLE_NAME + " ("
+ Contract.NewsEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ Contract.NewsEntry.COLUMN_SECTION + " TEXT NOT NULL, "
+ Contract.NewsEntry.COLUMN_TITLE + " TEXT NOT NULL, "
+ Contract.NewsEntry.COLUMN_DATE + " BLOB, "
+ Contract.NewsEntry.COLUMN_AUTHOR + " TEXT DEFAULT NULL, "
+ Contract.NewsEntry.COLUMN_URL + " BLOB);";
Log.v(LOG_TAG,SQL_CREATE_PRODUCTS_TABLE);
db.execSQL(SQL_CREATE_PRODUCTS_TABLE);
}
Then in my mind the idea is when the JSON data are stored in an array, i'd take the array values and store them in the table.
private static List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsJSON);
String response = baseJsonResponse.getString("response");
JSONObject object = new JSONObject(response);
;
JSONArray newsArray = object.getJSONArray("results");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject currentNews = newsArray.getJSONObject(i);
String title = currentNews.getString("webTitle");
String section = currentNews.getString("sectionName");
String date = currentNews.getString("webPublicationDate");
JSONArray tag = currentNews.getJSONArray("tags");
String author = null;
if (tag.length() != 0) {
author = tag.getJSONObject(0).getString("firstName");
}
String url = currentNews.getString("webUrl");
News nNews = new News(title, date, section, author, url);
news.add(nNews);
//add news array in the table
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return news;
}
i don't really know how to do this or if it's possible even. if it is how can i do it? or what's the best way to implement my idea?

you're are 70% done with what you're trying to do.
All you need to do now is:
Get a writable database from the NewsDBHelper
Create a content values of the data you want to insert to db
Call the insert() method on the writable database, passing it the content values.
And fetching the persisted data from the database at due time.
Below is a sample code that adopts the above listed steps.
//Create an instance of NewsDBHelper
NewsDBHelper newsDBHelper = new NewsDBHelper(context);
//get a writable database from newsDBHelper
SQLiteDatabase writableDatabase = newsDBHelper.getWritableDatabase();
//create content values of data to persist
ContentValues values = new ContentValues();
values.put("section","Sample section");
values.put("title","Sample title");
values.put("date","1/29/2018");
values.put("author","John Chan");
values.put("url","https://example.com");
//write the data to the database. Notice that the "news" is the table name
writableDatabase.insert("news",null,values);
To fetch data from the database, get a readable database from the newsDBHelper like this:
SQLiteDatabase readableDatabase = newsDBHelper.getReadableDatabase();
//query or read data from the database by calling:
readableDatabase.query(String table, String[] columns, String selection,
String[] selectionArgs,String groupBy, String having,
String orderBy, String limit);
For more information on SQLiteOpenHelper, Readable, and Writable Databases, check out the official the documentation of SQLiteDatabase

Related

SQLite, return data as an array

I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();

SQLiteDatabase concurrent convenience update, query not updated android

I am trying to update the field of an entry in an SQLiteDatabase using the db.update(...) method, but it seems the value is not stored. I've tried the convenience db.query(...) method right after the update method has been executed and found that the entry is still stored as before the update.
Is there some sort of background work that I must wait for before the query, or where am I going wrong? I am using a singleton extended SQLiteOpenHelper (dbHelper) as recommended in SQLite DB accessed from multiple threads and I've even tried getting a new readable instance of the db from the helper for the query in a new thread, as in the code below:
ContentValues deviceListEntry = new ContentValues();
deviceListEntry.put(DeviceListDBEntry.NODE_ID, nodeID);
...
...
String WHERE = DeviceListDBEntry.NODE_ID + " = ?";
final String[] WHERE_ARG = {String.valueOf(nodeID)};
SQLiteDatabase db = dbHelper.getWritableDatabase();
int listings = 0;
try {
//Update the device in the database DeviceList table
listings = db.update(
DeviceListDBEntry.TABLE_NAME,
deviceListEntry,
WHERE,
WHERE_ARG
);
} catch (Exception e) {
throw new ApiHandlerException("db.update(DeviceList, node " + nodeID + ")", e);
}
Log.e("updateDBdevice", " node " + device.getNodeID() + " listening = " + device.isListening());
final String[] TABLE_COLUMNS = {
DeviceListDBEntry.DEVICE_TYPE,
DeviceListDBEntry.INTERVIEWED,
DeviceListDBEntry.DEVICE_JSON
};
final String where = WHERE;
new Thread(new Runnable() {
#Override
public void run() {
SQLiteDatabase db2 = dbHelper.getReadableDatabase();
Cursor deviceEntry = db2.query(
DeviceListDBEntry.TABLE_NAME, //FROM DeviceList Table
TABLE_COLUMNS, //SELECT * columns
where, //WHERE nodeID =
WHERE_ARG, //args nodeID
null,
null,
null
);
if (!deviceEntry.moveToFirst()) throw new ApiHandlerException("DeviceListDB no entry found - WHERE nodeID = " + nodeID);
if (deviceEntry.getCount() > 1) throw new ApiHandlerException("DeviceListDB duplicate entries - WHERE nodeID = " + nodeID);
String deviceJson = deviceEntry.getString(deviceEntry.getColumnIndexOrThrow(DeviceListDBEntry.DEVICE_JSON));
Log.e("updateDBdevice retreive", " node " + nodeID + " JSON : " + deviceJson);
}
}).start();
I am using a Gson object to parse my device class to a JSON object which is stored in the DB. I know that this works when using the db.insert(...) method.
The query here is only there to see if the update was successful, because I found that explicit queries using other delayed threads (synchronised using a object lock and the same SQLiteOpenHelper) returned values that were not updated.
Is there an obvious thing I am missing or should I consider going to raw SQL commands on the db?
My mistake, I found that I had actually not added the updated JSON object to the new entry. Subsequently the deviceJson column of the listing did not update, but a db.update() was executed...
If "WHERE" clause has "text" column comparison then use single quotes around value. In your case try below line (notice single quotes around ?)
String WHERE = DeviceListDBEntry.NODE_ID + " = '?'";

Android: Retrieve data from sqlite Database

I currently I have my database set up like the following:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER, " + KEY_PIN
+ " INTEGER);");
And I am trying to write a method to get the pin code from the column for a specific locker number. Any ideas? I am very new I would like think I would need to use the query function and a cursor. I just one to get the integer value and store it into an int variable so I can compare the pin codes from what the user types in to the one in the database.
Queries to database returns in a Cursor object. You should use the db.query() method to get a row(s). Pass the table name, an array of columns you want to get (or null if you want all of them), pass a selection string that should be like "id = ?" or "key > ?", etc, then pass a String array containing the value for those ? inside the previous string,
and finally pass null for having, groupBy and orderBy unless you want to use them.
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ROWID }, "id = ?", new String[] { Integer.toString(id) }, null, null, null);
After you get the Cursor, do cursor.moveToFirst() or cursor.moveToPosition(0) (can't remember the exact method, but the point is to move the cursor to the first retrieved row)
then you're going to iterate through the cursor with
while(cursor.moveToNext()) {
int keyRowIdColumnIndex = cursor.getColumnIndex(KEY_ROWID);
int yourValue = cursor.getInt(keyRowIdColumnIndex);
int keyLockNumberColumnIndex = cursor.getColumnIndex(KEY_LOCKNUMBER);
int pin = cursor.getInt(keyLockNumberColumnIndex);
}
This is a pretty straight forward task and there is a bunch of tutorials, examples, similar questions on SO:
How to perform an SQLite query within an Android application?
In general - you need to query the database passing your search arguments. See the documentation.
It will return you a Cursor with the matching results, which you can then iterate over and manipulate as you wish.
Fyi - storing password in a database table is a bad idea. On Android databases can be accessed and easily read. You either need to encrypt your data or think of another way to store it if it's important.
//Try This code
public String getLabeId(String LockNo)
{
ArrayList<String> Key_Pin_array = new ArrayList<String>();
Cursor cur = db.rawQuery("SELECT * FROM DATABASE_TABLE where KEY_LOCKERNUMBER = '" + LockNo + "'", null);
try {
while (cur.moveToNext())
{
System.out.println("Key_Pin" + cur.getString(3));
Key_Pin_array.add(cur.getString(3));
}
}
catch (Exception e)
{
System.out.println("error in getLabelID in DB() :" + e);
}
finally
{
cur.close();
}
return id;
}

Sqlite : Unique makes my database go crazy

I'm having an issue with my app.
What my app does is this : gets some data from a couple of edittexts(3 per row,created dynamically) and puts them in a database .
What i want the database to do is this : take the product name,the quantity and the price and put them in the table.The name should be UNIQUE(it will be used to power an autocomplete,it needs to be unique not to have duplicates in the AC list).The price in the database must be the last price inserted for that product(for example,if Cheese at 3$ is inserted and after that Cheese at 2.5$ in the database we will find 2.5$).The quantity has to be summed up(if i enter Cheese in quantity 3 and then again Cheese in quantity 4 in the database we will find 7).
Now,my issue : Lets say i enter this in my shopping list :
1. Hhhh 4 2.5
2. Dddd 3 1
3. Eeee 2 2
4. Aaaa 5 3.5
In my database I will find this :
4. Aaaa 4 2.5
2. Dddd 3 1
3. Eeee 2 2
1. Hhhh 5 3.5
So,the issue is that it arranges the product name column alphabetically but the other columns remain in the same order,the one i entered in the edittexts.
I did some tests,if i remove the UNIQUE from the product name column,it will enter it as it should but of course,it will create duplicates,which i don't need.I don't get it,what's wrong ? why does UNIQUE trigger this ?
Here's my code :
My table creation :
public class SQLiteCountryAssistant extends SQLiteOpenHelper {
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_COLUMN_2_NAME = "country_counter";
private static final String DB_COLUMN_3_NAME = "country_price";
private static final String DB_CREATE_SCRIPT = "create table "
+ DB_TABLE_NAME
+ " (_id INTEGER PRIMARY KEY,country_name text unique, country_quantity REAL DEFAULT '0',country_price REAL);) ";
private SQLiteDatabase sqliteDBInstance = null;
public SQLiteCountryAssistant(Context context) {
super(context, DB_NAME, null, DB_VERSION_NUMBER);
}
#Override
public void onCreate(SQLiteDatabase sqliteDBInstance) {
Log.i("onCreate", "Creating the database...");
sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
}
My insert method :
public void insertCountry(String countryName, String countryPrice,
String countryQuantity) {
sqliteDBInstance.execSQL("INSERT OR IGNORE INTO " + DB_TABLE_NAME
+ "(country_name, country_quantity, country_price) VALUES('"
+ countryName + "','0', '" + countryPrice + "')");
sqliteDBInstance.execSQL("UPDATE " + DB_TABLE_NAME
+ " SET country_name='" + countryName
+ "', country_quantity=country_quantity+'" + countryQuantity
+ "' WHERE country_name='" + countryName + "';");
sqliteDBInstance.execSQL("UPDATE " + DB_TABLE_NAME
+ " SET country_name='" + countryName + "', country_price='"
+ countryPrice + "' WHERE country_name='" + countryName + "';");
}
And this is how i call the insert method :
for (int g = 0; g < allcant.size() - 1; g++) {
if (prod[g] != "0.0") {
sqlliteCountryAssistant.insertCountry(prod[g],pret[g],cant[g]);
}
Also,please excuse my messy code,i've started learning android with no programming background like a month ago.I just got my bachelors degree in Sociology so yea,i'm an absolute beginner.If there is way to do it better then i did and i'm pretty sure there is,please,show me the way,heh.
Thanks and have a good day !
EDIT : Aaaand the whole db class :
public class SQLiteCountryAssistant extends SQLiteOpenHelper {
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_COLUMN_2_NAME = "country_counter";
private static final String DB_COLUMN_3_NAME = "country_price";
private static final String DB_CREATE_SCRIPT = "create table "
+ DB_TABLE_NAME
+ " ( id INTEGER PRIMARY KEY AUTOINCREMENT,country_name text unique, country_quantity REAL DEFAULT '0',country_price REAL)";
private SQLiteDatabase sqliteDBInstance = null;
public SQLiteCountryAssistant(Context context) {
super(context, DB_NAME, null, DB_VERSION_NUMBER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO: Implement onUpgrade
}
#Override
public void onCreate(SQLiteDatabase sqliteDBInstance) {
Log.i("onCreate", "Creating the database...");
sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
}
public void openDB() throws SQLException {
Log.i("openDB", "Checking sqliteDBInstance...");
if (this.sqliteDBInstance == null) {
Log.i("openDB", "Creating sqliteDBInstance...");
this.sqliteDBInstance = this.getWritableDatabase();
}
}
public void closeDB() {
if (this.sqliteDBInstance != null) {
if (this.sqliteDBInstance.isOpen())
this.sqliteDBInstance.close();
}
}
public void insertCountry(String countryName, String countryPrice,
String countryQuantity) {
ContentValues cv = new ContentValues();
cv.put("country_name", countryName);
cv.put("country_price", countryPrice);
sqliteDBInstance.insertWithOnConflict(DB_TABLE_NAME, null, cv, sqliteDBInstance.CONFLICT_IGNORE);
// Increment the quantity field (there isn't a good way to do this with sql.update() )
sqliteDBInstance.execSQL("UPDATE " + DB_TABLE_NAME + " SET country_quantity=country_quantity+? WHERE country_name=?",
new Object[] { new Long(countryQuantity), countryName });
/*sqliteDBInstance.execSQL("INSERT OR IGNORE INTO " + DB_TABLE_NAME
+ "(country_name) VALUES('" + countryName + "')");
sqliteDBInstance.execSQL("UPDATE " + DB_TABLE_NAME
+ " SET country_quantity=country_quantity+" + countryQuantity
+ " WHERE country_name='" + countryName + "';");
sqliteDBInstance.execSQL("UPDATE " + DB_TABLE_NAME
+ " SET country_price=" + countryPrice
+ " WHERE country_name='" + countryName + "';");*/
}
public boolean removeCountry(String countryName) {
int result = this.sqliteDBInstance.delete(DB_TABLE_NAME,
"country_name='" + countryName + "'", null);
if (result > 0)
return true;
else
return false;
}
public long updateCountry(String oldCountryName, String newCountryName) {
ContentValues contentValues = new ContentValues();
contentValues.put(DB_COLUMN_1_NAME, newCountryName);
return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues,
"country_name='" + oldCountryName + "'", null);
}
public String[] getAllCountries() {
Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME,
new String[] { DB_COLUMN_1_NAME }, null, null, null, null,
DB_COLUMN_1_NAME + " ASC");
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
// String[] strpri = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor
.getColumnIndex(DB_COLUMN_1_NAME));
// strpri[i] = cursor.getString(cursor
// .getColumnIndex(DB_COLUMN_2_NAME));
i++;
}
return str;
} else {
return new String[] {};
}
}
}
I haven't figured out the crazy order but I found two things that might even clear something up:
your create table sql has one closing bracket too much (remove the one after the semicolon)
your insert method is really messy :) I would split it into two methods.
The general approach would be to create an insertOrUpdate method that queries the database for the entry (in your case the countryName). If an entry exist, it will be updated, if not it will be inserted. As you are a beginner, this might be a good task to do that by yourself, you should get the basic code here on SO in different questions.
The final tip (you might have seen it already): Use the parameter version and/or the real update/insert methods from the database.
db.insert(TABLE_NAME, null, contentValues); // see class ContentValues for details
According to the execSQL() method, you shouldn't use that for any SELECT/INSERT/UPDATE/DELETE statement:
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
Now my question which answer might help me to help you:
I would also like to know how you verified the order of your database content? Have you created a query in your android code where you query the content or have you opened the db file with a SQLite manager tool? If you query, can you include your query/display code in your question, too?
A couple of things to add to #WarrenFaith's excellent suggestions. I agree that the error is probably in code you haven't shown.
The quotes around the increment value in the UPDATE SQL are wrong. Should be e.g. quantity=quantity+42, not quantity=quantity+'42'
You need to use argument escapes (question marks ?) to avoid problems including SQL insertion attacks on your app.
The insert logic is insanely complicated. Perhaps this is where the problem lies.
You want something like:
// Insert or ignore.
ContentValues cv = new ContentValues();
cv.put("country_name", country_name);
cv.put("country_price", country_price);
sql.insertWithOnConflict(DB_TABLE_NAME, null, cv, CONFLICT_IGNORE);
// Increment the quantity field (there isn't a good way to do this with sql.update() )
sql.execSQL("UPDATE " + DB_TABLE_NAME + " SET country_quantity=country_quantity+? WHERE country_name=?",
new Object[] { new Long(country_quantity), country_name });
AND you didn't mention if the LogCat is clean. It must be showing DB errors at least regarding the quotes problem. Also suggest you make sure the table is dropped and rebuilt between debugging runs.

sqlite how to add value on conflict

I have a database with product name,product price and product counter.
Product name is unique,product price gets replaced everytime a new value is entered and the problem is the product counter.
Its default value is 1,when a new product is entered his value is set to 1.I need it to increment whenever there is a conflict for the product name.So if Cheese is entered twice,the counter will say 2 and so on.
What i need it to do is when there is a conflict,add 1 to its value. I want to do it this way because i'll need this later.I'll need to add the inputed value to the table value on some other thing i plan to implement in my app.
How can i achieve this ? I'd like to keep doing it the way i'm doing it now,with the contentvalues method of inserting and not with the sqlite syntax(INSERT,SELECT,etc).Is that even possible ? Cuz i'm an absolute 0 at sqlite syntax.And also,i need it to have a method that i can call in other activities to insert into the database (like insertCountry(Japan,10))
public class SQLiteCountryAssistant extends SQLiteOpenHelper {
private static final String DB_NAME = "usingsqlite.db";
private static final int DB_VERSION_NUMBER = 1;
private static final String DB_TABLE_NAME = "countries";
private static final String DB_COLUMN_1_NAME = "country_name";
private static final String DB_COLUMN_2_NAME = "country_price";
private static final String DB_COLUMN_3_NAME = "country_counter";
private static final String DB_CREATE_SCRIPT = "create table "
+ DB_TABLE_NAME
+ " (_id integer primary key autoincrement, country_name text UNIQUE ON CONFLICT REPLACE,country_price text,country_counter integer default '1' );)";
And this is how i insert :
public void insertCountry(String countryName, String countryPrice) {
sqliteDBInstance.execSQL("INSERT INTO " + DB_TABLE_NAME
+ "(country_name, country_price) VALUES('" + countryName
+ "', '" + countryPrice + "')");
}
Incrementing a value to a specific cell is not available in sqlite. You have to read the current value of cell and add your needed value to it and replace it with the old one. You can use update method.
public void update(String countryName, String price, long id) {
ContentValues cv = new ContentValues();
cv.put(dbHelper.COLUMN_1, countryName); // These Fields should be your
// String values of actual column
// names
cv.put(dbHelper.COLUMN_2, price);
database.update(dbHelper.TABLE_NAME, cv, "_id " + "=" + id, null);
}
every time you're going to add a row to your table you have to read all it and check if the row exists.here is a method to retrieve all rows:
public List<TableRow> getAllRows() {
List<TableRow> rows= new ArrayList<TableRow>();
Cursor cursor = database.query(Helper.TABLE_SITUPS, allColumns,
null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
TableRow row = cursorToRow(cursor);
comments.add(row);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return rows;
}
TableRow is a class for database table rows and contains fields stands for actual table columns.
with iterating this list and get "country" value of each one you can understand if that row exists or not.
These are basic concepts of sqlite databases programming. I recommend you to research a bit in this matter.
I don't know your database class, but check this method:
return this.sqliteDBInstance.insertWithOnConflict(DB_TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
If you are creating your column correctly, if there is a conflict, the new entry will replace the old one.
EDIT: after your last comment, all you need is an update: first query your database with the name of your item (check carefully if parameters are ok):
return this.sqliteDBInstance.query(DB_TABLE_NAME, null, DB_COLUMN_1_NAME + "=?", new String[] {productName}, null, null, null);
This will return a Cursor with 0 or 1 row. If there aren't row, you can proceed inserting data normally (don't forget to add your counter: is 1 on first insert):
public void insertCountry(String countryName, String countryPrice) {
sqliteDBInstance.execSQL("INSERT INTO " + DB_TABLE_NAME
+ "(country_name, country_price) VALUES('" + countryName
+ "', '" + countryPrice + "', '" + countryCounter + "')");
}
if there is 1 row, your product is already on your database, so just iterate the Cursor, take the value on counter, add +1 on it and update your database with this method:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)

Categories