SQLiteException: unknown database - java

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

Related

How Can I delete item on my SQliteOpenhelper [duplicate]

This question already has answers here:
How to delete items from sqlite database with SQLiteOpenHelper class
(2 answers)
Closed 2 years ago.
I save my recyclerview with SQliteopenhelper . I can add item with edittext varibles . I use Itemtouchhelper for swip to delete item . How can ı delete item on SQliteopenhelper . Can you be fast
todoactivity.java
public class todoactivity extends AppCompatActivity {
TextView title;
Button back;
ImageButton gorevo;
RecyclerView recyclerView;
List<String>Listsx = new ArrayList<>();
TodoActivityAdpter adapterx;
DatabaseHelper4 myDBxxx;
TextView textView;
CheckBox checkBox;
long id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todoactivity);
recyclerView=findViewById(R.id.recyclerviewxx);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapterx=new TodoActivityAdpter(Listsx);
recyclerView.setAdapter(adapterx);
title=findViewById(R.id.titlex);
textView=findViewById(R.id.text_viewx);
gorevo = findViewById(R.id.gorevo);
myDBxxx = new DatabaseHelper4(this);
Cursor datax = myDBxxx.getListContents();
if(datax.getCount() == 0){
}else{
while(datax.moveToNext()){
Listsx.add(datax.getString(1));
ListAdapter listAdapterx = new ArrayAdapter<>(this,R.layout.todoactivity_item,R.id.textitem,Listsx);
adapterx.notifyItemInserted(Listsx.size()-1);
}
}
gorevo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(todoactivity.this);
bottomSheetDialog.setContentView(R.layout.bottomsheetlayout3);
bottomSheetDialog.show();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
EditText editText = bottomSheetDialog.findViewById(R.id.editx);
Button ekle = bottomSheetDialog.findViewById(R.id.ekle);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editText.getText().toString();
Listsx.add(text);
AddDataxxx(text);
adapterx.notifyItemInserted(Listsx.size()-1);
bottomSheetDialog.hide();
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
}
});
}
});
back=findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(todoactivity.this, pomodoroscreen.class);
startActivity(i);
overridePendingTransition(0,0);
}
});
ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
int positionx = viewHolder.getAdapterPosition();
Listsx.remove(positionx);
adapterx.notifyItemRemoved(positionx);
int id = recyclerView.getChildAt(positionx).getId();
myDBxxx.deleteItem(id);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public void AddDataxxx(String newEntry) {
boolean insertDatax = myDBxxx.addDataxxx(newEntry);
}
}
DatabaseHelper.java
public class DatabaseHelper4 extends SQLiteOpenHelper {
public static final String DATABASE_NAME4 = "mylistxxx.db";
public static final String TABLE_NAME4 = "mylist_dataxxx";
public static final String COL14 = "iDxxx";
public static final String COL24 = "ITEM1xxx";
public DatabaseHelper4(Context context) {
super(context, DATABASE_NAME4, null, 1);
}
#Override
public void onCreate(SQLiteDatabase dbxxx) {
String createTable = "CREATE TABLE " + TABLE_NAME4 + " (iDxxx INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1xxx TEXT)";
dbxxx.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase dbxxx, int oldVersion, int newVersion) {
dbxxx.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME4);
onCreate(dbxxx);
}
public boolean addDataxxx(String textt) {
SQLiteDatabase dbxxx = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL24, textt);
long result = dbxxx.insert(TABLE_NAME4, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase dbxxx = this.getWritableDatabase();
Cursor dataxxx = dbxxx.rawQuery("SELECT * FROM " + TABLE_NAME4, null);
return dataxxx;
}
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " = " +
iDxxx);
}
}
Adapter.java
public class TodoActivityAdpter extends RecyclerView.Adapter<TodoActivityAdpter.Holder> {
List<String>Listsx;
public TodoActivityAdpter(List<String>itemxxx){
this.Listsx = itemxxx;
}
#NonNull
#Override
public TodoActivityAdpter.Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todoactivity_item,parent,false);
Holder holder = new Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull TodoActivityAdpter.Holder holder, int position) {
holder.textView.setText(Listsx.get(position));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.checkBox.isChecked()) {
holder.textView.setTextColor(view.getResources().getColor(R.color.grey));
} else {
holder.textView.setTextColor(view.getResources().getColor(R.color.Color_black));
}
}
});
}
#Override
public int getItemCount() {
return Listsx.size();
}
public class Holder extends RecyclerView.ViewHolder {
CheckBox checkBox;
TextView textView;
List<String>Listsx;
RecyclerView recyclerView;
Context mContext;
public Holder(View view) {
super(view);
textView=view.findViewById(R.id.text_viewx);
checkBox=view.findViewById(R.id.checkbox);
recyclerView=view.findViewById(R.id.recyclerviewxx);
}
}
}
Thats my java classes . My activity is todoactivity . My SQliteopenhelper is DatabaseHelper.java . My Adapter is adapter.java . I can delete item on my recyclerview but ı cant delete item on my database
You can easily delete item from your table by just below code.
//Add method in your database class.
public void deleteItem(int iDxxx) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME4 + " WHERE " + COL14 + " =
" + iDxxx);
}
and Just Call this method from where you are deleting item.

SQLite in Android - How to refresh the list

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

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