For Create table :
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID + " REAL NOT NULL" +"," + TOTAL_DISPLACEMENT_DISTANCE + " REAL NOT NULL" + "" + ");");
}
for Update table, want to save only displacement so i update every time because i want to override the data.
public void insertTotalDisplacement(String userID, Double displacement) {
try {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, userID); //User phone No used as a USER ID
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues, NewDatabaseForInRideData.USER_ID+" = "+userID, new String [] {});
} catch (Exception e) {
e.printStackTrace();
}
}
For Retrieving data, I used several ways to do this but data not save in database and not retrieved from database.
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
// cursor = database.rawQuery(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
//choice = String.valueOf(cursor.getDouble(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE)));
Cursor cur=database.rawQuery("SELECT "+NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE+" where "+NewDatabaseForInRideData.USER_ID+" = " +1+ " from"+NewDatabaseForInRideData.IN_RIDE_DATA,new String [] {});
//Cursor cur=database.rawQuery("SELECT * from IN_RIDE_DATA",new String [] {});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
The issue is in getTotalDisplacementDistance method, you are using two cursor variables, one has query result and other is null, and you are processing the one with null value.
Update it accordingly,
public Cursor getTotalDisplacementDistance() {
Cursor cursor=null;
try {
cursor = database.rawQuery("SELECT " + NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE + " from IN_RIDE_DATA where " + NewDatabaseForInRideData.USER_ID + " = ?", new String[] {"1"});
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
} catch (Exception e) {
e.printStackTrace();
return cursor;
}
}
You can try this
String selectQuery = "SELECT * FROM " + IN_RIDE_DATA;
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.USER_ID))));
contact.setName(cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE))));
// Adding data to your list
list.add(contact);
} while (cursor.moveToNext());
db.setTransactionSuccessful();
}
db.endTransaction();
Edit
Use you model class for setting data
I change these things
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
//database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " (" + USER_ID +"," + TOTAL_DISPLACEMENT_DISTANCE + "" + ");");
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT"+");");
}
For Deleting Table
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
For Inserting
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For retrieving the values:
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
Related
After the record iteration, the list key value is mismatching/wrongly shown ! what could be the reason.
Correct data in the database like this is saved (which is correct)
Problem: You can see in this screenshot link, record is a mismatch with columns, e.g the key dayName has wrong value showing , key MenuIcon value is shown on dayName key
the sql lite DAO
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
Full code of DAO for insertion,create table, list object . Please let me know any code you want to see, i will post
public class ExercisesDAO {
public static final String TAG = "ExercisesDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {DBHelper.COLUMN_EX_DETAILS_ID,
DBHelper.COLUMN_ROUTINE_ID,
DBHelper.COLUMN_DAY_ID,
DBHelper.COLUMN_EXERCISE_ID,
DBHelper.COLUMN_REPS,
DBHelper.COLUMN_SETS,
DBHelper.COLUMN_TIME_PERSET,
DBHelper.COLUMN_CALORIE_BURN,
DBHelper.COLUMN_RESTTIME_PERSET,
DBHelper.COLUMN_RESTTIME_POST_SET,
DBHelper.COLUMN_ORDER_ID,
DBHelper.COLUMN_EXERCISE_NAME,
DBHelper.COLUMN_TIPS,
DBHelper.COLUMN_YOUTUBE_URL,
DBHelper.COLUMN_WARNINGS,
DBHelper.COLUMN_DISPLAY_ID,
DBHelper.COLUMN_VISIBILITY,
DBHelper.COLUMN_FOR_DATE,
DBHelper.COLUMN_GIF,
DBHelper.COLUMN_DAYNAME
};
public ExercisesDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public ExerciseDetails createExerciseDetail(String routineId,String dayId,
String exerciseId, String reps,String sets, String timePerset,
String calorieBurn, String resttimePerset, String resttimeAfterex,String order,
String menuName, String tips, String youtubeUrl, String warnings, String displayId,
String visibility, String forDate, String menuIcon, String dayName) {
ExerciseDetails newCompany = null;
try {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROUTINE_ID, routineId);
values.put(DBHelper.COLUMN_DAY_ID, dayId);
values.put(DBHelper.COLUMN_EXERCISE_ID, exerciseId);
values.put(DBHelper.COLUMN_REPS, reps);
values.put(DBHelper.COLUMN_SETS, sets);
values.put(DBHelper.COLUMN_TIME_PERSET, timePerset);
values.put(DBHelper.COLUMN_CALORIE_BURN, calorieBurn);
values.put(DBHelper.COLUMN_RESTTIME_PERSET, resttimePerset);
values.put(DBHelper.COLUMN_RESTTIME_POST_SET, resttimeAfterex);
values.put(DBHelper.COLUMN_ORDER_ID, order);
values.put(DBHelper.COLUMN_EXERCISE_NAME, menuName);
values.put(DBHelper.COLUMN_TIPS, tips);
values.put(DBHelper.COLUMN_YOUTUBE_URL, youtubeUrl);
values.put(DBHelper.COLUMN_WARNINGS, warnings);
values.put(DBHelper.COLUMN_DISPLAY_ID, displayId);
values.put(DBHelper.COLUMN_VISIBILITY, visibility);
values.put(DBHelper.COLUMN_FOR_DATE, forDate);
values.put(DBHelper.COLUMN_GIF, menuIcon);
values.put(DBHelper.COLUMN_DAYNAME, dayName);
long insertId = mDatabase
.insert(DBHelper.TABLE_EXERCISE_DETAILS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
DBHelper.COLUMN_EX_DETAILS_ID + " = " + insertId, null, null,
null, null);
cursor.moveToFirst();
newCompany = cursorToExerciseDetails(cursor);
cursor.close();
} catch (Exception e) {
Log.e("exception", "exception in CreateFollowing class - " + e);
}
return newCompany;
}
public void executeSqlOnExerciseDetail(String sql) {
mDatabase.execSQL(sql);
}
public Long getTotalCountExerciseDetail() {
return DatabaseUtils.queryNumEntries(mDatabase, DBHelper.TABLE_EXERCISE_DETAILS);
}
/*
* Get the all the exercises by ID asecending order
*/
public LinkedList<ExerciseDetails> getAllExerciseInfo() {
LinkedList<ExerciseDetails> listCompanies = new LinkedList<ExerciseDetails>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_EXERCISE_DETAILS, mAllColumns,
"",
new String[]{}, "order_id", null, "order_id ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
ExerciseDetails company = cursorToExerciseDetails(cursor);
listCompanies.add(company);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listCompanies;
}
/*
* Check whether the exercise data present or not in the db before executing statement
*/
public boolean CheckIfRecordExists(String rid, String did) {
String Query = "Select * from " + DBHelper.TABLE_EXERCISE_DETAILS + " where " + DBHelper.COLUMN_ROUTINE_ID + " = " + rid + " AND " + DBHelper.COLUMN_DAY_ID + " = " + did;
Cursor cursor = mDatabase.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
protected ExerciseDetails cursorToExerciseDetails(Cursor cursor) {
try{
ExerciseDetails exerciseDetails = new ExerciseDetails();
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
exerciseDetails.setDayId(cursor.getString(2));
exerciseDetails.setExerciseId(cursor.getString(3));
exerciseDetails.setReps(cursor.getString(4));
exerciseDetails.setSets(cursor.getString(5));
exerciseDetails.setTimePerset(cursor.getString(6));
exerciseDetails.setCalorieBurn(cursor.getString(7));
exerciseDetails.setResttimePerset(cursor.getString(8));
exerciseDetails.setOrder(cursor.getString(9));
exerciseDetails.setMenuName(cursor.getString(10));
exerciseDetails.setTips(cursor.getString(11));
exerciseDetails.setYoutubeUrl(cursor.getString(12));
exerciseDetails.setWarnings(cursor.getString(13));
exerciseDetails.setDisplayId(cursor.getString(14));
exerciseDetails.setVisibility(cursor.getString(15));
exerciseDetails.setForDate(cursor.getString(16));
exerciseDetails.setMenuIcon(cursor.getString(17));
exerciseDetails.setDayName(cursor.getString(18));
return exerciseDetails;
} catch (Exception e){
System.out.println("error------------"+e);
return null;
}
}
}
FUll json value which i inserted Into sqllite
https://pastebin.com/DmAkPkXg
In cursorToExerciseDetails() instead of explicitly setting the index of a column:
exerciseDetails.setExDetailsId(cursor.getLong(0));
exerciseDetails.setRoutineId(cursor.getString(1));
....................................................
use getColumnIndex() with he name of the column to return the index:
exerciseDetails.setExDetailsId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_EX_DETAILS_ID)));
exerciseDetails.setRoutineId(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ROUTINE_ID))));
....................................................
I need only one table and only one row and update new displacement in it.
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT" + ");");
}
For Updating Table (I remove previous displacement and then insert it new displacement, But i Want to update already existing displacement)
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For getting displacement
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
For deleting displacement
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
You have to make object of contentvalue
ContentValues cv = new ContentValues();
cv.put("displacement1","231"); //These Fields should be your String
values of actual column names
cv.put("displacement2","21");
cv.put("displacement3","21");
after this, you can use update query which SQLite provides
database.update(TableName, cv, "USER_ID ="+id, null);
The following or something along the lines of the following could be used as a replacement for the insertDisplacement method :-
public void insertOrUpdateDisplacement(String id, String displacement) {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
String whereclause = NewDatabaseForInRideData.USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = database.query(NewDatabaseForInRideData.IN_RIDE_DATA,
null,
whereclause,
whereargs,
null,null,null
);
if (csr.getCount() < 1) {
deleteDriverLocData();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} else {
//deleteDriverLocData(); ????? Not sure if required or not.
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues,whereclause,whereargs);
}
csr.close();
}
This will insert if there is no row (I assume for the user_id) otherwise it will update the displacement column of the existing row.
User Case :
Select item by id, if its already present in the basket.
Check the numbers of this item.
If item numbers == 1 then delete this item from basket table and return 0.
If its greater than 1 then decrement it by one and update the table and return number-- .
Its not updating my "numbers" column, and silently passes through the execution and I am helpless nor can I post any stack trace here, but I am posting my code fragment, responsible for this job.
public int removeFromBasketasAnonymous(Long _id){
Log.d("app : ", " _id = " + _id);
int numbers = 0;
try {
database = openDatabaseInReadMode();
Cursor cursor = database.rawQuery("select * from basket where basket._id=" + _id + ";", null);
if (cursor != null) {
cursor.moveToFirst();
Log.d(APP, "GetCount = " + cursor.getCount());
if (cursor.getCount() == 1) {
//this item already present in basket
numbers = cursor.getInt(1);
Log.d(APP, " numbers = " + numbers);
Log.d(APP, "db id = " + cursor.getString(0));
String[] columns = cursor.getColumnNames();
for(String str : columns){
Log.d("APP ", " columns = "+str);
}
Log.d(APP, " id = " + _id);
if (numbers == 1) {
//remove this row entry
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
String strSQL = "DELETE from basket where basket._id=" + _id;
try{
database.execSQL(strSQL);
}catch(Exception e){
e.printStackTrace();
}finally{
database.endTransaction();
database.close();
}
numbers--;
} else {
//decrement this number by one
Log.d(APP, " number " + numbers);
numbers--;
Log.d(APP, " dcremented numbers = " + numbers);
cursor.close();
database.close();
database = openDatabaseInReadWriteMode();
database.beginTransaction();
try{
ContentValues data = new ContentValues();
data.put("numbers", numbers);
database.update("basket", data, "_id = " + _id, null);
}catch (Exception e){
e.printStackTrace();
}finally {
database.endTransaction();
database.close();
}
}
}
}
}finally{
if(database != null){
database.close();
}
}
return numbers;
}
public SQLiteDatabase openDatabaseInReadMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
public SQLiteDatabase openDatabaseInReadWriteMode() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!isDataBaseExist()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
/*Log.d("DB available", "path = " + dbFile.exists() + " path" + dbFile.getPath());*/
/*Log.d("actual path ", "exists = " + isDataBaseExist());*/
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
}
Regards,
Shashank
How you can use database transaction in Android
If you want to start the transaction there is a method beginTransaction()
If you want to commit the transaction there is a
method setTransactionSuccessful() which will commit the values in the
database
If you had start the transaction you need to close the transaction so there is a method endTransaction() which will end your database transaction
Now there are two main points
If you want to set transaction successful you need to write
setTransactionSuccessful() and then endTransaction() after
beginTransaction()
If you want to rollback your transaction then you need to endTransaction()
without committing the transaction by setTransactionSuccessful().
I have a function that should delete a record in my sqlite database. But it is not deleting, what could be wrong?
public boolean deleteLoc(String id) {
boolean deleteSuccessful = false;
try {
SQLiteDatabase db = this.getWritableDatabase();
deleteSuccessful = db.delete(TABLE_NAME, "id =" + id, null) > 0;
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return deleteSuccessful;
}
it always returns false.
try out this:
deleteSuccessful = db.delete(TABLE_NAME, "id ='" + id + "'", null) > 0;
otherwise there is no corresponding record in table.......have you checked your table for the entry you are trying to delete?
If id is of type string then, you should use:
deleteSuccessful = db.delete(TABLE_NAME, "id ='" + id + "'", null) > 0;
EDIT:
If id is of type Numeric then, you should convert it to long:
long longId = Long.parseLong(id);
deleteSuccessful = db.delete(TABLE_NAME, "id =" + longId, null) > 0;
I am making an android app, I want to remove a contact from a specific group not to delete contact just remove from the group, I have group id and contact id, can anyone please tell me the query to do this,
I want to implement something like Delete contact_id=1 from group_id=2
Contacts are linked to groups with ContactsContract.CommonDataKinds.GroupMembership records. You can use something like this to delete contact from group:
private void deleteContactFromGroup(long contactId, long groupId)
{
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + groupId + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID + "=?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
for (Long id : getRawContactIdsForContact(contactId))
{
try
{
cr.delete(ContactsContract.Data.CONTENT_URI, where,
new String[] { String.valueOf(id) });
} catch (Exception e)
{
e.printStackTrace();
}
}
}
private HashSet<Long> getRawContactIdsForContact(long contactId)
{
HashSet<Long> ids = new HashSet<Long>();
Cursor cursor = getContentResolver().query(RawContacts.CONTENT_URI,
new String[]{RawContacts._ID},
RawContacts.CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)}, null);
if (cursor != null && cursor.moveToFirst())
{
do
{
ids.add(cursor.getLong(0));
} while (cursor.moveToNext());
cursor.close();
}
return ids;
}
Note that when you perform delete, you should specify RAW_CONTACT_ID instead of CONTACT_ID. So you need to query all raw contact ids for specified contact.
Also you may need to consider account data. In that case change querying for contact ids to something like that:
Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType).build();
Cursor cursor = getContentResolver().query(rawContactUri,
new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?",
new String[] { String.valueOf(contactId) }, null);
public static Uri addContactToGroup(String rawContactId,String groupId)
{
try
{
ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(GroupMembership.GROUP_ROW_ID, groupId);
values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
return getContentResolver.insert(Data.CONTENT_URI, values);
}
catch (Exception e)
{}
return Uri.EMPTY;
}
//-----------------------------------
public static int removeContactFromGroup(String contactId,String groupId)
{
try
{
String where = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? AND " + GroupMembership.GROUP_ROW_ID + " = ?";
String[] args = {contactId, GroupMembership.CONTENT_ITEM_TYPE, groupId};
return getContentResolver.delete(Data.CONTENT_URI, where, args);
}
catch (Exception e)
{}
return 0;
}