package com.company.app;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.widget.*;
public class DBManager
{
private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;
// Constructor
public DBManager(Context c){
context = c;
}
public DBManager open() throws SQLException{
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
public void insert(String name, String desc){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
public Cursor fetch(){
String[] columns = new String[] {DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + "=" + _id, null);
return i;
}
public void delete(long _id){
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
I have problem when programming the functions of delete() and update(). I found lots of material to see whether will they solve the problem.
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if(id == R.id.delete_record){
dbManager.delete(_id);
this.returnHome();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed(){
titleText = findViewById(R.id.subject_edittext);
descText = findViewById(R.id.description_edittext);
String title = titleText.getText().toString();
String desc = descText.getText().toString();
dbManager.update(_id, title, desc);
this.returnHome();
}
private void returnHome()
{
Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
the this.returnHome()
is working, thus I ensure that the problem is came from the DBManager.
Problem: delete() and update() do not work.
thanks.