I know there has been a lot of these questions, but unfortunately none of these helps me with my problem.
With a button click i want to add some new content to my database,
or the existing columns should be overwritten. Adding the content to my database works fine. But if i want to overwrite the existing content, my code just adds a new row to the database.
This is my Code:
Main Activity: Add Content With Button To BD
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListView shopList= (ListView) findViewById(R.id.lvShopList);
for(int i = 0; i < dataSource.size();i++){
tvname = (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvName);
tvamount= (TextView) shoppingList.getChildAt(i).findViewById(R.id.tvAmount);
String nameTV = tvname.getText().toString();
String amaountTV = tvamount.getText().toString();
ingredient.setName(nameTV);
ingredient.setAmpunt(amaountTV );
myDB.getInstance(MainActivity.this).increaseIngredient(ingredient);
}
}
});
This Is My DB Class
public Ingredient increaseIngredient(final Ingredient ingredient){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, ingredient.getName());
values.put(COL_AMOUNT, ingredient.getAmount());
long newID = db.insert(TABLE_NAME, null, values);
db.close();
return getiIngredient(newID);
//Also tried this code, but with this, nothing will be shown:
// db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});
// db.close();
// return getiIngredient(ingredient.getId());
}
public Ingredient getIngredient(final long id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query
(TABLE_NAME, new String[]{KEY_ID, COL_NAME, COL_AMOUNT},
KEY_ID + " = ?",
new String[]{String.valueOf(id)},
null, null, null);
Ingredient ingredient = null;
if(c != null && c.getCount() > 0) {
c.moveToFirst();
ingredient = new Ingredient(c.getString(c.getColumnIndex(COL_NAME)));
ingredient.setId(c.getLong(c.getColumnIndex(KEY_ID)));
ingredient.setAmount(c.getString(c.getColumnIndex(COL_AMOUNT)));
}
db.close();
return ingredient;
}
This Is My Model Class
public class Ingredient implements Serializable {
private long id;
private String name;
private String amount;
public Zutaten() {
this(null, null);
}
public Zutaten(String name) {
this(name, null);
}
public Zutaten(String name, String amount) {
this.name = name;
this.amount= amount;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount= amount;
}
}
EDIT: This is my activity where i want to show the DB Content:
public class StorageDB extends AppCompatActivity {
myDB dbIngredients;
ListView lvDB;
TextView name, amount;
ArrayList<Ingredients> dataSource;
DbStorageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredient_storage);
lvDB= (ListView) findViewById(R.id.lvDB);
dataSource = dbIngredients.getInstance(this).getAllIngredient();
this.adapter = new DbStorageAdapter (dataSource, this);
lvDB.setAdapter(adapter);
name = (TextView)findViewById(R.id.tvName);
amount= (TextView)findViewById(R.id.tvAmount);
showDBcontent();
}
private void showDBcontent(){
myDB db = new myDB (this);
ArrayList<Ingredients> iList = db.getAllIngredient();
adapter = new DbStorageAdapter (zList, this);
lvDB.setAdapter(adapter);
}
}
So if i use update, the listview in my storage activity is empty, and if i use insert all the rows from the database will be shown.
With the first click i add 8 rows to the database. If i use db.insert and click on the button i have 16 rows in my database, and all 16 rows will be shown in the storage activity.
SECOND EDIT:
In fact I just want that my code checks after button click if the table exists. If it exists i want that it will update my table rows. If the table does not exist I want that it insert my content which is send by button click.
I tried this, but it does not work:
public Ingredient increaseIngredient (final Ingredient ingredient ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery
("SELECT * FROM " + TABLE_NAME + " WHERE " + COL_NAME + " = ?",
null);
ContentValues values = new ContentValues();
values.put(COL_NAME, ingredient .getName());
values.put(COL_AMOUNT, ingredient .getAmount());
if(c !=null && c.getCount() > 0){
db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(zutaten.getId())});
db.close();
return getZutat(zutaten.getId());
} else {
long newID = db.insert(TABLE_NAME, null, values);
db.close();
return getZutat(newID);
}
This:
db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});
would update the row with id = ingredient.getId() if this id exists in the table.
When you call:
myDB.getInstance(MainActivity.this).increaseIngredient(ingredient);
the ingredient object does not contain the id that you want to update.
If you do something like this:
ingredient.setId(10);
prior to calling increaseIngredient() then if there exists a row with id = 10, then this row will be updated.
Edit from comments:
I mean something like this:
public Ingredient increaseIngredient (Ingredient ingredient) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, ingredient.getName());
values.put(COL_AMOUNT, ingredient.getAmount());
if (ingredient.getId() == null) {
long newID = db.insert(TABLE_NAME, null, values);
db.close();
return ???;
} else {
db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(ingredient.getId())});
db.close();
return ???;
}
}
The question marks mean I don't know what you need to return.
Related
I spend much time on SQLite and I have a problem in deleting an item if it exist!
I'm working in Bookmark App that save links from webview into listview using SQLite, my problem is can't check if the item is exist > don't create a link.
this is my BookmarksDatabase used for sqlite:
public class BookmarksDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "bookmarks.db";
private static final String TABLE_NAME = "bookmarks_data";
private static final String COL1 = "ID";
private static final String COL2 = "ITEM1";
private static final String COL3 = "ITEM2";
public BookmarksDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " ITEM1 TEXT, " + " ITEM2 TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item1, String item2) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item1);
contentValues.put(COL3, item2);
long result = db.insert(TABLE_NAME, null, contentValues);
// if date as inserted incorrectly it will return -1
return result != -1;
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
public ArrayList<Bookmarks> getAllData() {
ArrayList<Bookmarks> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
while (data.moveToNext()) {
int id = data.getInt(0);
String title = data.getString(1);
String link = data.getString(2);
Bookmarks bookmarks = new Bookmarks(id, title, link);
arrayList.add(bookmarks);
}
return arrayList;
}
public int deleteSpecificContents(int id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, COL1 + "=?", new String[]{Integer.toString(id)});
}
}
this is my code used in MainActivity to fetch items on listview
/*---------------- Bookmark Tab, sqlite databases integrated ---------------*/
private void showBookmarksScreen() {
// initialize a dialog in the main activity
final Dialog bookmarksScreen = new Dialog(this);
bookmarksScreen.requestWindowFeature(Window.FEATURE_NO_TITLE);
bookmarksScreen.setContentView(R.layout.activity_bookmark);
bookmarksScreen.setCancelable(true);
final ListView listView = bookmarksScreen.findViewById(R.id.bookmark_list);
RelativeLayout bookmarkEmpty = bookmarksScreen.findViewById(R.id.bookmark_empty);
// create an array and call bookmark
// database to retrive data then
// fetch it into list view
arrayList = new ArrayList<>();
arrayList = bookmarkDB.getAllData();
// get all data from sqlite database
Cursor data = bookmarkDB.getListContents();
// check if no bookmarks
// then show view that inform
// user that there is no bookmarks
if(data.getCount() == 0 ) {
bookmarkEmpty.setVisibility(View.VISIBLE);
}
bookmarkListAdpater = new BookmarkListAdpater(this, arrayList);
listView.setAdapter(bookmarkListAdpater);
bookmarkListAdpater.notifyDataSetChanged();
// load link on item click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView link = view.findViewById(R.id.list_link);
String convertedLink = link.getText().toString();
webView.loadUrl(convertedLink);
bookmarksScreen.dismiss();
}
});
// ask user to delete bookmark on item long click
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
// initialize a dialog in the main activity
final Dialog deleteDialog = new Dialog(MainActivity.this);
deleteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
deleteDialog.setContentView(R.layout.activity_confirm);
// confirm message or dialog can't be
// canceled so we set it to false
deleteDialog.setCancelable(false);
TextView deleteMessage = deleteDialog.findViewById(R.id.confirm_text);
TextView deleteConfirm = deleteDialog.findViewById(R.id.confirm_allow);
TextView deleteCancel = deleteDialog.findViewById(R.id.confirm_deny);
deleteMessage.setText(getString(R.string.delete_bookmark));
// confirm button
deleteConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor data = bookmarkDB.getListContents();
int i = 0;
while(data.moveToNext()){
if(i == position){
break;
}
i++;
}
bookmarkDB.deleteSpecificContents(data.getInt(0));
deleteDialog.dismiss();
bookmarksScreen.dismiss();
customToast(getString(R.string.bookmark_deleted), 0);
}
});
// confirm cancel
deleteCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.dismiss();
}
});
deleteDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
deleteDialog.show();
return true;
}
});
bookmarksScreen.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
bookmarksScreen.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
bookmarksScreen.show();
}
My Model
public class Bookmarks {
int id;
String title, link;
public Bookmarks(int id, String title, String link) {
this.id = id;
this.title = title;
this.link = link;
}
public Bookmarks() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
any ideas? thanks.
Try using below to delete item from DB
bookmarkDB.deleteSpecificContents(arrayList.get(position).getId(0));
If you want to check item exists or not before adding then add below code in your BookmarksDatabase
public boolean isExists(String link) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COL3 + "='" + link + "'", null);
return cursor.getCount() > 0;
}
And then check
if(bookmarkDB.isExists(link))
//Already Exist
else
//Not Exist, add now
With the same logic you're using:
SQLiteDatabase db = new DatabaseManager(context).getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + ID_KEY + " = ?";
Cursor cursor = db.rawQuery(query, new String[]{Integer.toString(id)});
if(cursor.moveToFirst()){
db.delete(TABLE_NAME, ID_KEY + " = ?", new String[]{Integer.toString(id)});
}
cursor.close();
db.close();
Another possibility is changing the method return type to boolean and verifying the return count from the delete command:
public boolean deleteSpecificContents(int id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, COL1 + "=?", new String[]{Integer.toString(id)}) > 0;
}
I'm currently working an application on Android Studio and I have a little problem, hope you can help me. This application is made using Model-View-Presenter and in the Login activity (the main activity). I call a REST service to get data and save it in the data base, in the interactor class I have this mehtod to save the data of the JSON object in the database
private long insertLoginData() throws JSONException {
HelperDB dbObj = new HelperDB(_ctx);
ContentValues values = new ContentValues();
String firstName = "";
String lastName = "";
values.put(userTableFields[1], _objJson.getString(userTableFields[1]));
if (_objJson.has("fullName")){
JSONObject objFullName = _objJson.getJSONObject("fullName");
firstName = (objFullName.has(userTableFields[2]) ? objFullName.getString(userTableFields[2]) : "");
lastName = (objFullName.has(userTableFields[3]) ? objFullName.getString(userTableFields[3]) : "");
}
values.put(userTableFields[2], firstName);
values.put(userTableFields[3], lastName);
values.put(userTableFields[4], (_objJson.has(userTableFields[4]) ? _objJson.getString(userTableFields[4]) : ""));
values.put(userTableFields[5], true);
values.put(userTableFields[6], _userName);
values.put(userTableFields[7], _Password);
long localId = dbObj.insertStatement(0, values);
dbObj.closeDB();
return localId;
}
_ctx is a local variable of Context in the Presenter, it comes from Main Activity. And userTableFields Array contains the name of fields of my table users and it comes from the strings resource.
I know, this is a manual way to do it, I could use POJO to cast in classes the model of the JSON data, but this is no the problem. I use the debug console to check localId variable is returning a value different to -1, so record is inserting ok in the database.
After validate the user and insert the user records (user informations and its notifications) to data base I open a new Activity (the second activity) and then I call a method in the Presenter to get the user data and trying to show it in this new activity.
public class Home extends AppCompatActivity implements HomeView{
private HomePresenter presenter;
private ListView lvNotifications;
private TextView tvWelcome;
private ProgressBar pbHome;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
presenter = new HomePresenterImpl(this);
lvNotifications = (ListView)findViewById(R.id.lvNotifications);
tvWelcome = (TextView)findViewById(R.id.tvWelcome);
pbHome = (ProgressBar)findViewById(R.id.pbHome);
setTitle(getResources().getString(R.string.titleHome));
presenter.getNotificationsDataPresenter(getApplicationContext());
lvNotifications.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//presenter.getSelectedItem(position, _linkResource);
}
});
}
#Override
public void setDataSourceListView(String[] itemArray, String[] linkResource) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, itemArray);
lvNotifications.setAdapter(adapter);
}}
The problem is here. In the Presenter of the second activity I call a method in the database to get the notifications of users, even, if I change the sentence directly to "SELECT * FROM users" it always comes empty, I searched lot of topics about it but do not get solution.
This is the method to get data of users and does not work although inserts are happening satisfactorily in the first activity.
private void getNotificationsData(String query){
HelperDB dbObj = new HelperDB(_ctx);
Cursor cursor = dbObj.getQueryStatement(query, null);
itemArray = new String[cursor.getCount()];
linkResource = new String[cursor.getCount()];
int i = 0;
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
try{
while(cursor.moveToNext()){
itemArray[i] = cursor.getString(0);
linkResource[i] = cursor.getString(1);
i++;
}
}
finally {
cursor.close();
dbObj.close();
}
}
}
I was thinking it could be an issue about the Context, because en the first Activity I execute other functions in the data base and there are no problems, but in the second activity data of any kind is returned, the Cursor does not break or throw error, its variable mCount always is -1 and size is 0.
The following is the SQLiteOpenHelper that I'm using to connect the database.
public class HelperDB extends SQLiteOpenHelper{
private static final String DBName = "MyDb";
private static String createUserTableStatement = "";
private static String createNotificationsTableStatement = "";
String[] tableNames, userTableFields, notificationsTableFields;
public HelperDB(Context context) {
super(context, DBName, null, 1);
tableNames = context.getResources().getStringArray(R.array.tableNames);
userTableFields = context.getResources().getStringArray(R.array.userTableFields);
notificationsTableFields = context.getResources().getStringArray(R.array.notificationsTableFields);
createUserTableStatement = "CREATE TABLE " + tableNames[0] + " (" + userTableFields[0] + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ userTableFields[1] + " TEXT, " + userTableFields[2] + " TEXT, " + userTableFields[3]
+ " TEXT, " + userTableFields[4] + " TEXT, " + userTableFields[5] + " BOOLEAN, " + userTableFields[6] + " TEXT, "
+ userTableFields[7] + " TEXT)";
createNotificationsTableStatement = "CREATE TABLE " + tableNames[1] + " (" + notificationsTableFields[0]
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + notificationsTableFields[1] + " TEXT, "
+ notificationsTableFields[2] + " TEXT, " + notificationsTableFields[3]
+ " TEXT, " + notificationsTableFields[4] + " TEXT, " + notificationsTableFields[5] + " TEXT)";
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createUserTableStatement);
db.execSQL(createNotificationsTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int i = 0; i < tableNames.length; i++)
db.execSQL("DROP TABLE IF EXISTS " + tableNames[i]);
onCreate(db);
}
public void closeDB() {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null && db.isOpen())
db.close();
}
public long insertStatement(int tableIndex, ContentValues values){
SQLiteDatabase db = this.getWritableDatabase();
long userId;
try{
db.beginTransaction();
userId = db.insert(tableNames[tableIndex], null, values);
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
db.close();
}
return userId;
}
public Cursor getQueryStatement(String queryStatement, String[] fieldsArray){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryStatement, fieldsArray);
return cursor;
}
}
The question is what I'm doing wrong when I want to get data records in a second activity that previously in a prevoius activity were inserted?
Note: I always send getApplicationContext as parameter to the Presenter because methods in the SqliteOpenHelper needs the context in the construtor.
You should make POJO class and implement Parcelable like below code just modify your params
public class User implements Parcelable {
private Integer id;
private String userName;
private Integer age;
public User() {
}
protected User(Parcel in) {
userName = in.readString();
age = in.readInt();
}
public static final Creator<User> CREATOR = new Creator<User>() {
#Override
public User createFromParcel(Parcel in) {
return new User(in);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
public Integer getId() {
return id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(userName);
parcel.writeInt(age);
}
Then using intent put your model into intent and getIntent in another activity where you want like:
Intent intent = new Intent(mContext,//your activity name);
intent.putExtra("yourModekey",userModel);
startActivities(intent);
in other activity get like
getIntent().getParcelableExtra("yourModelkey");
I wrote some codes using this example to save and update 2 long values in SQlite. I can create new row however I can't update it. I try everything which I can but I couldn't update a row and there is no error just not update row. I am using this code to update a row:
db.updateContact(new Contact(consumed, total));
which both consumed and total are long values. I can't see any error however still I couldn't success to update a row. My constructor and databesehandler codes are below:
Contaxt.java
public class Contact {
// private variables
int _id;
double _name;
double _phone_number;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int id, double name, double _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(double name, double _phone_number) {
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int id) {
this._id = id;
}
// getting name
public double getName() {
return this._name;
}
// setting name
public void setName(double name) {
this._name = name;
}
// getting phone number
public double getPhoneNumber() {
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(double phone_number) {
this._phone_number = phone_number;
}
}
DatabeseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(cursor.getInt(0));
contact.setName(cursor.getDouble(1));
contact.setPhoneNumber(cursor.getDouble(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
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()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Thanks in advance.
You did not set the id in Contact object.
db.updateContact(new Contact(consumed, total));
In updateContact method : following update query is used :
db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
contact.getID() returns 0, and no id matched with id 0 and nothing updated.
You should pass correct id also
I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps
I use this method to delete an Item on my SQLite database:
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this to my ListView:
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
The problem is that when i delete an item on my listview the item disappears but when I re-open it the item is still there, because this doesn't remove from the database.
I 'll try to explain this with images :
This means that there is some problem with the deleting from the db. Just replace 2nd line in your deleteItem() with
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item}
Log.d("deletedItem", x);
Here x would be the number of rows deleted. Check the value of x after deleting, it should be greater than 0 if the deletion was successful. If it is not then that means the query is wrong and we would need the database schema for correcting it. From your ListView implementation code, its clear that your nameString itself is wrong. You are adding the whole Item in the arraylist and passing to the adapter. And when you fetch the item in the onItemClick dialog, you are using this code
String nameString = (arg0
.getItemAtPosition(arg2))
.toString();
Here arg0.getItemAtPosition(arg2) would return an Item object. You will have to do something like this.
Item tempItem=(Item)items.get(arg2);
String nameString=tempItem.getName();
where getName() would return the name of the item.
The change that I did:
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
to
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
String nameStringData = nameString.substring(6,
nameString.indexOf("Priority Level:") - 1);
Log.d("itemtodelete", nameStringData);
db.deleteItem(nameStringData);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
If you have a better suggestion please post an answer.
Yes this is the problem.
deletedItem = 0 on logCat so that's my database:
public class DatabaseHolder extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ItemsList";
private static final String TABLE_NAME = "Items";
private static final String ITEMS_COLUMN = "items_name";
private static final String PRIORITY_COLUMN = "Priority";
private static final String ID_COLUMN = "Items";
private static int DATABASE_VERSION = 1;
private static String QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEMS_COLUMN
+ " TEXT NOT NULL, " + PRIORITY_COLUMN + " TEXT NOT NULL);";
public DatabaseHolder(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
// Sharer!
public void addItem(String item_name, String priority) {
if (!duplicate(item_name)) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEMS_COLUMN, item_name);
values.put(PRIORITY_COLUMN, priority);
db.beginTransaction();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
public boolean duplicate(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, ITEMS_COLUMN + " =?",
new String[] { name }, null, null, null);
int temp = c.getCount();
c.close();
db.close();
if (temp > 0)
return true;
else
return false;
}
public ArrayList<Item> getAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Item> item = new ArrayList<Item>();
db.beginTransaction();
Cursor cursor = db.query(TABLE_NAME, new String[] { this.ITEMS_COLUMN,
this.PRIORITY_COLUMN }, null, null, null, null, PRIORITY_COLUMN
+ " DESC");
while (cursor.moveToNext()) {
Item itemTemp = new Item(cursor.getString(cursor
.getColumnIndexOrThrow(ITEMS_COLUMN)), new Level(
Integer.parseInt(cursor.getString(cursor
.getColumnIndexOrThrow(PRIORITY_COLUMN)))));
item.add(itemTemp);
}
cursor.close();
db.endTransaction();
db.close();
return item;
}
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
Log.d("deletedItem", String.valueOf(x) );
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}