I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it.
I make the call
mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);
Which calls...
public long createNote(String value, String table) {
ContentValues initialValues = new ContentValues();
initialValues.put(table, value);
return mDb.insert(table, null, initialValues);
}
Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried
return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);
However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...
How can I get this to work?
Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.
Use the REPLACE command
In such situation I perfrom such checking:
if (!checkRecordExist(DATABASE_TABLE, new String[] {KEY_1, KEY_2}, new String[] {value_1, value_2}))
database.insert(DATABASE_TABLE, null, updateValues);
where
private boolean checkRecordExist(String tableName, String[] keys, String [] values) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keys.length; i++) {
sb.append(keys[i])
.append("=\"")
.append(values[i])
.append("\" ");
if (i<keys.length-1) sb.append("AND ");
}
Cursor cursor = database.query(tableName, null, sb.toString(), null, null, null, null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Add a Primary Key. If you try to insert another row with the same key, the insert will fail.
Have you tried using a primary key that isn't set to auto-increment? That might be why the REPLACE command isn't working
Related
I am trying to return the names of distinct values in the 'category' column of an SQLite database. The cursor does not appear to be returning any results.
I'm building an Android app using a pre-existing database of bird species. The aim is to allow the user to explore the database through the app. The problem I'm having is in trying to return the distinct categories of bird species that exist in the database. The database appears to be opening successfully - no SQLite exception is being thrown, - but after using the query, the '.moveToNext' method does not appear to be returning any data.
public ArrayList<String> getCategory(String[] name){
String TABLE_BIRDS = "main";
String[] COLUMN = name;
ArrayList<String>categories = new ArrayList<>();
if (name[0]!=null)
{
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
x = db.query(true, TABLE_BIRDS, new String[] { COLUMN[0] } , null, null, COLUMN[0], null, null, null );
if (x.moveToNext()) {
Log.i(LOG_TAG, x.getString(x.getColumnIndex("category")));
}
else {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
//Simple cursor loop
if (x.moveToNext()){
String category = new String();
category = x.getString(x.getColumnIndex(category));
categories.add(category);
Log.i("cursor loop", category);
}
return categories;
In the above code, the log messages are showing that: getCategory is receiving the expected string "category" before the query, but right after the query, the if/else loop is reporting that "The cursor is not returning any data".
What I expected is that the query would return six Strings, the cursor loop would add them to the ArrayList 'categories', and this ArrayList would be returned.
Please any help would be appreciated.
Here is a simpler version of your method:
public ArrayList<String> getCategory(String[] name) {
String TABLE_BIRDS = "main";
ArrayList<String> categories = new ArrayList<>();
if (name[0] != null) {
Log.d(LOG_TAG, name[0]);
} else {
Log.d(LOG_TAG, "name[0] has not been passed");
}
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
while (x.moveToNext()) {
String category = x.getString(0);
categories.add(category);
Log.i("cursor loop", category);
}
if (x.getCount() == 0) {
Log.i(LOG_TAG, "The cursor is not returning any data");
}
x.close();
return categories;
}
I guess name[0] contains the string 'category' which is the column that you want to query.
Since you pass true as the 1st argument in the method query() this means that you will get distinct values, so no need for the group by argument.
You don't need the variable COLUMN since you have what you need in the variable name.Also you don't need getColumnIndex() since the cursor returns only 1 column.
Edit
Instead of:
Cursor x = db.query(true, TABLE_BIRDS, new String[]{name[0]}, null, null, null, null, null, null);
try rawQuery():
Cursor x = db.rawQuery("SELECT DISTINCT " + name[0] + " FROM " + TABLE_BIRDS, null);
Assuming the cursor is not null, you should
iterate over the results with a while/for loop.
e.g :while(x.moveToNext()) {
//your logic
}
It is always useful when debugging this kind of issues to install an SQLite DB browser then check the cursor's query against your DB to see if you have any data.
I have f.e. a thousand names (texts) and I need to show them one by one in random order when I click a button. What is the best way to do that?
Use SQLite or Shared Preferences if you need to keep names even after you close the program. Here is the sample code.
ExternalDbOpenHelper dbOpenHelper;
SQLiteDatabase database;
dbOpenHelper = new ExternalDbOpenHelper(context, "DB");
database = dbOpenHelper.getWritableDatabase();
database.execSQL("CREATE TABLE IF NOT EXISTS "+"names"+
" ("+"ID"+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
"name"+" TEXT)");
ContentValues cv = new ContentValues();
cv.put("name", name_string);
database.insert("names", null, cv);
database.close();
then use Cursor to access values from database:
Cursor c = database.query("names", null, null, null, null, null, null);
c.moveToFirst();
String name;
do{
int nameCI = c.getColumnIndex("name");
name = c.getInt(nameCI);
}while (c.moveToNext());
get all the name from database and store in the array list .You can get the all the name on the onCreate() of the activity or on button click as you wish.
ArrayList<String> list= new ArrayList<String>();
list.add("A");
list.add("E");
list.add("I");
list.add("O");
list.add("U");
public void clickEvent(){
Collections.shuffle(list);
String name=list.get(0);//from index
textView.setText(name);
}
I am creating an application. I need the email of the existing user, which is already saved in the first table, and save it into the second table. Which queries or functions do I need to achieve this? Any suggestions?
First, you need to fetch the user's email by passing on the valid row id:
public Cursor getRecord(long id) throws SQLException {
Cursor cursor = this.database.query(true, databaseTable, new String[] {columnId, columnName, columnEmail}, columnId + "=" + id, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Please note, you may have different columns so change the String[] array with your designated columns. Now, we can create another function to save that email in another table like so:
public long insertExistingUser(String name, String email) {
ContentValues contentValues = new ContentValues();
contentValues.put(columnName, name);
contentValues.put(columnEmail, email);
return this.database.insert(otherDatabaseTable, null, contentValues);
}
This will insert the other user's information into the other table. In order for this to work in your application:
DatabaseAdapter db = new DatabaseAdapter(this);
db.open();
Cursor cursor = db.getRecord(current_user_id);
if (db.insertExistingUser(cursor.getString(1), cursor.getString(2)) > 0)
Toast.makeText(this, "Old user's info was inserted!", Toast.LENGTH_SHORT).show();
db.close();
The cursor.getString(1) requires a number that indicates what column it is. Usually, 0 is the id column which you use to get the user's email.
First of all, please bear with me, I have minimal experience with SQLite. I am writing an app in Java for the Android platform and I've run into an issue while attempted to query a SQLite database.
I have implemented a database and I am unsure of how to write a method which returns a cursor of only specific rows with a certain value in a certain column. Say there is a column titled "date", I would like to write a method which returns all the columns that do not have the value string "null" in the "date" column.
I know how to write a fetchAll() method and how to write a fetch() for specific rows given an ID, but I not multiple specific rows.
If anyone can help me it would be greatly appreciated.
These will return all the row where Date!=null
public Cursor fetch()
{
return db.query(DATABASE_TABLE,
null,
DATE + "!=''",
null,
null,
null,
null);
}
If you don't need all columns then use
public Cursor fetch()
{
return db.query(DATABASE_TABLE,new String[] {
DATE,
TIME
},
DATE + "!=''",
null,
null,
null,
null);
}
For fetching multiple row using curosor, Have a go with this, You could customize it for your need:
public List<String> getNotNullValues(String value) {
String[] resultCols = new String[] { "Give your result column name here" }; //u could specify multiple column name here
List<String> list = new ArrayList<String>();
int count = 0;
Cursor cr = getWord("DATE", "Your Table Name", "Value of the column",
resultCols,"!="); //Cr is the cursor for resulted query
if (null == cr) {
return null;
}
do {
list.add(cr.getString(0)); //Fill the list or whatever here while traversing with the cursor
} while (cr.moveToNext());
cr.close();
return list;
}
}
public Cursor getWord(String columnName, String tblName, String rowId,
String[] columns, String condition) {
String selection = columnName + condition ; //condtion for selecting a value : "= ?"
String[] selectionArgs = new String[] { rowId };
return query(selection, tblName, selectionArgs, columns);
}
here are the steps:
Form the query with condition, column name and required column name
Get the cursor to the resulting query
Move the cursor to the next record till cr.moveToNext() returns false
For further reference:
Complete Step by Step SQLite Example:
http://mobile.tutsplus.com/tutorials/android/android-sqlite/
Youtube Video Tutorial
http://www.youtube.com/watch?v=kMaBTolOuGo
Multiple Table Creation
http://androidforbeginners.blogspot.com/2010/01/creating-multiple-sqlite-database.html
PS: All the links are tested and working well!!
Happy Coding!!
I have an sqlitedb, row _id auto increments. How do I form a query to get the highest number in row _id and put that into a variable? I know how to do it in sql but not using the query method.
As answered elsewhere on this site:
String query = "SELECT MAX(row_id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, null);
int id = 0;
if (cursor.moveToFirst())
{
id = cursor.getInt(0);
}
Cursor Days = db.query(true, DATABASE_TABLE, new String[]{"_id"},
"_id="+"(select max(_id) from" +DATABASE_TABLE+")" , null, null, null, null, null);
This should also work.
cursor.getLong(cursor.getColumnIndex("row_id"))
Did you try this? When you insert the data in database, autoincrement increases the id for primary key and I assume row_id must be your one of the keys.
you can get this by count and also by using MAX(column name) function in your query.
max function returns the maximum value
Cursor newCursor = newContentResolver.query
(
CONTENT_URI,
new String[]{"_id"},
null,
null,
null
);
if(newCursor.moveToLast())
{
int index = newCursor.getColumnIndex("_id");
String id = newCursor.getString(index);
Log.v("TAG", "Highest id : "+id);
}
This is one way of getting the highest row id. Since the generation is auto increment, we are assured that the last row is the highest in the database. moveToLast() moves the cursor to the last row.