Can anybody please have a look at my code and tell me where I am wrong? I don't get errors, unfortunately the row that is long pressed and new value is provided is not being updated unless I specify exact row number. I need to be able to update the row that is clicked. I tried everything and up to today I didn't manage to get any help. I am beginner in Android development.
Here is the code of MyDB:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" ,
new String[]{ Double.valueOf(rowId).toString() })>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the code with the dialog, where I should update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
private long rowId;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
long rowId = adapter.getItemId(position); //Will return the clicked item
saveItToDB(rowId);
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
// public void notifyDataSetChanged();
dismiss();
try {
saveItToDB(rowId);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB(long rowId) {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), rowId);
dba.close();
((TextView) editText).setText("");
}
}
And here is the Diary Adapter:
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
i found first problem at your DB class
update this method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
To
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, new String[]{Constants.TITLE_NAME ,Constants.CONTENT_NAME}, null,
null, null, null, null);
return c;
}
Related
I'm developing an application in Android Studio using this library: com.daimajia.swipelayout:library:1.2.0#aar. My app user a SQLite database with the following classes:
BDSQLiteHelper.java
public class BDSQLiteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ExtraOficial";
private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";
private static final String vazID = "VazID";
private static final String nomeServico = "nomeServico";
private static final String[] VAZ_COLUNAS = {vazID, nomeServico};
public BDSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
"vazID INTEGER PRIMARY KEY AUTOINCREMENT,"+
"nomeServico)";
db.execSQL(CREATE_VAZAMENTOTABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
this.onCreate(db);
}
public void addVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(nomeServico, VazamentosToSQL.getNomeServico());
db.insert(TABELA_VAZAMENTOS, null, values);
db.close();
}
public VazamentosToSQL getVazamentos (int vazID) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELA_VAZAMENTOS,
VAZ_COLUNAS,
" vazID = ?",
new String[] {String.valueOf(vazID)},
null,
null,
null,
null);
if (cursor == null) {
return null;
} else {
cursor.moveToFirst();
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
return VazamentosToSQL;
}
}
private VazamentosToSQL cursorTovazamentos(Cursor cursor) {
VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
VazamentosToSQL.setNomeServico(cursor.getString(1));
return VazamentosToSQL;
}
public ArrayList<VazamentosToSQL> getAllVazamentos() {
ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
listaVazamentos.add(VazamentosToSQL);
} while (cursor.moveToNext());
}
return listaVazamentos;
}
[...]
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS,
vazID+" =?",
new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
VazamentosToSQL.java
public class VazamentosToSQL {
private int vazID;
private String nomeServico;
public int getVazID() { return vazID; }
public void setVazID(int vazID) {
this.vazID = vazID;
}
public String getNomeServico() { return nomeServico; }
public void setNomeServico(String nomeServico) { this.nomeServico = nomeServico; }
}
ListViewActivity.java:
[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
[...]
bd = new BDSQLiteHelper(this);
lista = (ListView) findViewById(R.id.lvdenuncias);
listaVazamentos = bd.getAllVazamentos();
setListViewHeader();
setListViewAdapter();
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { //aqui é o vazamentosAdapter
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
startActivity(intent);
}
});
#Override
protected void onStart() {
super.onStart();
updateAdapter(); //Refresh ListView items
}
private void setListViewHeader() {
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview, lista, false);
totalClassmates = (TextView) header.findViewById(R.id.total);
swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
setSwipeViewFeatures();
//UNNECESSARY for me: lista.addHeaderView(header);
}
private void setSwipeViewFeatures() {
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
//add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));
swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
#Override
public void onClose(SwipeLayout layout) {
Log.i(TAG, "onClose");
}
#Override
public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
Log.i(TAG, "on swiping");
}
#Override
public void onStartOpen(SwipeLayout layout) {
Log.i(TAG, "on start open");
}
#Override
public void onOpen(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally show");
}
#Override
public void onStartClose(SwipeLayout layout) {
Log.i(TAG, "the BottomView totally close");
}
#Override
public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
//when user's hand released.
}
});
}
private void setListViewAdapter() {
adapter = new vazamentosAdapter(this, listaVazamentos);
lista.setAdapter(adapter);
}
public void updateAdapter() {
listaVazamentos.clear();
listaVazamentos.addAll(bd.getAllVazamentos());
adapter.notifyDataSetChanged(); //update adapter
lista.invalidateViews();
lista.refreshDrawableState();
}
}
vazamentosAdapter.java:
public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> {
private final Context context;
private final ArrayList<VazamentosToSQL> elementos;
File imgFile;
private Bitmap bitmap;
private ExifInterface exifObject;
private ExibeVazamentosActivity activity;
int vazID;
private SQLiteDatabase bd;
public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) {
super(context, R.layout.linha, elementos);
this.context = context;
this.elementos = elementos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.linha, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
}else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
[...]
editText.setText(elementos.get(position).getVaznomeServico());
holder.btnEdit.setOnClickListener(onEditListener(position, holder));
holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));
return convertView;
}
private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
/**--------------Tried it, not working =( ---------------*/
elementos.get(position).getVazID();
//listaVazamentos.remove(position);
//activity.listaVazamentos.remove(position);
//bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
//bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
//bd.close();
//elementos.remove(position);
Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
bd.deleteVazamentos(VazamentosToSQL);
holder.swipeLayout.close();
// activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
/**--------------Tried it, not working =( ---------------*/
}
};
}
private class ViewHolder {
private TextView name;
private View btnDelete;
private View btnEdit;
private SwipeLayout swipeLayout;
private ListView listv;
public ViewHolder(View v) {
swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
btnDelete = v.findViewById(R.id.delete);
btnEdit = v.findViewById(R.id.edit_query);
listv = (ListView) v.findViewById(R.id.lvdenuncias);
swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
}
}
The mentioned library is working great. But i'm trying to delete database row when user click in a button according to the listview selected line. With this code: elementos.get(position).getVazID() I get the database index. But I can't delete from database. Someone can help me with the code to delete row from database and line from listview?
Try changing this:
public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[] { String.valueOf(VazamentosToSQL.getVazID())});
db.close();
return i;
}
To this:
public void deleteVazamentos(int vazID) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null);
}
Then if you want to delete a row, you can call:
(Inside onDeleteListener)
bd.deleteVazamentos(elementos.get(position).getVazID());
Good Day Guys..Need some help here..i got troubled from deleting the selected row in my list view..i want to use an alert dialog for confirmation to delete the selected row..and to edit also..i am a beginner and i have tried searching for answers to this problem and also tried relating it to other problems but i still didn't get it...
My DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper implements Filterable{
// private static final String COLUMN_NAME="ageing_column";
private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ContractClass.NewInfo.TABLE_NAME+"("+ ContractClass.NewInfo.ITEM_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ContractClass.NewInfo.DESCRIPTION+" TEXT, "+
ContractClass.NewInfo.CATEGORY+" TEXT,"+ ContractClass.NewInfo.MONTHONE+" TEXT, "+ ContractClass.NewInfo.REMIND_AT+" TEXT, "+ ContractClass.NewInfo.QTY+" TEXT, "+
ContractClass.NewInfo.LOCATION+" TEXT );";
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context1=context;
Log.e("DATABASE OPERATIONS", "Database created / opened....");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created....");
}
public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(ContractClass.NewInfo.LOCATION,location);
contentValues.put(ContractClass.NewInfo.DESCRIPTION,description);
contentValues.put(ContractClass.NewInfo.CATEGORY,category);
contentValues.put(ContractClass.NewInfo.MONTHONE,monthOne);
contentValues.put(ContractClass.NewInfo.REMIND_AT,remind);
contentValues.put(ContractClass.NewInfo.QTY,quantity);
db.insert(ContractClass.NewInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
db.close();
}
public Cursor getInformations(SQLiteDatabase db)
{
Cursor cursor;
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
cursor=db.query(ContractClass.NewInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
{
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
String selection = ContractClass.NewInfo.LOCATION+" LIKE? ";
String [] sargs={location};
Cursor cursor=sqLiteDatabase.query(ContractClass.NewInfo.TABLE_NAME,projections,selection,sargs,null,null,null);
return cursor;
}
public String[] SelectAllData()
{
try
{
String arrData[]=null;
SQLiteDatabase db;
db=this.getReadableDatabase();
String strSQL=" SELECT "+ ContractClass.NewInfo.LOCATION+" FROM "+ ContractClass.NewInfo.TABLE_NAME;
Cursor cursor =db.rawQuery(strSQL,null);
if(cursor !=null)
{
if(cursor.moveToFirst())
{
arrData=new String[cursor.getCount()];
int i=0;
do
{
arrData[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
}
}
cursor.close();
return arrData;
}catch(Exception e){
return null;
}
}
public void delete_byID(int id){
sqLiteDatabase.delete(ContractClass.NewInfo.TABLE_NAME, ContractClass.NewInfo.ITEM_ID + "=" + id, null);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public Filter getFilter() {
return null;
}
}
THis is My MAin Class..
public class ViewListsActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
ListDataAdapter listDataAdapter;
ListView listView;
Cursor cursor;
EditText delete_txt;
String deletetxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_lists_activity);
listView = (ListView) findViewById(R.id.search_listView);
listDataAdapter = new
ListDataAdapter(getApplicationContext(),R.layout.row_layout);
databaseHelper = new DatabaseHelper(getApplicationContext());
databaseHelper = new DatabaseHelper(this);
delete_txt = (EditText) findViewById(R.id.delete_text);
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
listView.setAdapter(listDataAdapter);
if (cursor.moveToFirst()) {
do {
String description, category, month1,remind,qty,location;
description = cursor.getString(0);
category = cursor.getString(1);
month1 = cursor.getString(2);
qty=cursor.getString(3);
remind=cursor.getString(4);
location = cursor.getString(5);
DataProvider dataProvider = new DataProvider(description,
category, month1,qty,remind,location);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View
view, int position, long id) {
return false;
}
});
}
public void ToSearchBtn(View view)
{
Intent intent=new Intent(this,ThirdActivitySearchAllData.class);
startActivity(intent);
}
public void ToAddNewItemBtn(View view)
{
Intent intent=new Intent(this,SecondActivitySaveData.class);
startActivity(intent);
}
}
My List Adapter Class
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
}
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.row_layout,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
row.setTag(layoutHandler);
}else
{
layoutHandler=(LayoutHandler)row.getTag();
}
DataProvider dataProvider= (DataProvider) this.getItem(position);
layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
layoutHandler.CATEGORY.setText(dataProvider.getCategory());
layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
layoutHandler.REMIND.setText(dataProvider.getRemindAt());
layoutHandler.QTY.setText(dataProvider.getQuantity());
layoutHandler.LOCATION.setText(dataProvider.getLocation());
return row;
}
}
You can use ALERT DIALOG for showing confirmation popup, with YES/NO option both for delete and edit, and based on options selected in ALERT DIALOG you can perform further operations
In the below link you can find the sample code
How do I display an alert dialog on Android?
In every row of my ListView I have a checkbox with a listener. The Listener update databse row.
MyAdapter class is :
public class MyAdapter extends CursorAdapter {
Context b;
LayoutInflater inflater;
#SuppressWarnings("deprecation")
public MyAdapter(Context context, Cursor c) {
super(context, c);
inflater = LayoutInflater.from(context);
b= (Context) context;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
TextView tv1 = (TextView)view.findViewById(R.id.txt_name);
TextView tv2 = (TextView)view.findViewById(R.id.txt_numer);
tv1.setText(cursor.getString(2));
tv2.setText(cursor.getString(3));
final int pos = cursor.getPosition();
final CheckBox repeatChkBx = (CheckBox)view.findViewById(R.id.favorite_check);
String likes = cursor.getString(cursor.getColumnIndex("like"));
if (likes.equals("yes")) {
repeatChkBx.setChecked(true);
} else {
repeatChkBx.setChecked(false);
}
repeatChkBx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
MyDatabase mydatabase = new MyDatabase(b);
SQLiteDatabase mydb = mydatabase.getWritableDatabase();
cursor.moveToPosition(pos);
if (repeatChkBx.isChecked()) {
ContentValues cv = new ContentValues();
cv.put("like", "yes");
mydb.update("list", cv, "id ="+cursor.getString(1), null);
} else {
ContentValues cv = new ContentValues();
cv.put("like", "no");
mydb.update("list", cv, "id ="+cursor.getString(1), null);
}
mydb.close();
}
});
}
protected Context getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.item, parent, false);
}
}
I have this problem that moving the list I lost the checkbox state for row that disappear from screen.
like this pic :
check below code, I have made some changes in your code,... hope it will solve your problem
public class MyAdapter extends CursorAdapter {
Context b;
LayoutInflater inflater;
ArrayLis<Boolean> checkbox_arr = new ArrayLis<Boolean>();
#SuppressWarnings("deprecation")
public MyAdapter(Context context, Cursor c) {
super(context, c);
for(int i=0;i<c.getCount();i++){
checkbox_arr.add(false);
}
inflater = LayoutInflater.from(context);
b= (Context) context;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
TextView tv1 = (TextView)view.findViewById(R.id.txt_name);
TextView tv2 = (TextView)view.findViewById(R.id.txt_numer);
tv1.setText(cursor.getString(2));
tv2.setText(cursor.getString(3));
final int pos = cursor.getPosition();
final CheckBox repeatChkBx = (CheckBox)view.findViewById(R.id.favorite_check);
String likes = cursor.getString(cursor.getColumnIndex("like"));
if (likes.equals("yes")) {
checkbox_arr.set(pos,true);
} else {
checkbox_arr.set(pos,false);
}
repeatChkBx.setChecked(checkbox_arr.get(pos));
repeatChkBx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
MyDatabase mydatabase = new MyDatabase(b);
SQLiteDatabase mydb = mydatabase.getWritableDatabase();
cursor.moveToPosition(pos);
if (repeatChkBx.isChecked()) {
checkbox_arr.set(pos,false); //
ContentValues cv = new ContentValues();
cv.put("like", "no");
mydb.update("list", cv, "id ="+cursor.getString(1), null);
} else {
checkbox_arr.set(pos,true); //
ContentValues cv = new ContentValues();
cv.put("like", "yes"); //
mydb.update("list", cv, "id ="+cursor.getString(1), null);
}
repeatChkBx.setChecked(checkbox_arr.get(pos)); //
notifyDataSetChanged();
mydb.close();
}
});
}
protected Context getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.item, parent, false);
}
}
I put some code together to have functionality of updating my sql rows but it doesn't work. Can anyone have a look at my code please and let me know where I am wrong?
I can post alternative code if necessary. Here is my dialog file which is supposed to update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 1);
dba.close();
((TextView) editText).setText("");// TODO Auto-generated method stub
}
}
MyDB file:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
dba object is not initialized and your try/catch get the crash. Initialize it with
dba = new MyDB(context);
in your EditListItemDialog constructor (Uncomment it and remove List fragment_monday) like this:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
Replace your saveItToDB method with:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 1);
dba.close();
((TextView) editText).setText("")
}
dba.open() is missing.
After a long time I figured out that changing argument from 0 to different number allows me to update row with corresponding id to this number:
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
In above code I changed 0 to 2 and I was able to update content of row no 2. Here is full class code:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
dismiss();
try {
saveItToDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB() {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), 2);
dba.close();
((TextView) editText).setText("");
}
}
Now, what do I need to do in order to tell it that I want to update row that is clicked, not row number 2? Any help would be appreciated.
Here is MyDB code:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" + rowId, null)>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the Adapter:
public class Monday extends ListActivity {
private SQLiteDatabase db;
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Implement getItemId(int position) in your adapter. In your onListItemClick method, call this method with the given position.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long itemId = adapter.getItemId(position);
saveItToDB(itemId);
}
private void saveItToDB(long itemId) {
String text = editText.getText().toString();
editText.setText("");
dba.open();
dba.updateDiaryEntry(text, itemId);
dba.close();
}