SQLite database table updating all but one field - java

So I'm working on an Android app where I have data saved in Android's SQLite database. For some reason, streakCategory and daysKept will update fine, but streakName will not update. Does anybody have any idea why? My code is the same as it is for streakCategory and daysKept.
Snippet of EditStreak.java:
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putString("currButtonActivityName", streakIcon.getText().toString()).commit();
editor.putString("currButtonActivityCategory", categoryIcon.getText().toString()).commit();
editor.putInt("currButtonDaysKept", Integer.parseInt(streakDaysKept.getText().toString().trim())).commit();
String updateName = prefs.getString("currButtonActivityName", "").trim();
String updateCategory = prefs.getString("currButtonActivityCategory", "").trim();
int updateDaysKept = prefs.getInt("currButtonDaysKept", 0);
boolean isUpdated = db.updateData(updateName, updateCategory, updateDaysKept);
Log.d("Name: ", prefs.getString("currButtonActivityName", ""));
if (isUpdated == true){
Log.d("carter.streakly", "AFTER SUCCESS: ID: " + prefs.getInt("currButtonID", 0) + " Name: " + prefs.getString("currButtonActivityName", "") + " Category: " +
prefs.getString("currButtonActivityCategory", "") + " Days Kept: " + prefs.getInt("currButtonDaysKept", 9));
Intent intent = new Intent(EditStreak.this, EnlargedActivity.class);
startActivity(intent);
finish();
}
else{
Toast.makeText(EditStreak.this, "Data not Updated", Toast.LENGTH_LONG);
}
}
});
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "streaks.db"; // Name of DB
public static final String TABLE_NAME = "streak_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "STREAKNAME";
public static final String COL_3 = "STREAKCATEGORY";
public static final String COL_4 = "DATESTARTED";
public static final String COL_5 = "DAYSKEPT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,STREAKNAME TEXT,STREAKCATEGORY TEXT,DATESTARTED TEXT,DAYSKEPT INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String STREAKNAME, String STREAKCATEGORY, String DATESTARTED, int DAYSKEPT){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, STREAKNAME);
contentValues.put(COL_3, STREAKCATEGORY);
contentValues.put(COL_4, DATESTARTED);
contentValues.put(COL_5, DAYSKEPT);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
} else {
db.close();
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM "+TABLE_NAME,null);
return res;
}
public boolean updateData(String streakName, String streakCategory, int daysKept){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, streakName);
contentValues.put(COL_3, streakCategory);
contentValues.put(COL_5, daysKept);
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {streakName});
return true;
}
public Integer deleteData(String streakName){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "STREAKNAME = ?", new String[] {streakName});
}
public boolean vacuum(){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("VACUUM");
return true;
}
}

You can try something like this :
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
SQLiteStatement upd=db.compileStatement("UPDATE "+TABLE_NAME+" SET "+COLUMN_NAME+"=VALUE WHERE "+STREAKNAME +"=?");
upd.bindString(1, streakNameValue);
upd.execute();
db.setTransactionSuccessful();
db.endTransaction();
Log.e("update", "done");

Would that ever change according to logic ??
you are querying the record based on streakName and updating the same name.
......
contentValues.put(COL_2, streakName); // streakName = "abcd"
......
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {streakName});
return true;
// here you are querying records which have streakName as "abcd" already, so it wont change
Eithe you need to change it to query it by id of record or pass old streakname which has to be replaced by this new streakName.
db.update(TABLE_NAME, contentValues, "STREAKID = ?", new String[] {streakID});
return true;
or
contentValues.put(COL_2, NEWstreakName);
db.update(TABLE_NAME, contentValues, "STREAKNAME = ?", new String[] {OLDStreakName});
return true;

Related

multiple tables in android

I want to use two tables in my SQLite database but when I try to read the second table my app crashes.
I have a table for the items in a storage and another table for the employees of the storage.
Here is my database class:
public class Database extends SQLiteOpenHelper {
protected static final String DATABASE_NAME = "Storage";
protected static final String KEY_ID = "id";
protected static final String KEY_DESCRIPTION = "description";
protected static final String KEY_CATEGORY = "category";
protected static final String KEY_ORIGIN = "origin";
protected static final String KEY_DATE = "date";
protected static final String KEY_BRAND = "brand";
protected static final String TAB_NAME = "items";
protected static final String KEY_ID2 = "id2";
protected static final String KEY_SURNAME = "surname";
protected static final String KEY_NAME = "name";
protected static final String KEY_USERNAME = "username";
protected static final String KEY_PASSWORD = "password";
protected static final String TAB_NAME2 = "employees";
protected static final int VERSION = 1;
public Database(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TAB_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_DESCRIPTION + " TEXT, "
+ KEY_CATEGORY + " TEXT, "
+ KEY_ORIGIN + " TEXT, "
+ KEY_DATE + " TEXT, "
+ KEY_BRAND + " TEXT)";
String CREATE_DIPENDENTI_TABLE = "CREATE TABLE " + TAB_NAME2 + " ("
+ KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_SURNAME + " TEXT, "
+ KEY_NAME + " TEXT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT)";
db.execSQL(CREATE_ITEMS_TABLE);
db.execSQL(CREATE_DIPENDENTI_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME2);
this.onCreate(db);
}
public void Add(String des, String cat, String pro, String data, String brand) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_DESCRIPTION, des);
contentValues.put(KEY_CATEGORY, cat);
contentValues.put(KEY_ORIGIN, pro);
contentValues.put(KEY_DATE, data);
contentValues.put(KEY_BRAND, brand);
sqLiteDatabase.insert(TAB_NAME,null, contentValues);
sqLiteDatabase.close();
}
public void Add(String cog, String nom, String user, String pass) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURNAME, cog);
contentValues.put(KEY_NAME, nom);
contentValues.put(KEY_USERNAME, user);
contentValues.put(KEY_PASSWORD, pass);
sqLiteDatabase.insert(TAB_NAME2,null, contentValues);
sqLiteDatabase.close();
}
public Cursor getInfo() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + ";";
return sqLiteDatabase.rawQuery(query, null);
}
public ArrayList getInfoDip() {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
ArrayList<String> al=new ArrayList<>();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM " +TAB_NAME2, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
al.add(cursor.getString(cursor.getColumnIndex("surname")));
al.add(cursor.getString(cursor.getColumnIndex("name")));
al.add(cursor.getString(cursor.getColumnIndex("username")));
al.add(cursor.getString(cursor.getColumnIndex("password")));
cursor.moveToNext();
}
return al;
}
public void Modify(int cod,String des, String cat, String pro, String dat, String bran){
SQLiteDatabase db = this.getWritableDatabase();
if(!des.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET description = "+"'"+des+"' "+ "WHERE id = "+"'"+cod+"'");
if(!cat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET categoria = "+"'"+cat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!pro.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET origin = "+"'"+pro+"' "+ "WHERE id = "+"'"+cod+"'");
if(!dat.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET date = "+"'"+dat+"' "+ "WHERE id = "+"'"+cod+"'");
if(!bran.isEmpty())
db.execSQL("UPDATE "+TAB_NAME+" SET brand = "+"'"+bran+"' "+ "WHERE id = "+"'"+cod+"'");
}
public void Modify(int cod, String cog, String nom, String user, String pass){
SQLiteDatabase db = this.getWritableDatabase();
if(!cog.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET surname = "+"'"+cog+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!nom.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET name = "+"'"+nom+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!user.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET username = "+"'"+user+"' "+ "WHERE id2 = "+"'"+cod+"'");
if(!pass.isEmpty())
db.execSQL("UPDATE "+TAB_NAME2+" SET password = "+"'"+pass+"' "+ "WHERE id2 = "+"'"+cod+"'");
}
public void Delete(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME+" WHERE id= "+"'"+cod+"'");
}
public void DeleteDip(int cod){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+TAB_NAME2+" WHERE id2= "+"'"+cod+"'");
}
public Cursor Search(int cod){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE id = "+"'"+cod+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public Cursor Search(String des){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM " + TAB_NAME + " WHERE description = "+"'"+des+"';";
return sqLiteDatabase.rawQuery(query, null);
}
public void DeleteAll() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from " + TAB_NAME);
}
}
and here is the activity where I try to get the ArrayList with the data:
private Database db= new Database(this);
private ArrayList<String> al=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
db.Add("admin","admin","admin","admin");
al.addAll(db.getInfoDip());
But when I try to put the data in the ArrayList the app crashes. Can anyone help me out?
Well so far, how I learned that the best practice for formating queries is to use String.format function. Here your example:
String query = "SELECT * FROM " + TAB_NAME + ";";
Best practice:
String query = String.format("SELECT * FROM %s", TAB_NAME);
So let's get to the getInfoDip method, you should try this:
public List<ContentValues> getInfoDip() {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", TAB_NAME2);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContentValues> list = new ArrayList<>(res.getCount());
while (!res.isAfterLast()){
String surname = res.getString(res.getColumnIndex(KEY_SURNAME));
String name = res.getString(res.getColumnIndex(KEY_NAME));
String username = res.getString(res.getColumnIndex(KEY_USERNAME));
String password = res.getString(res.getColumnIndex(KEY_PASSWORD));
list.add(new ContentValues(surname, name, username, password));
res.moveToNext();
}
return list;
}
Here is my whole SQLite test program, check out maybe it helps you:
package com.example.vezba09;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_FILE_NAME = "contact_database";
public Database(#Nullable Context context) {
super(context, DATABASE_FILE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = String.format(
"CREATE TABLE IF NOT EXISTS %s (%s INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT, %s TEXT)",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID,
ContactModel.COLUMN_CONTACT_NAME,
ContactModel.COLUMN_CONTACT_EMAIL,
ContactModel.COLUMN_CONTACT_PHONE
);
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
String query = String.format("DROP TABLE IF EXISTS %s", ContactModel.TABLE_NAME);
db.execSQL(query);
onCreate(db);
}
//Dodavanje kontakta
public void addContact(String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.insert(ContactModel.TABLE_NAME, null, cv);
}
//Izmena
public void editContact(int contactId, String name, String email, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ContactModel.COLUMN_CONTACT_NAME, name);
cv.put(ContactModel.COLUMN_CONTACT_EMAIL, email);
cv.put(ContactModel.COLUMN_CONTACT_PHONE, phone);
db.update(ContactModel.TABLE_NAME,
cv,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public int deleteContact(int contactId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)});
}
public ContactModel getContactById(int contactId) {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s WHERE %s = ?",
ContactModel.TABLE_NAME,
ContactModel.COLUMN_CONTACT_ID);
Cursor res = db.rawQuery(query, new String[] {String.valueOf(contactId)});
if(res.moveToFirst()) {
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
return new ContactModel(contactId, name, email, phone);
}
else {
return null;
}
}
public List<ContactModel> getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
String query = String.format("SELECT * FROM %s", ContactModel.TABLE_NAME);
Cursor res = db.rawQuery(query, null);
res.moveToFirst();
List<ContactModel> list = new ArrayList<>(res.getCount());
while(!res.isAfterLast()) {
int contactId = res.getInt(res.getColumnIndex(ContactModel.COLUMN_CONTACT_ID));
String name = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_NAME));
String email = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_EMAIL));
String phone = res.getString(res.getColumnIndex(ContactModel.COLUMN_CONTACT_PHONE));
list.add(new ContactModel(contactId, name, email, phone));
res.moveToNext();
}
return list;
}
}
Try this and feel free to ask more questions :)
Best regards, Sanady

Picasso is loading URL but no picture is shown

I have one of the weirdest problems I've had so far. I am creating an app which sends information about books and authors through different activities. I am sending them with the help of intents. My problem is within the authors section. I am sending name, age and the picture. Name and age are send successfully and to my knowledge with the debugger, the image is sent successfully as well. However, Picasso refuses to load it in ImageView. There are no errors shown and I have no idea what is going on. Here is some code.
This function resets the information in my database:
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
AuthorAdapter class. This is the adapter for my recycler view which displays details about the author. It is also where I start up the intent to move to the other activity:
#Override
public void onBindViewHolder(#NonNull AuthorsViewHolder holder, int position) {
if (!mCursor.moveToPosition(position))
{
return;
}
final int author_id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_1));
final String name = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_2));
final String age = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_3));
final String image = mCursor.getString(mCursor.getColumnIndex(DatabaseHelper.AUTHORS_COL_4));
holder.authorIndex.setText(String.valueOf(author_id));
holder.authorName.setText(name);
holder.authorAge.setText(String.valueOf(age));
holder.authorName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), displayBooksFromAuthor.class);
intent.putExtra("Author_id", author_id);
intent.putExtra("Author_name", name);
intent.putExtra("Author_age", age);
intent.putExtra("Author_image", image);
mContext.startActivity(intent);
}
});
}
And finally, my DisplayAuthorDetails class which receives the data from the intent and displays it:
int author_id = intent.getIntExtra("Author_id", 0);
String author_name = intent.getStringExtra("Author_name");
String author_age = intent.getStringExtra("Author_age");
String author_picture = intent.getStringExtra("Author_image");
et_name.setText(author_name);
et_age.setText(author_age);
et_id.setText(String.valueOf(author_id));
Picasso.get().load(author_picture).into(author_image);
I have the library dependency and also the two permissions in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
implementation 'com.squareup.picasso:picasso:2.71828
The weirdest part of this problem is that when I create a brand new project and try to load an image it loads successfully. Any help is appreciated. Thank you for your time
EDIT
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Books and Authors.db";
public static final String TABLE_NAME_AUTHORS = "Authors_table";
public static final String AUTHORS_COL_1 = "Author_ID";
public static final String AUTHORS_COL_2 = "Name";
public static final String AUTHORS_COL_3 = "Age";
public static final String AUTHORS_COL_4 = "Author_picture";
public static final String TABLE_NAME_BOOKS = "Books_table";
public static final String BOOKS_COL_1 = "Book_ID";
public static final String BOOKS_COL_2 = "Author_Foreign";
public static final String BOOKS_COL_3 = "Title";
public static final String BOOKS_COL_4 = "Price";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_BOOKS + " (Book_ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT," + "Author_Foreign INT," + "Price TEXT)");
db.execSQL("create table " + TABLE_NAME_AUTHORS + " (Author_ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT," + "Age INTEGER," + "Author_picture TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_AUTHORS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_BOOKS);
onCreate(db);
}
public boolean insertDataBooks(String title, float price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean insertDataAuthors(String name, int age) {
SQLiteDatabase mydb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
long result = mydb.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfo(int foreign_author_id, String title, double price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BOOKS_COL_2, foreign_author_id);
contentValues.put(BOOKS_COL_3, title);
contentValues.put(BOOKS_COL_4, price);
long result = db.insert(TABLE_NAME_BOOKS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public boolean addBegginingInfoAuthor(String name, int age, String image)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AUTHORS_COL_2, name);
contentValues.put(AUTHORS_COL_3, age);
contentValues.put(AUTHORS_COL_4, image);
long result = db.insert(TABLE_NAME_AUTHORS, null, contentValues);
if (result == 1) {
return false;
} else {
return true;
}
}
public Integer deleteBook(String index) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_BOOKS, "Book_ID = ?", new String[]{index});
}
public Integer deleteAuthor(String authorIndex) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_AUTHORS, "Author_ID = ?", new String[]{authorIndex});
}
public void resetBookTable() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_BOOKS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_BOOKS + "'");
addBegginingInfo(1, "Harry Potter", 9.99);
addBegginingInfo(1, "Fantastic Beasts", 14.99);
addBegginingInfo(2, "Lord of the Rings", 8.99);
addBegginingInfo(2, "The Hobbit", 12.99);
addBegginingInfo(3, "Sherlock Holmes", 6.99);
addBegginingInfo(3, "Valley of Fear", 7.99);
}
public void resetAuthor()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_AUTHORS);
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + TABLE_NAME_AUTHORS + "'");
addBegginingInfoAuthor("J.K.Rowling", 54, "https://www.biographyonline.net/wp-content/uploads/2014/05/jk-rowling4.jpg");
addBegginingInfoAuthor("J.R.R. Tolken", 81, "https://www.biography.com/.image/t_share/MTE5NTU2MzE2Mzg4MzYxNzM5/jrr-tolkien-9508428-1-402.jpg");
addBegginingInfoAuthor("Arthur Conan Doyle", 71, "https://upload.wikimedia.org/wikipedia/commons/b/bd/Arthur_Conan_Doyle_by_Walter_Benington%2C_1914.png");
}
}
After many hours of trying I finally found out that to fix this issue I just had to re-install the app on the emulator.

android: showing data from sqlite to AlertDialog

I'm having problem with my codes. I created 2 tables in android sqlite and I like to show the data from the database using AlertDialog but when I click the view Button it will go back to the previous activity. please check my codes. thank you
My DatabaseHelper :
private static final String TABLE_CREATE_QUIZ = "create table quiz (QUIZ_ID integer primary key not null ,"+
"question text not null, answer1 text not null, answer2 text not null, answer3 text not null, answer4 text not null);";
public DatabaseHelper(Context context)
{
super(context , DATABASE_NAME , null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
db.execSQL(TABLE_CREATE_QUIZ);
this.db = db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
String query1 = "DROP TABLE IF EXISTS "+TABLE_CREATE_QUIZ;
db.execSQL(query);
db.execSQL(query1);
this.onCreate(db);
}
public void insertContact(Contact c) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from contacts";
Cursor cursor = db.rawQuery(query , null);
int count = cursor.getCount();
values.put(COLUMN_ID , count);
values.put(COLUMN_NAME , c.getName());
values.put(COLUMN_EMAIL , c.getEmail());
values.put(COLUMN_UNAME, c.getUname());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public boolean insertQuest(String question, String answer1, String answer2, String answer3, String answer4){
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String query1 = "select * from quiz";
Cursor cursor = db.rawQuery(query1 , null);
int count = cursor.getCount();
contentValues.put(COLUMN_QUIZ_ID, count);
contentValues.put(COLUMN_QUESTION, question);
contentValues.put(COLUMN_ANSWER1, answer1);
contentValues.put(COLUMN_ANSWER2, answer2);
contentValues.put(COLUMN_ANSWER3, answer3);
contentValues.put(COLUMN_ANSWER4, answer4);
long result = db.insert(TABLE_QUIZ, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData(){
db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from"+TABLE_QUIZ,null);
return res;
}
My Viewing codes:
public void viewAll(){
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = helper.getAllData();
if(res.getCount()== 0){
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()){
buffer.append("Id:"+ res.getString(0)+"\n");
buffer.append("Question:"+ res.getString(1)+"\n");
buffer.append("Answer1:"+ res.getString(2)+"\n");
buffer.append("Answer2:"+ res.getString(3)+"\n");
buffer.append("Answer3:"+ res.getString(4)+"\n");
buffer.append("Answer4:"+ res.getString(5)+"\n\n");
}
showMessage("Data",buffer.toString());
}
});
}
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
You should probably drop TABLE_QUIZ instead of TABLE_CREATE_QUIZ if that is the table name.
But your problem lays in the fact you are missing a space between from and TABLE_QUIZ in your getAllData method.

Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it

I am having difficulty inserting image in my sqlite database. There are no syntax errors in my code. After I run it, the app automatically force stops. The logcat shows:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at com.synergy88studios.catalogapp.DatabaseHandler.getAllItemsInList(DatabaseHandler.java:86)
at com.synergy88studios.catalogapp.MainActivity.onCreate(MainActivity.java:56)
Here is my method in getAllItemsInList in my DatabaseHandler.class
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
In my MainActivity, I simply call the method.
items = db.getAllItemsInList();
EDIT
DatabaseHandler.class
public class DatabaseHandler extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CatalogItems";
public static final String TABLE_ITEMS = "Items";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESC = "description";
public static final String KEY_IMAGE = "image";
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_DESC};
//private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "( "
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT, " + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_ITEMS);
onCreate(db);
}
public void addItems(Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
db.insert(TABLE_ITEMS, null ,values);
db.close();
}
Item getItem(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC , KEY_IMAGE}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getBlob(3));
return item;
}
void deleteAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+ TABLE_ITEMS);
}
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
String where = null;
Cursor c = db.query(true, TABLE_ITEMS, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public int getItemsCount(){
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
}
public void deleteContact(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
db.close();
}
}
I hope someone can explain to me what happens. I can post my other classes for reference.
Don't store large data in an Android sqlite table. In particular, the CursorWindow only supports row data up to 2MB. If your row is larger, you can't access it.
Instead, store your blobs as files in the filesystem and store just the path in database.

Delete an Item on Listview but this doesnt deleted from SQLite

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();
}
}

Categories