I'm trying to get the value or data from the array that doesn't exists in the database.
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","cold"};
SQLiteDatabase db= getReadableDatabase();
String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")";
c=db.rawQuery(query,null);
Log.i("From Cursor","Cursor Count : " + c.getCount());
if(c.getCount()>0){
String val= c.getString()
Log.i("From Cursor","No insertion");
}else{
Log.i("From Cursor","Insertion");
}
db.close();
return c;
}
public static String toArrayRep(String[] in) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < in.length; i++) {
if (i != 0) {
result.append(",");
}
result.append("'" + in[i] + "'");
}
return result.toString();
}
In the String values={"headache","cold"} ,headache exists but cold does not exist in the database. From the code above, the Cursor returns Count=1 which is count>0 hence i can't insert into table.I would like to know how i can independently check whether the individual data exists, and the one which doesn't exist will be inserted into table.So in this case, "Cold" would be able to be inserted into the table.
If you use a single query to check all values, then what you get is a list of existing values, and you still have to search in the original list for any differences.
It is simpler to check each value individually:
String[] values = { "headache", "cold" };
SQLiteDatabase db = getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You need check Cursor.moveToFirst()
True = Have records in cursor.
False = Dont have records.
Example my code:
return database.query( table.getNameTable(),
table.getColumns(),
table.getWhereSelectTableScript(),
null,
table.getGroupBySelectTableScript(),
table.getHavingSelectTableScript(),
table.getOrderBySelectTableScript(),
table.getLimitRecordsSelectTableScript());
See more here !
Related
I am creating app in which i register user and store user's information in database,so i have created database and storing value in databse but i don't know how to fetch data from database and show in textview?Using below query to fetch data but it has error.What is correct way?
public void insertEntry(String fname, String lname, String gen,String weight)
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", gen);
values.put("weight",weight);
}
public Cursor fetchData()
{
SQLiteDatabase mDB = dbHelper.getWritableDatabase();
return mDB.rawQuery("SELECT * FROM Register WHERE firstname=? lastname =?" , null);
}
Using this to set fetched value on textview in different activity
Cursor name = sqliteDataBase.fetchData();
tv_name.setText((CharSequence) name);
Try this,
try {
SQLiteDatabase mDB = dbHelper.getReadableDatabase();
String selectQuery = "SELECT * FROM Register WHERE firstname= "+first+" lastname =" + last + ";";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
String firstName = cursor.getString(cursor.getColumnIndex("firstname")));
}
}
} catch(Exception e) {
e.printSTackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
public String fecthResults()
{
String name = null;
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
name = cursor.getString(cursor.getColumnIndex("firstname")
} while (cursor.moveToNext());
cursor.close();
}
sqLiteDatabase.close();
return name;
Get the name and then set it directly to a texView
A Cursor is an interface that provides random read-write access to the result set returned by the query. It contains multiple rows of data and this data can be easily processed by help of For loop.
Lets take an example to understand the process. Suppose, you need to access data from a column name "col_1" and show the data in TextView. The For loop for the process will be as follows.
for (cursor.moveToNext()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Now, if we need only one value (from only one record or tuple) then, we can opt out the For loop and change the code as shown below.
if (cursor.moveToFirst()) {
textView.setText(cursor.getString(cursor.getColumnIndex("col_1")));
}
Always remember to close the cursor after using it.
To close the cursor, use the following line of code.
cursor.close();
For more information, please visit the following links:
https://developer.android.com/reference/android/database/Cursor.html
https://developer.android.com/training/basics/data-storage/databases.html#ReadDbRow
I'm Parsing a JSON WebService and creating a array with data to INSERT and DELETE entries in a database.
I found the solution bulkInsert to insert multiple rows using database transactions inside a content provider, however, I am trying to do the same procedure to delete multiple lines.
The INSERT solution:
#Override
public int bulkInsert(Uri uri, ContentValues[] allValues) {
SQLiteDatabase sqlDB = mCustomerDB.getWritableDatabase();
int numInserted = 0;
String table = MyDatabase.TABLE;
sqlDB.beginTransaction();
try {
for (ContentValues cv : allValues) {
//long newID = sqlDB.insertOrThrow(table, null, cv);
long newID = sqlDB.insertWithOnConflict(table, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
if (newID <= 0) {
throw new SQLException("Error to add: " + uri);
}
}
sqlDB.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
numInserted = allValues.length;
} finally {
sqlDB.endTransaction();
}
return numInserted;
}
Using this call:
mContext.getContentResolver().bulkInsert(ProviderMyDatabase.CONTENT_URI, valuesToInsertArray);
Is there any way to delete multiple rows (with this array ID's) of database using content provider.
UPDATE:
I found this solution, using the `IN clause:
List<String> list = new ArrayList<String>();
for (ContentValues cv : valuesToDelete) {
Object value = cv.get(DatabaseMyDatabase.KEY_ROW_ID);
list.add(value.toString());
}
String[] args = list.toArray(new String[list.size()]);
String selection = DatabaseMyDatabase.KEY_ROW_ID + " IN(" + new String(new char[args.length-1]).replace("\0", "?,") + "?)";
int total = mContext.getContentResolver().delete(ProviderMyDatabase.CONTENT_URI, selection, args);
LOGD(TAG, "Total = " + total);
The problem is that, if the JSON return more than 1000 rows to insert, occurs error, because the SQLITE_MAX_VARIABLE_NUMBER is set to 999. It can be changed but only at compile time.
ERROR: SQLiteException: too many SQL variables
Thanks in advance
I solved this issue with this code:
if (!valuesToDelete.isEmpty()) {
StringBuilder sb = new StringBuilder();
String value = null;
for (ContentValues cv : valuesToDelete) {
value = cv.getAsString(kei_id);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(value);
}
String args = sb.toString();
String selection = kei_id + " IN(" + args + ")";
int total = mContext.getContentResolver().delete(uri, selection, null);
LOGD(TAG, "Total = " + total);
} else {
LOGD(TAG, "No data to Delete");
}
Thanks
User ContentResolver object to delete multiple rows.
// get the ContentResolver from a context
// if not from any activity, then you can use application's context to get the ContentResolver
// 'where' is the condition e.g., "field1 = ?"
// whereArgs is the values in string e.g., new String[] { field1Value }
ContentResolver cr = getContentResolver();
cr.delete(ProviderMyDatabase.CONTENT_URI, where, whereArgs);
So any row with (field1 = field1Value) will be deleted.
If you want to delete all the rows then
cr.delete(ProviderMyDatabase.CONTENT_URI, "1 = 1", null);
I have created an application to insert data to sq-lite . i want if i enter same data again it should give e toast massage and then it only update that data not re-insert.
what should i do.....
now data is been re-inserted
method code of SQLiteOpenHelper.....
public void insertdata(String name,String ph,String area){
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
sd=this.getWritableDatabase();
sd.insert("location", null, cv);
sd.close();
method use in Activity class......
public void onClick(View v) {
// TODO Auto-generated method stub
help=new MyHelper(getApplicationContext());
help.getWritableDatabase();
String myname=name.getText().toString();
String call=phone.getText().toString();
String myarea=area.getText().toString().trim();
help.insertdata(myname, call, myarea);
Toast.makeText(getApplicationContext(), "data saved ", Toast.LENGTH_SHORT).show();
}
});
The data is being reinserted because you're methods never check to see if it already exists in the databse. You need to add a query for some unique combination - probably name and phone number. If that query returns a result you can prompt the user to enter the data.
String query = "SELECT * FROM " + TABLE_NAME + " WHERE name = " + name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if(cursor != null && cursor.moveToFirst()){ //if cursor has entry then don't reinsert
//prompt user with dialog
} else {
//insert data
}
Also you cannot use a Toast for this. What you want is a Dialog. If the data exists you can display a custom Dialog to the user that you could use to allow them to (1) enter new data (2) edit existing data (3) choose to reinsert the data they are posting. A Toast will just display a message to them like - "reinserting data". It does not sound like that is the functionalty you want to achieve.
To update the database you can just use an update statment depending on what fields you want to change.
String query = "UPDATE " + TABLE_NAME + " SET";
if(!name.isEmpty(){
query += " name = " + name;
}
if(!phone.isEmpty(){
query += " phone = " + phone;
}
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_CONTACTS_TABLE)
I put the if statments in to check for which fields are being changed and add them to the query accordingly. In the alternative you could use something like this
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
While I havnet modified it to fit your example you can see the basic approach. Hhere you can use conditionals to check if values are being supplied, if they are you add them to the ContentVlues list which will update them in the DB.
You can try something like this:
ContentValues values=new ContentValues();
cv.put("name", name);
cv.put("phone", ph);
cv.put("area", area);
if (db == null) {
db = getWritableDatabase();
}
if (isNameExists(name)) { //check if name exits
id = db.update(TABLE_NAME, values, name + " = ?",
new String[] {name});
} else {
id = db.insert(TABLE_NAME, null, values);
}
public boolean isNameExists(String name) {
Cursor cursor = null;
boolean result = false;
try {
String[] args = { "" + name };
StringBuffer sbQuery = new StringBuffer("SELECT * from ").append(
TABLE_NAME).append(" where name=?");
cursor = getReadableDatabase().rawQuery(sbQuery.toString(), args);
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
} catch (Exception e) {
Log.e("AppoitnmentDBhelper", e.toString());
}
return result;
In my application i am showing data from database in a table view.My requirement is that from database i have to retrieve the data which will fall in the current month.I Have written the query but it is coming as 0.Actually i have 1 entry in the database with today's date,so my query should return that data,but it is showing as 0.Please help me.Thanks in advance.
My query is as follows:
public String addgroupincome(String grp) throws SQLException
{
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE date= Strftime('%Y-%m','now') AND category='Income' AND groups='"+grp+"'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
return housetotal;
}
I am getting that total and showing in atextview in table layout..
final String houtotal=db.addgroupincome(group1);
housetotal.setText(houtotal);
Most probably nothing wrong with the query but the way you pass the query result to ListView. Can you show how you do it? Perhaps I could help.
Or you could take a look here or here
public int getCount() {
DBHelper dbHelper = DBHelper.getDBAdapterInstance(this);
int count = 0;
try {
dbHelper.openDataBase();
String query = "select count(1) from t_model where upper(brandName) = upper('"
+ selectedBrand + "') order by modelName ASC";
Cursor cursor = dbHelper.selectRecordsCursor(query, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
cursor.close();
cursor = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
return count;
}
and for the TextView should be as simple as
TextView tvCount = (TextView) findViewById(R.id.tvCount);
tvCount.setText("Count : " + getCount);
If you are having trouble debugging your query. Try http://sqlitebrowser.sourceforge.net/ or http://www.sqliteexpert.com/
Why don't you try by giving column names of your table in your query..might it work out for you..specify the columns which you want to retrive..
if (cursor.moveToNext()) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.i(ID, cursor.getInt(0) + "");
cursor.moveToNext();
}
cursor.close();
} else {
cursor.close();
return null;
}
Try This Method....
I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}