I have a bug in my code. Whenever I delete items from my SQ Lite database, the itens are deleted. Although, when I insert a new item, the items who were removed appear again. Can you help me? Sorry to bother, but i don't know what to do.
Here it is my MainActivity.
MainActivity.java
public class MainActivity extends Activity
{
private InputDbHelper mHelper;
private ListView mListView;
private EditText mEditText;
private Button mButton;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
mHelper = new InputDbHelper(this);
updateUI();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, input);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
list.remove(positionToRemove);
adapter.remove(String.valueOf(positionToRemove));
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<String>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (adapter== null) {
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
taskList);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(taskList);
adapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
My Database:
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
By doing this:
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry._ID + " = ?", new String[] {
String.valueOf(positionToRemove)
}
);
you're coding it to use the position of the ListView item as a table ID, which it may work for the first rows when you create a new table, but when you'll start deleting items all things will get messed up.
You'll have to store the ID's either by creating a custom class for ArrayAdapter or by storing row ID to an Array/List and use positionToRemove to get the ID from that List, but that it can result to unexpected behaviur if you mess with the ListView and don't update the List data.
Check this question Custom Adapter for List View to see how you can create a custom adapter and save row ID to all ListView items along with the text.
Related
I am having trouble with my programming project. I am creating a shopping application and all I need is deleting the selected data from listview and mysqlite database with a click of a button. I also created a query on my sqlite where it will delete primary key autoincrement integer.
Here is my class:
public class CartPage extends AppCompatActivity {
DatabaseHelper myDB;
public Button button_delete;
public Button button_home;
public TextView textView_totalAmount;
public TextView textView_PK;
public ListView listView_datas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page);
myDB = new DatabaseHelper(this);
listView_datas = (ListView) findViewById(R.id.listView_ShoppingData);
button_delete = (Button) findViewById(R.id.button_deleteData);
button_home = (Button) findViewById(R.id.button_HomePage);
textView_totalAmount = (TextView) findViewById(R.id.textView_DisplayTotalAmount);
int total = myDB.addPrice();
textView_totalAmount.setText("$" + Integer.toString(total));
final ArrayList<String> list_cart = new ArrayList<>();
final Cursor data = myDB.getPrice_cart();
if (data.getCount() == 0) {
Toast.makeText(CartPage.this, "The Database is empty..", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
list_cart.add(data.getString(1) + "\n" +
data.getString(2) + "\n");
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, list_cart);
listView_datas.setAdapter(listAdapter);
}
}
button_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goHome = new Intent(CartPage.this, FirstPage.class);
startActivity(goHome);
}
});
}
}
Here is my database helper query for deleting the data by primary key
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(table_Cart,"number = ?" , new String[] {number} );
}
For this scenario I was thinking on using but I am not sure how to do it.
listView_datas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
I also saw where when you hold the selected item it would get deleted. I don't mind that as long as it deletes the data.
Thank you!
I would suggest you implement a long click listener in your ListView and on long click on the item in your list, it will show an option to delete the corresponding item in your list. Here's a sample code that can help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View view, final int position, long arg3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RecipeList.this);
alertDialog.setTitle("Delete");
alertDialog.setMessage(yourList.get(position));
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteSelectedItem(yourList.get(position))
}
});
alertDialog.show();
return true;
}
});
And yes, you need to call notifyDataSetChanged() in your deleteSelectedItem() function to see the effect of the delete in your list.
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(table_Cart,"number = ?" , new String[] {number} );
// Update your list here
// Remove the deleted item from the list that you have passed to the adapter. Then call notifyDataSetChanged
updateYourListCart();
myAdapter.notifyDataSetChanged();
}
I'm making a wine list app. I'm also trying to use SQLite in it which I'm having a very hard time getting the hang of.
I have a number of activities but there are two that are relevant to this right now.
MainActivity - this just shows the names of the wines in a ListView
AddActivity - this has EditTexts for the wine name, price, and description.
The trouble I'm having currently is that when I add a wine to the list, when I get back to the MainActivity the list doesn't show the newly added Wine until I close the app and go back into it.
How do I fix this?
Here is my main method:
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
ListView listView;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentGoToAdd = new Intent(MainActivity.this, AddActivity.class);
startActivity(intentGoToAdd);
}
});
mDatabaseHelper = new DatabaseHelper(this);
arrayListAndAdapter();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
//Which columns I want to select
String[] projection = {
WineContract.WineEntry.COLUMN_ID,
WineContract.WineEntry.COLUMN_WINE_NAME,
WineContract.WineEntry.COLUMN_WINE_PRICE,
WineContract.WineEntry.COLUMN_WINE_DESCRIPTION};
Cursor cursor = db.query(WineContract.WineEntry.TABLE_NAME, projection,null,null,null,null,null);
cursor.moveToPosition(position);
Intent intentGoToDetails = new Intent(MainActivity.this,DetailsActivity.class);
String name = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_NAME));
String price = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_PRICE));
String description = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_DESCRIPTION));
intentGoToDetails.putExtra("NAME", name);
intentGoToDetails.putExtra("PRICE", price);
intentGoToDetails.putExtra("DESCRIPTION", description);
startActivity(intentGoToDetails);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_deleteDB) {
mDatabaseHelper.deleteDatabase();
return true;
}
return super.onOptionsItemSelected(item);
}
public void arrayListAndAdapter(){
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
//Which columns I want to select
String[] projection = {
WineContract.WineEntry.COLUMN_ID,
WineContract.WineEntry.COLUMN_WINE_NAME,
WineContract.WineEntry.COLUMN_WINE_PRICE,
WineContract.WineEntry.COLUMN_WINE_DESCRIPTION};
Cursor cursor = db.query(WineContract.WineEntry.TABLE_NAME, projection,null,null,null,null,null);
ArrayList<String> mArrayList = new ArrayList<String>();
while(cursor.moveToNext()) {
mArrayList.add(cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_NAME))); //add the item
}
listView = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mArrayList);
listView.setAdapter(adapter);
}
}
Here is the AddActivity:
public class AddActivity extends AppCompatActivity {
EditText editWineName, editWinePrice, editWineDescription;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
mDatabaseHelper = new DatabaseHelper(this);
editWineName = (EditText) findViewById(R.id.editWineName);
editWinePrice = (EditText) findViewById(R.id.editWinePrice);
editWineDescription = (EditText) findViewById(R.id.editWineDescription);
}
public void toastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_deleteDB) {
long result = mDatabaseHelper.addWine(editWineName.getText().toString(), editWinePrice.getText().toString(), editWineDescription.getText().toString() );
if (result!=-1){
toastMessage(editWineName.getText().toString() + " was added to the list.");
finish();
}else{
toastMessage("Error");
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
And if necessary, here is my DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "wines.db";
private static final String SQL_CREATE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_WINE_NAME + " TEXT, " +
COLUMN_WINE_PRICE + " TEXT, " +
COLUMN_WINE_DESCRIPTION + " TEXT);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addWine(String name, String price, String description){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_WINE_NAME, name);
values.put(COLUMN_WINE_PRICE, price);
values.put(COLUMN_WINE_DESCRIPTION, description);
return db.insert(TABLE_NAME,null, values);
}
public void deleteDatabase(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
}
Your activity is only created once so onCreate is only called the first time. What you want is the data to be fresh every time MainActivity resumes. If you override the onResume method and put your arrayListAndAdapter() method and setOnItemClickListener you will get the desired effect. So here's the new code (you can remove this code from onCreate as well to prevent querying twice):
#Override
protected void onResume() {
super.onResume();
arrayListAndAdapter();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
//Which columns I want to select
String[] projection = {
WineContract.WineEntry.COLUMN_ID,
WineContract.WineEntry.COLUMN_WINE_NAME,
WineContract.WineEntry.COLUMN_WINE_PRICE,
WineContract.WineEntry.COLUMN_WINE_DESCRIPTION};
Cursor cursor = db.query(WineContract.WineEntry.TABLE_NAME, projection,null,null,null,null,null);
cursor.moveToPosition(position);
Intent intentGoToDetails = new Intent(MainActivity.this,DetailsActivity.class);
String name = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_NAME));
String price = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_PRICE));
String description = cursor.getString(cursor.getColumnIndex(WineContract.WineEntry.COLUMN_WINE_DESCRIPTION));
intentGoToDetails.putExtra("NAME", name);
intentGoToDetails.putExtra("PRICE", price);
intentGoToDetails.putExtra("DESCRIPTION", description);
startActivity(intentGoToDetails);
}
});
I made a custom Adapter for my ListView following this tutorial.
But when I run my app on my device, it gives an error when it's starting.
The error appears when the onCreate() method of the MainActivity tries to call the getData() method of the NotesDbHelper class.
Can you help me?
MainActivity.java
public class MainActivity extends Activity
{
private EditText mEditText;
private Button mButton;
NotesCustomAdapter notesCustomAdapter = null;
ListView listView = null;
NotesDbHelper database = null;
ArrayList<Notes> notes = null;
/** Called when the activity is first created.
* #param savedInstanceState */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
database = new NotesDbHelper(this);
notes = database.getData();
notesCustomAdapter= new NotesCustomAdapter(this,R.layout.notes_details,notes);
listView = (ListView) findViewById(R.id.simpleListView);
listView.setAdapter(notesCustomAdapter);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
database.insertNote(input);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
database.deleteNote(which);
notes.remove(positionToRemove);
notesCustomAdapter.remove(String.valueOf(positionToRemove));
notesCustomAdapter.notifyDataSetChanged();
}});
adb.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
NotesDbHelper.java
public class NotesDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Notes.db";
public static final String NOTES_TABLE_NAME = "Notes.user";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NAME = "n_text";
public NotesDbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + NOTES_TABLE_NAME +
"(_id integer primary key AUTOINCREMENT NOT NULL," + NOTES_COLUMN_NAME +
")"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+ DATABASE_NAME);
onCreate(db);
}
public boolean insertNote(String text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.insert(NOTES_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList<Notes> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Notes> notes = new ArrayList<Notes>();
Cursor result = db.rawQuery("select * from "+ NOTES_TABLE_NAME , null);
while(result.moveToNext()){
notes.add( new Notes(result.getString(result.getColumnIndex(NOTES_COLUMN_NAME))));
}
return notes;
}
public boolean updateNotes(int id, int text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("n_text", text);
db.update(NOTES_TABLE_NAME, contentValues, "id = ? ", new String[]{Integer.toString(id)});
return true;
}
public Integer deleteNote(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(NOTES_TABLE_NAME,
"id = ? ",
new String[]{Integer.toString(id)});
}
}
Notes.java
public class Notes {
String text;
public Notes(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
NotesCustomAdapter.java
public class NotesCustomAdapter extends ArrayAdapter{
private Context context;
private ArrayList<Notes> notes;
public NotesCustomAdapter(Context context, int textViewResourceId, ArrayList objects) {
super(context,textViewResourceId, objects);
this.context= context;
notes=objects;
}
private class ViewHolder
{
TextView text;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.notes_details, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Notes textNotes = notes.get(position);
holder.text.setText(textNotes.getText());
return convertView;
}
}
LogCat
the first line says:
java.lang.RuntimeException: Unable to start activity ComponentInfo{agenda.com/agenda.com.MainActivity}: android.database.sqlite.SQLiteException: unknown database Notes (code 1): while compiling: create table Notes.user(_id integer primary key AUTOINCREMENT NOT NULL,n_text)
Why Notes.user? You're putting an unnecessary dot. Go compare to the link you've referenced.
Just use Notes or UserNotes
Sorry for my English. I am new in Android Development. I have an app in which the user make notes. When the user make his note, the note is saved in a SQ Lite Database and is shown in a ListView. When I want to delete the note, the note is removed from the ListView but not from the Database. Could you help me?
MainActivity.java
public class MainActivity extends Activity
{
private InputDbHelper mHelper;
private ListView mListView;
private EditText mEditText;
private Button mButton;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
mHelper = new InputDbHelper(this);
updateUI();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, input);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
}
public void deleteTask() {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<String>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (adapter== null) {
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
taskList);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(taskList);
adapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
You are not deleting the row in your database.You can do this
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
try something like:
db.execSQL("DELETE FROM myTable WHERE noteID = 7")
Or more generally:
`int idToDelete = 7; //for example
db.execSQL(
"DELETE FROM "+ InputContract.TaskEntry.TABLE +
" WHERE "+ InputContract.TaskEntry._ID +" = " + idToDelete
)`
I have created a list view. On button click the data is added in list and also stored in an SQLite database. I have also added the image on the right-hand side of list, on click of which a particular row data is deleted, but I also want to delete data from SQLite. How could I do this?
Main Activity.Java
public class MainActivity extends Activity {
EditText editText;
Button Button,Button1;
ListView listView;
ArrayList<String> listItems;
BaseAdapter adapter;
private DataBaseHandler mHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DataBaseHandler(this);
editText = (EditText) findViewById(R.id.editText);
Button = (Button) findViewById(R.id.Button);
listView = (ListView) findViewById(R.id.listview);
listItems = new ArrayList<String>();
adapter =new BaseAdapter()
{
#Override
public View getView(final int arg0, View arg1, ViewGroup arg2)
{
LayoutInflater inflater = getLayoutInflater();
arg1 = inflater.inflate(R.layout.custom, null);
TextView textview = (TextView)arg1. findViewById(R.id.textView1);
textview.setText(listItems.get(arg0));
ImageView image = (ImageView)arg1. findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
listItems.remove(arg0);
listView.setAdapter(adapter);
Toast.makeText(MainActivity.this, "Item has been successfully deleted", Toast.LENGTH_LONG)
.show();
}
});
return arg1;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public int getCount() {
//code to set the list item size according to array data size
return listItems.size();
}
};
listView.setAdapter(adapter);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
listItems= mHelper.addListItem(editText.getText().toString());
adapter.notifyDataSetChanged();
listView.setSelection(listView.getAdapter().getCount()-1);
editText.getText().clear();
}
});
}
}
DATABASE HANDLER.JAVA
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDatabase.db";
private static final String TABLE_LIST = "MyListItem";
private static final String KEY_ID = "id";
private static final String KEY_ListItem = "listitem";
public static final String KEY_NAME = null;
public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_LIST_TABLE = "CREATE TABLE " + TABLE_LIST + "(" + KEY_ID
+ " integer primary key autoincrement," + KEY_ListItem + " TEXT" + ")";
db.execSQL(CREATE_LIST_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);
onCreate(db);
}
ArrayList<String> addListItem(String listItem)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ListItem, listItem);
db.insert(TABLE_LIST, null, values);
ArrayList<String> items=new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LIST;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
items.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
db.close();
return items;
}
Cursor getListItem()
{
String selectQuery = "SELECT * FROM " + TABLE_LIST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
}
To delete single data entry(i.e. Row) make a method in database handler:
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + "=?",
new String[] { String.valueOf(id) }); // KEY_ID= id of row and third parameter is argument.
db.close();
}
This method will delete single row which ID is given.
You will need to make a method deleteItem in your DataBaseHandler class. Which will do something like,
db.delete(TABLE_LIST , KEY_ID + "=" + yourIdToBeDeleted, null);
And make a call to this method from your delete button/image's onClick as:
mHelper.deleteItem(idOfItemToBeDeleted);
Hope it helps.