SQLite in Android - How to refresh the list - java

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

Related

Delete selected item from listview and sqlite Android

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

SQLiteException: unknown database

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

Data deleted from an SQLite Database appear again

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.

How do I delete an item from an SQ Lite Database in Android?

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
)`

How to pass value from listview to the next activity

I'm new to android studios and am currently about to finish up on my first project. However, I'm stuck at the part where I have to pass the value selected from the listview to the next activity. I have tried researching on the codes but none seem to be able to work. Any help would be greatly appreciated.
DisplayProduct.java
public class DisplayProduct extends AppCompatActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseHelper databaseHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_product);
listView = (ListView)findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.display_product_row);
listView.setAdapter(listDataAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Object data = parent.getItemAtPosition(position);
//String value = data.toString();
}
});
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
if(cursor.moveToFirst())
{
do {
String contact,location,issue;
contact = cursor.getString(0);
location = cursor.getString(1);
issue = cursor.getString(2);
Information information = new Information(contact,location,issue);
listDataAdapter.add(information);
} while (cursor.moveToNext());
}
}
}
ListDataAdapter.java
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView Contact,Location,Issue;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.display_product_row, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.Contact = (TextView) row.findViewById(R.id.textView8);
layoutHandler.Location = (TextView) row.findViewById(R.id.textView18);
layoutHandler.Issue = (TextView) row.findViewById(R.id.textView90);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
Information information = (Information) this.getItem(position);
layoutHandler.Contact.setText(information.getContact());
layoutHandler.Location.setText(information.getLocation());
layoutHandler.Issue.setText(information.getIssue());
return row;
}
}
LocationDetail.java
public class LocationDetail extends AppCompatActivity {
private TextView Textv;
DatabaseHelper databaseHelper;
SQLiteDatabase sqlitedatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_detail);
}
#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_location_detail, 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);
}
}
From DisplayProduct.java :
Intent intent = new Intent(this, LocationDetail.class);
Object data = parent.getItemAtPosition(position);
String message = data.toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
From LocationDetail.java:
Intent intent = getIntent();
String value = intent.getStringExtra(EXTRA_MESSAGE);

Categories