android: showing data from sqlite to AlertDialog - java

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.

Related

. How to update individual database elements with SQLite?

Good evening everyone, this is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Users.db";
private static final String DB_TABLE = "Users_Table";
//Colonne
private static final String ID = "ID";
private static final String NAME = "NAME";
private static final String CREATE_TABLE = "CREATE TABLE "+ DB_TABLE+" ("+
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
NAME+ " TEXT "+ ")";
public DatabaseHelper (Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL( "DROP TABLE IF EXISTS "+ DB_TABLE );
onCreate( db );
}
public boolean updateData(int id, String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues( );
contentValues.put( NAME, name );
contentValues.put( ID, id );
db.update( DB_TABLE, contentValues, "ID = ?", new String[] {String.valueOf( id )} );
db.close();
return true;
}
//Metodo per inserire dati
public boolean insertData (String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues( );
contentValues.put( NAME, name );
long result = db.insert( DB_TABLE, null, contentValues );
return result != -1; //Se il risultato è = -1 i dati NON vengono inseriti
}
//Metodo per cancellare i dati
public int deleteSelectedItem(String NAME) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete( DB_TABLE, "NAME = ?", new String[] {NAME} );
return result;
}
//Metodo per visualizzare i dati
public Cursor viewData(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * from "+DB_TABLE;
Cursor cursor = db.rawQuery(query, null);
return cursor;
}}
In MainActivity I call the method like this:
builder.setPositiveButton( "Modifica", new DialogInterface.OnClickListener() {
#Override
public void onClick (DialogInterface dialog, int which) {
if (!editText.getText().toString().isEmpty()) {
listItem.set( position, editText.getText().toString().trim() );
db.updateData( editText.getText().toString() );
arrayAdapter.notifyDataSetChanged();
Toast.makeText( MainActivity.this, "Elemento modificato", Toast.LENGTH_SHORT ).show();
} else {
editText.setError( "aggiungi elemento qui" );
}
}
} );
When I use it, the ListView updates, but when I restart the emulator, the text I had edited, it returns to its original state.
So the method does not update the items in the database. What's wrong with my code? Thanks
EDIT:
This is the viewData method in the Main:
private void viewData () {
Cursor cursor = db.viewData();
if (cursor.getCount() == 0) {
Toast.makeText( this, "Nessun dato da visualizzare", Toast.LENGTH_SHORT ).show();
} else {
while (cursor.moveToNext()) {
listItem.add( cursor.getString( 1 ) );
//index 1 è il nome, index 0 è l'ID
}
arrayAdapter = new ArrayAdapter<>( MainActivity.this, R.layout.support_simple_spinner_dropdown_item, listItem );
userlist.setAdapter( arrayAdapter );
}
}
Change the definition of the table so that the column name is unique:
private static final String CREATE_TABLE = "CREATE TABLE "+ DB_TABLE+" ("+
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
NAME+ " TEXT UNIQUE"+ ")";
You will have to uninstall the app from the device so the database is deleted and rerun so that the database and the table are recreated.
Then change updateData() like this:
public boolean updateData(String currentName, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues( );
contentValues.put( NAME, newName );
boolean result = db.update( DB_TABLE, contentValues, NAME + " = ?", new String[] {currentName} ) > 0;
db.close();
return result;
}
So you pass the current name to updateData() to find the row that you want to update.
Finally change the listener of the button:
builder.setPositiveButton( "Modifica", new DialogInterface.OnClickListener() {
#Override
public void onClick (DialogInterface dialog, int which) {
if (!editText.getText().toString().isEmpty()) {
db.updateData( listItem.get( position ), editText.getText().toString().trim() );
listItem.set( position, editText.getText().toString().trim() );
arrayAdapter.notifyDataSetChanged();
Toast.makeText( MainActivity.this, "Elemento modificato", Toast.LENGTH_SHORT ).show();
} else {
editText.setError( "aggiungi elemento qui" );
}
}
});

Am I using Cursor properly with SQLite?

I'm "experimenting" with Android Studio and SQLite for the first time. My app screen turns white and freezes upon opening new activity which should show up my SQL query values.
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context context) {
super(context,"book.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table books (ID INTEGER NOT NULL PRIMARY KEY, " +
"BOOK_TITLE TEXT NOT NULL, BOOK_CATEGORY TEXT NOT NULL, " +
"BOOK_DESCRIPTION TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists books");
onCreate(db);
}
public boolean insertData(String book_title_, String book_category_, String book_description_)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put("BOOK_TITLE", book_title_);
cValues.put("BOOK_CATEGORY", book_category_);
cValues.put("BOOK_DESCRIPTION", book_description_);
long result = db.insert("book", null, cValues);
if (result == -1)
return false;
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM book", null);
return res;
}
}
I found out that the problem is in calling getAllData() fuction from another class. By my logic everything should work fine? I though that the problem is in my QUERY but according to google I've done everything good.
Any suggestions?
Try this method. It's very efficient method:
public List<Movie> getAllData()
{
List<Movie> movies_list = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM movie_collection", null);
while(res.moveToNext())
{
movies_list.add(new Movie(res.getString(1)+"\n", res.getString(2)+"\n", res.getString(3)+"\n", R.drawable.gladiator));
}
res.close();
return movies_list;
}
and in viewAll() method:
public void viewAll()
{
movies_list = movie_database.getAllData();
// do whatever you want
}

Android Studio, how to retrieve data from Sqlite database and display it into textview?

I created an SQLite Database in my app, and I insert the data into it. And now I want to retrieve data from it but I want just insert one data and retrieve it then display it into a TextView.
public class Db_sqlit extends SQLiteOpenHelper{
String TABLE_NAME = "BallsTable";
public final static String name = "db_data";
public Db_sqlit(Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+TABLE_NAME+" (id INTEGER PRIMARY KEY AUTOINCREMENT, ball TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String balls){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("ball",balls);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}
else
return true;
}
public void list_balls(TextView textView) {
Cursor res = this.getReadableDatabase().rawQuery("select ball from "+TABLE_NAME+"",null);
textView.setText("");
while (res.moveToNext()){
textView.append(res.getString(1));
}
}
}
Here is an example of how I achieved this.
In this example I will store, retrieve, update and delete a students name and age.
First create a class, I called mine
DBManager.java
public class DBManager {
private Context context;
private SQLiteDatabase database;
private SQLiteHelper dbHelper;
public DBManager(Context c) {
this.context = c;
}
public DBManager open() throws SQLException {
this.dbHelper = new SQLiteHelper(this.context);
this.database = this.dbHelper.getWritableDatabase();
return this;
}
public void close() {
this.dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.NAME, name);
contentValue.put(SQLiteHelper.AGE, desc);
this.database.insert(SQLiteHelper.TABLE_NAME_STUDENT, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_STUDENT, new String[]{SQLiteHelper._ID, SQLiteHelper.NAME, SQLiteHelper.AGE}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteHelper.NAME, name);
contentValues.put(SQLiteHelper.AGE, desc);
return this.database.update(SQLiteHelper.TABLE_NAME_STUDENT, contentValues, "_id = " + _id, null);
}
public void delete(long _id) {
this.database.delete(SQLiteHelper.TABLE_NAME_STUDENT, "_id=" + _id, null);
}
}
Then create a SQLiteOpenHelper I called mine
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String AGE = "age";
private static final String CREATE_TABLE_STUDENT = " create table STUDENTS ( _id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL , age TEXT );";
private static final String DB_NAME = "STUDENTS.DB";
private static final int DB_VERSION = 1;
public static final String NAME = "name";
public static final String TABLE_NAME_STUDENT = "STUDENTS";
public static final String _ID = "_id";
public SQLiteHelper(Context context) {
super(context, DB_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS STUDENTS");
onCreate(db);
}
}
TO ADD:
In this example I take the text from EditText and when the button is clicked I check if the EditText is empty or not. If it is not empty and the student doesn't already exist I insert the students name and age into the database. I display a Toast, letting the user know of the status:
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtName.getText().toString().trim().length() == 0) {
Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();
} else{
try {
if (edtAge.getText().toString().trim().length() != 0) {
String name = edtName.getText().toString().trim();
String age = edtAge.getText().toString().trim();
String query = "Select * From STUDENTS where name = '"+name+"'";
if(dbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
dbManager.insert(name, age);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "please provide student age!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
TO UPDATE:
Here I take the Text in EditText and update the student when the button is clicked. You can also place the following in a try/catch to make sure it is updated successfully.
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = nameText.getText().toString();
String age = ageText.getText().toString();
dbManager.update(_id, name, age);
Toast.makeText(getApplicationContext(), "Updated successfully!", Toast.LENGTH_SHORT).show();
}
});
TO DELETE:
dbManager.delete(_id);
Toast.makeText(getApplicationContext(), "Deleted successfully!", Toast.LENGTH_SHORT).show();
TO GET:
Here I get the name of the student and display it in a TextView
DBManager dbManager = new DBManager(getActivity());
dbManager.open();
Cursor cursor = dbManager.fetch();
cursor.moveToFirst();
final TextView studentName = (TextView) getActivity().findViewById(R.id.nameOfStudent);
studentName.settext(cursor.getString(0));
Then I have implement the code in main java class where I want to show using cursor.moveToNext()
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor result = databaseSQLite2.searchData(searchET.getText().toString());
while (result.moveToNext()){
searchresultTV.setText(result.getString(2));
}
}
});
For fetching data from sqlite I have done this method in DatabaseHelper class
public Cursor searchData(String id){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
//String qry = "SELECT * FROM "+TABLE_NAME+" WHERE ID="+id;
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE ID="+id,null);
return cursor;
}

SQLite database table updating all but one field

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;

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