updating sql row with new data - android

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.

Related

how to display a blob image stocked in db browser in a listview in android

I am currently working on showing informations from my database (sqllite database in db browser) in a list view in android.
I copied the database in assets folder, retrieving textual informations from the database and showing it in the list view works all fine, but I don't know how to show the images.
This is my database question: how to set the images (blob in the sqllite database) in the image view which is in the item of list view ?
this is the code of the databasehelper :
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "fairytales.sqlite";
public static final String DBLOCATION = "/data/data/login.dell.com.affichage/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
String dbPath = mContext.getDatabasePath(DBNAME).getPath();
if(mDatabase != null && mDatabase.isOpen()) {
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if(mDatabase!=null) {
mDatabase.close();
}
}
public List<Histoire> getListHistoire() {
Histoire histoire = null;
List<Histoire> histoirelist = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM histoire", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
histoire = new Histoire(cursor.getInt(0), cursor.getInt(1),
cursor.getString(2), cursor.getString(3), cursor.getBlob(4));
byte [] photo=cursor.getBlob(4);
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap image= BitmapFactory.decodeStream(imageStream);
histoirelist.add(histoire);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return histoirelist;
}
}
this is my list adapter :
public class ListHistoireAdapter extends BaseAdapter {
private Context mContext;
private List<Histoire> mHistoireList;
public ListHistoireAdapter(Context mContext, List<Histoire> mHistoireList) {
this.mContext = mContext;
this.mHistoireList = mHistoireList;
}
#Override
public int getCount() {
return mHistoireList.size();
}
#Override
public Object getItem(int position) {
return mHistoireList.get(position);
}
#Override
public long getItemId(int position) {
return mHistoireList.get(position).getIdHistoire();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.activity_item_histoire, null);
TextView tvtitre = (TextView)v.findViewById(R.id.txtTitle);
TextView tvauteur = (TextView)v.findViewById(R.id.txtAuteur);
TextView tvnb = (TextView)v.findViewById(R.id.txtnb);
ImageView tvimg=(ImageView)v.findViewById(R.id.imgIcon);
tvtitre.setText(mHistoireList.get(position).getTitre());
tvauteur.setText(mHistoireList.get(position).getAuteur());
tvnb.setText(String.valueOf(mHistoireList.get(position).getNombredepages()));
// how to set the image in the list view !!
return v;
}
}
my main activity :
public class MainActivity extends Activity {
private ListView lvHisoire;
private ListHistoireAdapter adapter;
private List<Histoire> mHistoireList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvHisoire = (ListView)findViewById(R.id.listview_histoire);
mDBHelper = new DatabaseHelper(this);
lvHisoire.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent( MainActivity.this,Splash.class);
Histoire histoire = (Histoire)mHistoireList.get(position);
i.putExtra("ID",histoire.getIdHistoire());
startActivity(i);
}
});
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.DBNAME);
if(false == database.exists()) {
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)) {
Toast.makeText(this, "Copy database succes", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get lignes list in db when db exists
mHistoireList = mDBHelper.getListHistoire();
//Init adapter
adapter = new ListHistoireAdapter(this, mHistoireList);
//Set adapter for listview
lvHisoire.setAdapter(adapter);
}

SQLite filtering and searching data

Hello I have SQLite application based on SQLite database and I want it to have search/filter option. When i tried to use
adapter.getFilter().filter(query)
It filtered, but after filtering once,i can't do any more actions(add or delete items). Maybe someone have ideas how can I make search ?
DBAdapter.java
static final String ROW_ID ="id";
static final String NAME ="name";
static final String TAG = "DBAdapter";
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context ctx) {
this.c = ctx;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DBAdapter","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
public DBAdapter openDB()
{
try {
db=helper.getWritableDatabase();
} catch (SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
public void close()
{
helper.close();
}
public long add(String name)
{
try {
ContentValues cv = new ContentValues();
cv.put(NAME,name);
return db.insert(TBNAME,ROW_ID,cv);
} catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames()
{
String[] columns={ROW_ID,NAME};
return db.query(TBNAME,columns,null,null,null,null,null);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
EditText nameTxt;
Button savebtn,retrievebtn;
ArrayList<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt=(EditText)findViewById(R.id.editText);
savebtn=(Button)findViewById(R.id.saveBtn);
retrievebtn=(Button)findViewById(R.id.retrieveBtn);
lv = (ListView)findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item,books);
final DBAdapter db = new DBAdapter(this);
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.openDB();
long result = db.add(nameTxt.getText().toString());
if(result > 0)
{
nameTxt.setText("");
}else
{
Toast.makeText(getApplicationContext(),"Failure", Toast.LENGTH_SHORT).show();
}
db.close();
}
});
retrievebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
books.clear();
db.openDB();
Cursor c = db.getAllNames();
while (c.moveToNext())
{
String colIndex = c.getString(1);
books.add(colIndex);
}
lv.setAdapter(adapter);
db.close();
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),books.get(position), Toast.LENGTH_SHORT).show();
}
});
}

using loader to automatically update listview when a change happens to a database table

in my Application i have an Activity that has a ListView and a button. i am using loader to automatically loading data to listview from my table in the database.and i am using the button to change the table rows.
i want the loader to automatically load the data from table when a change happens to the table.
right now my code loads the data into listview but it doesn't update it when table changes after that.
here are my classes :
item
public class Item {
public int id;
public String name;
}
MainActivity :
public class MainActivity extends Activity implements
LoaderManager.LoaderCallbacks<List<Item>> {
ItemAdapter adapter;
List<Item> items;
Button button;
TextView tv;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
button = (Button) findViewById(R.id.button);
listview = (ListView) findViewById(R.id.listview);
items = new ArrayList<Item>();
adapter = new ItemAdapter(this, items);
listview.setAdapter(adapter);
getLoaderManager().initLoader(0, savedInstanceState, this).forceLoad();
}
//button code for changing db
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
}
#Override
public Loader<List<Item>> onCreateLoader(int id, Bundle args) {
final ItemHelper helper = new ItemHelper(getApplicationContext());
return new AsyncTaskLoader<List<Item>>(MainActivity.this) {
#Override
public List<Item> loadInBackground() {
return helper.read();
}
};
}
#Override
public void onLoadFinished(Loader<List<Item>> loader, List<Item> data) {
adapter.addAll(data);
adapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader<List<Item>> loader) {
adapter.clear();
adapter.notifyDataSetChanged();
}
ItemHelper
public class ItemHelper {
public static final String DB_NAME = "Test";
private static Context m_context;
private static SQLiteDatabase m_db;
private static DatabaseHelper m_helper;
String[] columns = { "id", "name" };
public ItemHelper(Context context) {
m_context = context;
m_helper = new DatabaseHelper(m_context, DB_NAME, null, 1);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public void insert(Item item) {
m_db = m_helper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", item.name);
m_db.insert("item", null, initialValues);
m_db.close();
}
public List<Item> read() {
List<Item> items = new ArrayList<Item>();
m_db = m_helper.getReadableDatabase();
Cursor cursor = m_db.query("item", columns, null, null, null, null,
null);
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
item.name = cursor.getString(cursor
.getColumnIndexOrThrow("name"));
items.add(item);
} while (cursor.moveToNext());
}
m_db.close();
return items;
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
private Context context;
private List<Item> items;
private LayoutInflater vi;
public ItemAdapter(Context context, int resource) {
super(context, resource);
// TODO Auto-generated constructor stub
}
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Item item = items.get(position);
if (item != null) {
view = vi.inflate(R.layout.item_info, parent, false); // custom xml
// for
// desired
// view
TextView tv1 = (TextView) view.findViewById(R.id.tvID);
tv1.setText(""+item.id);
TextView tv2 = (TextView) view.findViewById(R.id.tvName);
tv2.setText(item.name);
}
return view;
}
#Override
public Item getItem(int position) {
return items.get(position);
}
}
how can i do it ? ( i don't want to use content providers )
finally i used ContentProviders to solve this issue.
i created a method inside my database helper class that returns a Cursor according to it's parameters,
and used it inside ContentProvider to get Data.
public Cursor getCursor(int status, boolean isAccepted) {
m_db = m_helper.getReadableDatabase();
String sql = "SELECT id as _id , rid , isaccepted , status FROM torder";
Cursor cursor = m_db.rawQuery(sql, null);
return cursor;
}
also in helper when i insert data to db i notify the content provider :
public void notifyProvider(int status) {
ContentValues values = new ContentValues();
values.put("status", status);
Uri uri = m_context.getContentResolver().insert(
OrderProvider.CONTENT_URI, values);
}
public void insert(Order order) {
int flag = (order.isAccepted()) ? 1 : 0;
String[] args = { String.valueOf(order.getId()),
String.valueOf(order.getR_id()), String.valueOf(flag),
String.valueOf(order.getStatus()) };
m_db.execSQL(
"INSERT OR REPLACE INTO torder(id,rid,isaccepted,status) VALUES(?,?,?,?)",
args);
// save to orderdetails
List<OrderDetails> orderDetailsList = order.getOrders();
OrderDetailsHelper helper = OrderDetailsHelper.getInstance(m_context);
helper.open();
helper.insertAll(orderDetailsList);
helper.close();
notifyProvider(1);
}
Change your change method:
public void change(View view) {
ItemHelper helper = new ItemHelper(this);
Item item = new Item();
item.name = "Samsung P6800";
helper.insert(item);
getLoaderManager().restartLoader(0, null, this);
}

Updating SQL row with OnItemLongClick doesn't work

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

How to update row that is clicked?

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

Categories

Resources