The command : "DELETE FROM Table where ..." doesn't work - java

I cannot delete some data from my table in database.
I copy some SQLite code and paste it to my new project. It is quite simple.
I correct some code and it doesn't work.
I spend lots of time to solve this problem, but I couldn't make it.
Even no errors have occurred.
Except for the delete query, all other queries work pretty well.
This is based on android and java.
I tried to delete data by use these queries.
db.execSQL("DELETE FROM mca WHERE position=" + position + ";");
db.execSQL("DELETE FROM mca WHERE _id=" + id + ";");
db.execSQL("DELETE FROM mca WHERE member='" + member + "';");
I made _id, position and member have same value. So this codes make sense.
_id and position are INTEGER and member is TEXT.
This is MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
MyRecyclerViewAdapter adapter;
MemberData md;
#Override
protected void onCreate(Bundle savedInstanstState) {
super.onCreate(savedInstanstState);
setContentView(R.layout.activity_main);
final DBHelper dbHelper = new DBHelper(getApplicationContext(), "test_alarm.db", null, 1);
ArrayList<MemberData> member;
member = new ArrayList<>();
for (int i = 1; i < 5; i++) {
try {
md = new MemberData(member.get(member.size() - 1).position + 1, i + "");
}catch(Exception e){
Log.d("error", e+"");
md = new MemberData(1, i+"");
}
member.add(md);
dbHelper.insert(md);
}
/*************** activate delete command ***************/
dbHelper.delete(2);
/*******************************************************/
// set up the RecyclerView
recyclerView = findViewById(R.id.my_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, member, dbHelper);
recyclerView.setAdapter(adapter);
}
}
class MemberData {
public int position;
public String member;
public MemberData(int position, String member) {
this.member = member;
this.position = position;
}
}
This is the SQLite function
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE mca (_id INTEGER PRIMARY KEY AUTOINCREMENT, member TEXT, position INTEGER);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(MemberData md) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("INSERT INTO mca VALUES(null, '" + md.member + "', " + md.position + ");");
db.close();
}
public void delete(int position) {
SQLiteDatabase db = getWritableDatabase();
/********************* Delete query *******************/
db.execSQL("DELETE FROM mca WHERE position=" + position + ";");
/*******************************************************/
db.close();
}
public ArrayList<MemberData> getData() {
SQLiteDatabase db = getReadableDatabase();
ArrayList<MemberData> memberList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM mca", null);
while (cursor.moveToNext()) {
memberList.add(new MemberData(cursor.getInt(1), cursor.getString(2)));
}
return memberList;
}
}
This is the adapter for RecyclerView.
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private ArrayList<MemberData> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
private DBHelper db;
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
public ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// data is passed into the constructor
MyRecyclerViewAdapter(Context context, ArrayList<MemberData> data, DBHelper db) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.db = db;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.my_text_view, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String member = "member"+mData.get(position).member;
holder.myTextView.setText(member);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id).member;
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
I just want to remove a certain value from table

db.execSQL("DELETE FROM mca WHERE position='" + position + "'");
db.execSQL("DELETE FROM mca WHERE _id='" + id + "'");
db.execSQL("DELETE FROM mca WHERE member='" + member + "'");
try this
be careful on the "'" and ";"

Always use ' while using a variable in SQLite queries. also remove the ";"
Eg: you have used position so define it like,
db.execSQL("DELETE FROM mca WHERE position='" + position + "'");
db.execSQL("DELETE FROM mca WHERE _id='" + id + "'");
db.execSQL("DELETE FROM mca WHERE member='" + member + "'");

use db.delete it return's 0 for failure 1 for success
public int delete(String position) {
SQLiteDatabase db = getWritableDatabase();
return db.delete("mca","position = ?",new String[] {position});
db.close();
}

You should Change your sql code like below.
When you are using variable inside a sql query you need to bind the variable value and the sql query as a single string.
try the code below.
db.execSQL("DELETE FROM mca WHERE position='" + position + "';");
db.execSQL("DELETE FROM mca WHERE _id='" + id + "';");
db.execSQL("DELETE FROM mca WHERE member='" + member + "';");

Related

Android recyleview listing using with database not working

I am developing an app for listing details in database. The listing is not working. but it is showing in log as fine. Why my recyclerview listling is not working. when i am using bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()) it shows error.
My codes are shown below.
SpeedDialViewActivity.java
public class SpeedDialViewActivity extends AppCompatActivity {
private List<Bean> beanList = new ArrayList<>();
private RecyclerView recyclerView;
private ViewAdapter mAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_dial_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ViewAdapter(beanList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareData();
}
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "speeddial";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_SPEED_DIAL = "speed_dial_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_SPEED_DIAL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
void addContact(Bean bean) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, bean.getName()); // Contact Name
values.put(KEY_PH_NO, bean.getNumber()); // Contact Phone
values.put(KEY_PH_NO, bean.getSpeeddial()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
Bean getBean(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bean bean = new Bean(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return bean;
}
public List<Bean> getAllContacts() {
List<Bean> contactList = new ArrayList<Bean>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bean contact = new Bean();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
ViewAdapter.java
public class ViewAdapter extends RecyclerView.Adapter<ViewAdapter.MyViewHolder> {
private List<Bean> beanList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, number, speeddial_number;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
number = (TextView) view.findViewById(R.id.number);
speeddial_number = (TextView) view.findViewById(R.id.speeddialNumber);
}
}
public ViewAdapter(List<Bean> beanList){
this.beanList = beanList;
}
#Override
public ViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.speeddial_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewAdapter.MyViewHolder holder, int position) {
Bean bean = beanList.get(position);
holder.name.setText(bean.getName());
holder.number.setText(bean.getNumber());
holder.speeddial_number.setText(bean.getSpeeddial());
}
#Override
public int getItemCount() {
return beanList.size();
}
}
Bean.java
public class Bean{
private int id;
private String name;
private String number;
private String speeddial;
public Bean(int id, String name, String number, String speeddial) {
this.id=id;
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean(String name, String number, String speeddial) {
this.name=name;
this.number=number;
this.speeddial=speeddial;
}
public Bean() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getSpeeddial() {
return speeddial;
}
public void setSpeeddial(String speeddial) {
this.speeddial = speeddial;
}
}
The error is java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.appname/com.app.appname}: java.util.ConcurrentModificationException
Please help me
You are not adding the contacts you are fetching in the list and not doing notify data set changed. Change your onPrepare() method as follows
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
this.beanList.addAll(beanList);
mAdapter.notifyDatasetChanged();
}
pass the same list in prepareData(beanList) and add items in this list. And change your method to something likeprepareData(List<Bean> beanList>).after successfully adding, simply call mAdapter.notifyDataSetChanged() method so your adapter could know that some items have been added into the list.
You have not mention android:name in application tag in manifest file.
So you simple use context object or use SpeedDialViewActivity.this
DatabaseHandler handler = new DatabaseHandler(mContext);
or
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
private void prepareData() {
DatabaseHandler handler = new DatabaseHandler(SpeedDialViewActivity.this);
Log.d("Reading: ", "Reading all contacts..");
List<Bean> beanList = handler.getAllContacts();
//Cursor cursor = (Cursor) handler.getAllContacts();
//Bean bean1;
for (Bean cn : beanList) {
String log = "Id: " + cn.getId() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
// bean1 = new Bean(cn.getName(), cn.getNumber(), cn.getSpeeddial()); // Error occurring
// beanList.add(bean1);
}
}

How to send the Clicked Item Latitude to javascript from MainActivity.java

Here is my MainActivity.java
public class MainActivity extends AppCompatActivity{
CountriesDbAdapter myDB = new CountriesDbAdapter(this);
ListView listView;
public String lat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB.open();
myDB.deleteBank();
myDB.insertBank();
listView = (ListView) findViewById(R.id.listView);
toggleView();
WebView webView = (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "android");
webView.requestFocusFromTouch();
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/www/bank.html");
}
public void toggleView() {
final Cursor cursor = myDB.fetchBank();
final String[] arr = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
String data = cursor.getString(cursor.getColumnIndex("banks"));
arr[i] = data;
i++;
} while (cursor.moveToNext());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, arr);
listView.setAdapter(adapter);
final StringBuffer buffer = new StringBuffer();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this, arr[position], Toast.LENGTH_SHORT).show();
Cursor res = myDB.answerRequest(arr[position]);
if (res.moveToFirst()) {
do {
lat=res.getString(2);
//buffer.append("lat: " + lat + "\n");
// buffer.append("long: " + res.getString(3) + "\n\n");
// showMessage("Data", buffer.toString());
//showMessage();
} while (res.moveToNext());
}
}
});
}
class WebViewJavaScriptInterface {
private Activity activity;
public WebViewJavaScriptInterface(Activity activity) {
this.activity = activity;
}
#JavascriptInterface
public String getData() {
//From Here how can i Return my Updated latitude to javascript file
}
}
CountriesDbAdapter.java
package com.example.student.finalone;
public class CountriesDbAdapter {
public static final String COLUMN_BANK = "banks";
public static final String COLUMN_BANKL = "banksl";
public static final String COLUMN_BANKLG = "bankslg";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "Vijayawada";
private static final String BANK_TABLE = "Bank";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_BANK = "CREATE TABLE if not exists " + BANK_TABLE + " (" + KEY_ROWID + " integer PRIMARY KEY autoincrement," + COLUMN_BANK + "," + COLUMN_BANKL + "," + COLUMN_BANKLG + ");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_BANK);
db.execSQL(DATABASE_BANK);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + BANK_TABLE);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long createBank(String b, double blat,double blong) {
ContentValues initialValues = new ContentValues();initialValues.put(COLUMN_BANK, b);initialValues.put(COLUMN_BANKL, blat);initialValues.put(COLUMN_BANKLG, blong);
return mDb.insert(BANK_TABLE, null, initialValues);
}
public boolean deleteBank() {
int doneDelete = 0;
doneDelete = mDb.delete(BANK_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertBank()
{
createBank("ServicebranchSBI",16.5109,80.651);createBank("StateBankofIndia",16.5011,80.6559);createBank("StateBankOfHyderabad",16.4966,80.6569);
createBank("BankOfBaroda",16.4974,80.6546);createBank("AndhraBank",16.5028,80.6396);createBank("AndhraBank",16.5062,80.648);
}
public Cursor fetchBank() {
String SelectQuery="select * from "+BANK_TABLE;
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor answerRequest(String position) {
String SelectQuery= "SELECT * FROM " + BANK_TABLE + " WHERE " + COLUMN_BANK + "='" + position + "'";
Cursor mCursor = mDb.rawQuery(SelectQuery,null);
// String result="";
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
index.html
<html>
<head>
<script>
var showData = function() {
var data = android.getData();
window.alert("Hello! Data are: " + data + "; first = " + data);
}
</script>
</head>
<body>
<p>Lorem ipsem dolor et ceteris.</p>
<input type="button" value="Display data" onclick="showData()">
</body>
</html>
Iam trying to access the database from MainActivity.java and push it to the html file, Whenever i click on the html button it shows 0's in some cases iam getting error near the double lat declaration
You can achieve it in two ways:
1. Implement the Activity from OnItemClickListener and override onItemClick parallel to onCreate. Define double array a class variable and update that inside onItemClick
public class MainActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
}
2.Create a class MyItemClickListener and implement it from OnItemClickListener. Define double array a class variable
class MyItemClickListener implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Your code here
//Update the class member a1dToJson(lat).toString();//Here it returns all 0's
}
}
Change setOnItemClickListener to:
listView.setOnItemClickListener(new MyItemClickListener());

Display Data from SQL in custom ListView via SimpleCursorAdapter

i created a SQL Database and was able to safe data from three EditText Views and display it in a single TextView.
Then i thought it would be way better to display the data in a custom ListView, so i followed the developer guide and tried to display the data by a simpleCursorAdapter. But it did not work...i do not get any errors or anything, the data is just not shown...I guess there must be some missing connection between the Cursor, the Adapter or the DB...
i know that this kind of question is asked quite frequently, but i am unable to find my mistake, any help would be greatly appreciated:
MyDBHandlerFaecher.java:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
//Delete the line in which the COLUMN_NAME is equal to the input
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
FaecherActivity.java
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(), et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
//delete fach from database
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = new String[]{"_faechername", "_faecherraum", "_faecherfarbe"};
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = getContentResolver().query(Uri.parse(MyDBHandlerFaecher.TABLE_FAECHER),null, null, null, null);
SimpleCursorAdapter fachadapter = new SimpleCursorAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
}
}
i found code that works for me: i found out that the cursor in my DBHandler class was not empty, but it was empty in my FaecherActivity...so i created a custom SimpleCursorAdapter, and modified my code this way:
FaecherActivity:
public class FaecherActivity extends AppCompatActivity{
EditText et_facheintrag;
EditText et_raumeintrag;
EditText et_farbeintrag;
ListView lv_faecher;
MyDBHandlerFaecher dbHandlerFaecher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faecher);
et_facheintrag = (EditText) findViewById(R.id.et_facheintrag);
et_raumeintrag = (EditText) findViewById(R.id.et_raumeintrag);
et_farbeintrag = (EditText) findViewById(R.id.et_farbeintrag);
lv_faecher = (ListView) findViewById(R.id.lv_faecher);
dbHandlerFaecher = new MyDBHandlerFaecher(this, null, null, 1);
printDatabase();
}
//Add fach to database
public void addButtonClicked(View view){
Faecher fach = new Faecher(et_facheintrag.getText().toString(), et_raumeintrag.getText().toString(),
et_farbeintrag.getText().toString());
dbHandlerFaecher.addFach(fach);
printDatabase();
}
public void deleteButtonClicked(View view){
String inputText = et_facheintrag.getText().toString();
dbHandlerFaecher.deleteFach(inputText);
printDatabase();
}
public void printDatabase(){
String[] fromColumns = dbHandlerFaecher.databaseToStringArray();
int[] toViews = new int[]{R.id.facheintrag, R.id.raumeintrag, R.id.farbeintrag};
Cursor cursor;
cursor = dbHandlerFaecher.getWritableDatabase().rawQuery(" SELECT * FROM " + MyDBHandlerFaecher.TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist2");
}
else {
Log.d("Event", "Records do not exist2");
}
SimpleCursorAdapter fachadapter = new FaecherRowAdapter(this, R.layout.faecher_row, cursor, fromColumns,toViews, 0);
lv_faecher.setAdapter(fachadapter);
MyDBHandlerFaecher:
public class MyDBHandlerFaecher extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "faecher.db";
public static final String TABLE_FAECHER = "Faechertable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "_faechername";
public static final String COLUMN_RAUM = "_faecherraum";
public static final String COLUMN_COLOR = "_faecherfarbe";
public MyDBHandlerFaecher(FaecherActivity context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
//Create the table
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_FAECHER + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_RAUM + " TEXT, " +
COLUMN_COLOR + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAECHER);
onCreate(db);
}
//Add a new row to the DB
public void addFach(Faecher fach){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, fach.get_faechername());
values.put(COLUMN_RAUM, fach.get_faecherraum());
values.put(COLUMN_COLOR, fach.get_faecherfarbe());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FAECHER, null, values);
db.close();
}
//Delete row from DB
public void deleteFach(String name){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_FAECHER + " WHERE " + COLUMN_NAME + "=" + "\"" + name + "\"" + ";");
}
public String[] databaseToStringArray() {
String[] fromColumns = new String[]{COLUMN_NAME, COLUMN_RAUM, COLUMN_COLOR};
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(" SELECT * FROM " + TABLE_FAECHER + " WHERE 1 ", null);
//check if cursor is empty or not
if (cursor != null && cursor.getCount()>0) {
Log.d("Event", "Records do exist");
}
else {
Log.d("Event", "Records do not exist");
}
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
cursor.moveToNext();
}
db.close();
return fromColumns;
}
}
FaecherRowAdapter:
public class FaecherRowAdapter extends SimpleCursorAdapter {
private int layout;
private Context context;
public FaecherRowAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
this.context = context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.faecher_row, parent, false);
bindView(v, context, c);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int fachNameColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_NAME);
int fachRaumColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_RAUM);
int fachFarbeColumn = c.getColumnIndex(MyDBHandlerFaecher.COLUMN_COLOR);
String fachName = c.getString(fachNameColumn);
String fachRaum = c.getString(fachRaumColumn);
String fachFarbe = c.getString(fachFarbeColumn);
//set the name of the entry
TextView facheintrag = (TextView) v.findViewById(R.id.facheintrag);
if (facheintrag != null){
facheintrag.setText(fachName);
}
TextView raumeintrag = (TextView) v.findViewById(R.id.raumeintrag);
if (raumeintrag != null){
raumeintrag.setText(fachRaum);
}
TextView farbeintrag = (TextView) v.findViewById(R.id.farbeintrag);
if (farbeintrag != null){
farbeintrag.setText(fachFarbe);
}
}
}

How to delete items from a database

I am making an app that stores a name and a mark in a database and it displays this in a listview. How can I delete an item of the listview and also of the database with a long press of the item in the listview??
Here is the code of the database helper:
public class PersonDatabaseHelper {
private static final String TAG = PersonDatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
public static String query;
// table configuration
private static final String TABLE_NAME = "person_table"; // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";
private static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
PERSON_TABLE_COLUMN_NAME + " TEXT, " + PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
public void average() {
String query = "SELECT AVG("+PERSON_TABLE_COLUMN_PIN +") FROM "+TABLE_NAME;
database.rawQuery(query, null);
}
}
Well, since you have a unique ID associated with each entry in your database, you could delete based on that, like so:
public void deleteItem(int itemId){
this.getWritableDatabase().delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + itemId, null);
}
Then, when an item in your ListView is long-pressed, you could call that method to remove it from your database, and then call remove(Object) on your Adapter (or remove(int) on the List your Adapter uses), followed by notifyDataSetChanged() to ensure it updates the display correctly.
Edit: To answer your question about how to apply a long click listener to an item in your ListView, it depends on how you've implemented the Adapter. If it's's a custom adapter, you can simply set an onLongClickListener() to your root View (e.g. convertView). If you're not using that, you can try attaching an AdapterView.OnItemLongClickListener like this to your ListView:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long arg3) {
// get the data from your list at position, i.e. data.get(position)
// then pass that object / id to your database helper, e.g.
Person p = data.get(position);
personDatabaseHelper.deleteItem(p.getId());
data.remove(position); // or adapter.remove(p), depends on your implementation
adapter.notifyDataSetChanged(); // remove the object from your Adapter and notify it of the change
return true;
}
});
Edit 2: Using a custom Adapter
In your getView() method, add the following before returning convertView:
public View getView(final int position, View convertView, ViewGroup parent){
// your other stuff here
convertView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Person p = getItem(position);
personDatabaseHelper.deleteItem(p.getId());
remove(p);
notifyDataSetChanged();
return true;
}
});
return convertView;
}

Deleting row from sql database

The delete method of my sql database doesn't remove the entry from the database. It gives a null pointer exception:
10-18 00:44:25.069: E/AndroidRuntime(17968): java.lang.NullPointerException
10-18 00:44:25.069: E/AndroidRuntime(17968): at com.weather.app.LocationDB.deleteLocation(LocationDB.java:98)
public class LocationDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "locationManager";
private static final String TABLE_LOCATIONS = "locations";
private static final String KEY_ID = "id";
private static final String KEY_LOCATION = "location";
private static final String KEY_COUNTRY = "country";
private SQLiteDatabase db;
public LocationDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_LOCATIONS + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCATION
+ " TEXT, " + KEY_COUNTRY
+ " TEXT, " + " INTEGER)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void addLocation(LocationName location) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LOCATION, location.getTaskName());
values.put(KEY_COUNTRY, location.getTaskCountry());
db.insert(TABLE_LOCATIONS, null, values);
}
public List<LocationName> getAllLocations() {
List<LocationName> locList = new ArrayList<LocationName>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LOCATIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
LocationName task = new LocationName();
task.setId(cursor.getInt(0));
task.setTaskName(cursor.getString(1));
task.setTaskCountry(cursor.getString(2));
// Adding contact to list
locList.add(task);
} while (cursor.moveToNext());
}
return locList;
}
public boolean deleteLocation(long rowId) {
return db.delete(TABLE_LOCATIONS, KEY_ID + "=" + rowId, null) > 0;
}
}
Then entry is not removed even when the app is restarted, the addLocation method for adding a row works fine.
LocationSettings Activity:
public class LocationSettings extends Activity {
protected static LocationDB db;
static List<LocationName> list;
MyAdapter adapt;
private static TextView name;
private ListView listView;
private static final int DLG_EXAMPLE1 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_settings);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
db = new LocationDB(this);
list = db.getAllTasks();
adapt = new MyAdapter(this, R.layout.drawer_list_item, list);
listView = (ListView) findViewById(R.id.left_drawer);
listView.setAdapter(adapt);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
db.deleteTask(position);
adapt.remove(adapt.getItem(position));
}
}
});
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setOnTouchListener(touchListener);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
db.deleteTask(position);
adapt.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<LocationName> {
Context context;
List<LocationName> taskList = new ArrayList<LocationName>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId,
List<LocationName> objects) {
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.taskList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.drawer_list_item,parent, false);
name = (TextView) convertView.findViewById(R.id.text1);
}
LocationName current = taskList.get(position);
name.setText(current.getTaskName());
return convertView;
}
}
}
you forget to initialize db before calling delete method in deleteLocation.
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
Using the suggested following fragment of code from #ρяσѕρєяK:
public int deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) });
}
has changed the signature of your method generating that error. I think that
public boolean deleteLocation(long rowId) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_LOCATIONS, KEY_ID + " = ?",
new String[] { String.valueOf(rowId) }) > 0;
}
will solve your problem.

Categories