Passing data in from list to detail view in Android - android

I have a list view populated threw an SQlitedatabase but I need to pass to a detail activity from the list view. The problem is in passing the details from the listview activity to the detail activity because when I click the detail activity it gives me blank edit texts
Here is my listview activity:
public class consulter_note extends Activity implements AdapterView.OnItemClickListener{
ListView list;
SQLiteDatabase sqLiteDatabase;
DataBaseOperationstwo dataBaseOperationstwo;
Cursor cursor;
ListDataAdapter listDataAdapter;
String titre,objet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consulter_note);
list = (ListView) findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.notelist_row);
list.setAdapter(listDataAdapter);
list.setOnItemClickListener(this);
dataBaseOperationstwo = new DataBaseOperationstwo(getApplicationContext());
sqLiteDatabase = dataBaseOperationstwo.getReadableDatabase();
cursor = dataBaseOperationstwo.getInformations(sqLiteDatabase);
if (cursor.moveToFirst())
{
do
{
titre = cursor.getString(0);
objet = cursor.getString(1);
DataProvider dataProvider = new DataProvider(titre,objet);
listDataAdapter.add(dataProvider);
}while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, note_details.class);
startActivity(intent);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
}
}
And here is my array adapter:
public class ListDataAdapter extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView TITRE,OBJET;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.notelist_row,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.TITRE = (TextView) row.findViewById(R.id.titredemo);
layoutHandler.OBJET = (TextView) row.findViewById(R.id.objetdemo);
row.setTag(layoutHandler);
}
else
{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.TITRE.setText(dataProvider.getTitre());
layoutHandler.OBJET.setText(dataProvider.getObjet());
return row;
}
}
The data provider class used in the array adapter:
public class DataProvider {
private String titre,objet;
public DataProvider(String titre,String objet)
{
this.titre = titre;
this.objet = objet;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
}
And finally my details activity. I'm only interested in the intent part; the rest has nothing to do with my problem:
public class note_details extends Activity {
ImageButton Del;
EditText PASSTITRE,USEROBJET;
String Passtitre,Userobjet;
DataBaseOperationstwo DOP;
Context CTX = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =getIntent();
if(intent != null)
{
String objet = intent.getStringExtra("objet");
String titre= intent.getStringExtra("titre");
PASSTITRE.setText(objet);
USEROBJET.setText(objet);
}
setContentView(R.layout.activity_note_details);
Del = (ImageButton) findViewById(R.id.suppnote);
PASSTITRE = (EditText) findViewById(R.id.titree);
USEROBJET = (EditText) findViewById(R.id.objett);
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passtitre = PASSTITRE.getText().toString();
Userobjet = USEROBJET.getText().toString();
DOP = new DataBaseOperationstwo(CTX);
DOP.deleteNote(DOP,Passtitre,Userobjet);
Toast.makeText(getBaseContext(),"note supprimé",Toast.LENGTH_LONG).show();
finish();
}
});
}
public void liste(View v)
{
Intent i = new Intent(this, consulter_note.class);
startActivity(i);
}
public void supprimer(View v)
{
}
}
My logcat doesn’t show any errors but the details activity shows with empty edittexts.

You should first add extras to the Intent and then fire it:
Intent intent = new Intent(this, note_details.class);
intent.putExtra("titre", titre);
intent.putExtra("objet", objet);
startActivity(intent);
Another thing worth mentioning is that you should avoid doing DB queries on the main thread, as it will slow down your app. Use Loaders, or just run queries on worker threads.

Related

How do I use variables of some class in a different class ( ConsumerDescAndEdit.java ) through onItemClickListener?

I need to display name, phoneNumber and accountNumber in EditText in the class ConsumerdescAndEdit, so how do pass these values when OnItemClickListener is executed?
ShowAll.java:
I have the ListView that inflated from CustomAdapter.
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
startActivity(intent);
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects){
this.objects = objects;
this.mContext = context;
}
public CustomAdapter(){
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout,null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
return convertView;
}
}
ConsumerDescAndEdit.java (where do I need to use variables):
public class ConsumerDescAndEdit extends AppCompatActivity {
Button updateButton;
EditText nameEditTextVar;
EditText phoneEditTextVar;
EditText accountEditTextVar;
// Variables to store user inputted data.
String nameEdit;
String phoneEdit;
String accountEdit;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_desc_and_edit);
dbHelper = new DatabaseHelper(this);
updateButton = findViewById(R.id.updateButton);
nameEditTextVar = findViewById(R.id.nameEditScreen);
phoneEditTextVar = findViewById(R.id.phoneNumberEditScreen);
accountEditTextVar = findViewById(R.id.accountNumberEditScreen);
String s_intent = getIntent().getStringExtra("EXTRA_SESSION_ID");
nameEditTextVar.setText(s_intent);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameEdit = nameEditTextVar.getText().toString();
phoneEdit = phoneEditTextVar.getText().toString();
accountEdit = accountEditTextVar.getText().toString();
if (nameEdit.isEmpty() || phoneEdit.isEmpty() || accountEdit.isEmpty()) {
Toast.makeText(ConsumerDescAndEdit.this, "Data Insufficient", Toast.LENGTH_SHORT).show();
} else {
boolean b = dbHelper.updateData(nameEdit, phoneEdit, accountEdit);
if (b)
Toast.makeText(ConsumerDescAndEdit.this, "Data updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ConsumerDescAndEdit.this, "Could not update data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When you create the Intent for the edit Activity, add the data from the selected item as "extras" to the Intent, like this:
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
intent.putExtra("name", name);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
In the edit Activity, extract the data from the Intent like this:
String name = intent.getStringExtra("name");
String phone = intent.getStringExtra("phone");
String account = intent.getStringExtra("account");
Try below code
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
private ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(Consumer consumer);
}
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects, ItemClickListener itemClickListener) {
this.objects = objects;
this.mContext = context;
this.itemClickListener = itemClickListener;
}
public CustomAdapter() {
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout, null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(consumer);
}
}
});
return convertView;
}
}
In Activity do following
public class ConsumerActivity extends AppCompatActivity implements CustomAdapter.ItemClickListener {
CustomAdapter adapter;
ArrayList<Consumer> objects;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer);
adapter = new CustomAdapter(this, objects, this);
}
#Override
public void onItemClick(Consumer consumer) {
Intent intent = new Intent(this, CustomerEdit.class);
intent.putExtra("Consumer", consumer);
startActivity(intent);
}
}

notifyDatasetChanged is not working for listview

My ListView has set of rows with Delete Button in each row.
On Click of the delete button must delete particular row from Sqlite Database and refresh the listview.
Problem
I am able to delete row from database. But I am not able to refresh the page after deleting the row.
For refreshing I tried using notifyDatasetChanged(), but no luck.
I could able to see the new list if i got back to previous activity and come back to same activity.
Please find the adapter and class codes below.
MainClass:
public class AddToCart extends AppCompatActivity {
ListView cart_list;
DatabaseHandler db = new DatabaseHandler(this);
Cursor todoCursor;
Context context;
String name, price, image, model;
ArrayList<String> bitmapArray = new ArrayList<String>();
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
Toolbar toolbar;
Button checkout;
static CustomAdapter_cart customAdapter_cart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addtocart);
context = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
cart_list = (ListView) findViewById(R.id.listview_cart);
checkout = (Button) findViewById(R.id.checkout);
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(AddToCart.this, Signup.class);
startActivity(in);
}
});
Intent i = getIntent();
// Get access to the underlying writeable database
// Query for items from the database and get a cursor back
// todoCursor = db1.rawQuery("SELECT id as _id, * from cart ", null);
// db1.execSQL("DELETE FROM cart");
// Reading all contacts
List<Cart> contacts = db.getAllContacts();
cart_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
for (Cart cn : contacts) {
name = cn.getName();
list_name.add(name);
price = cn.getPhoneNumber();
list_price.add(price);
image = cn.getImage_list();
bitmapArray.add(image);
model = cn.getModel();
list_model.add(model);
}
customAdapter_cart = new CustomAdapter_cart(this, list_name, list_price, bitmapArray, list_model);
cart_list.setAdapter(customAdapter_cart);
}
public static class MyLovelyOnClickListener implements View.OnClickListener
{
CustomAdapter_cart contextnew;
String myLovelyVariable;
Context context;
public MyLovelyOnClickListener(Context contextnew, CustomAdapter_cart context, String tv_model) {
this.contextnew = context;
this.context = contextnew;
this.myLovelyVariable = tv_model;
}
#Override
public void onClick(View v) {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db1.delete("cart", "model = ?", new String[]{myLovelyVariable});
customAdapter_cart.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
}
CustomAdapter.class
public class CustomAdapter_cart extends BaseAdapter {
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_images = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
CustomAdapter_cart cart_refresh;
Bitmap b;
View rowView;
Context context;
AddToCart cart;
private static LayoutInflater inflater = null;
Cursor cu;
Context contextnew;
AddToCart.MyLovelyOnClickListener listener;
String model_item;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.cart_refresh = this;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list_name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv_name, tv_price, tv_model;
ImageView image;
Button delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Holder holder = new Holder();
rowView = inflater.inflate(R.layout.list_items_cart, null);
holder.tv_name = (TextView) rowView.findViewById(R.id.name_cart);
holder.tv_price = (TextView) rowView.findViewById(R.id.price_cart);
holder.image = (ImageView) rowView.findViewById(R.id.image_cart);
holder.tv_model = (TextView) rowView.findViewById(R.id.model_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.tv_name.setText(list_name.get(position));
holder.tv_price.setText(list_price.get(position));
holder.tv_model.setText(list_model.get(position));
String n = holder.tv_model.getText().toString();
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
// holder.delete.setTag(holder.tv_model);
listener = new AddToCart.MyLovelyOnClickListener(context,CustomAdapter_cart.this,n);
holder.delete.setOnClickListener(listener);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) rowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) rowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) rowView.findViewById(R.id.model_cart)).getText().toString();
Intent in = new Intent(context, AddCart_FullImage.class);
in.putExtra("model", model_item);
in.putExtra("name", name_item);
in.putExtra("price", price_item);
context.startActivity(in);
}
});
return rowView;
}
private Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path, "");
f.canRead();
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any Help would be really helpfull.
Thanks.
you are just deleting a row from database. Your adapter is still having the same set of data. So first update the data set of the adapter and than call notifydatasetchanged()

How to refresh view after updating sql row while using OnItemLongClick?

The problem is as follows: When I click on the row, dialog opens where I enter new row value and click ok to save changes. The row is updated, but I need to exit view and go back again to see changes. How can I refresh view automatically when the sava button is clicked?
Here is my code for Dialog:
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("");
}
}
And here is the code where I want to refresh view instead of doing it manually:
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);
}
}
I hope it's clear enough what I am looking for. Where my list is, I want the list to be refreshed automatically after updating row so the new content of the row shows up immediately instead of navigating to other view and going back. I will be appreciated for your help.
At some point, after you call EditListItemDialog and it finishes, you need to run NotifyDataSetChanged() on your listview adapter. onResume() is a good place to do it,

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

android sqlite onresume() oncreate()

I have several activities that write and read to database. As client has to switch between them. If i leave code just in onCreate, different views will not be updated when activity is broght back to screen. What is the best way to ensure that all data is apdated when activity gets focus?
Is it wise to move evrything from onCreate() to onResume() ?
is there wat to make it better?
public class InboxActivity extends ListActivity {
List<Candidate> candidates;
private DatabaseHandler db;
private CandidateAdapter adapter;
private ListView lvMain;
public void onDestroy(){
if (db != null)
db.close();
super.onDestroy();
//db.close();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inbox_list);
db = new DatabaseHandler(this);
candidates = db.getAllCandidates(1);
db.close();
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain = getListView();
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.from)).getText().toString();
Log.d("Name ", name);
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra("name", name);
Log.d("Starting activity ", "Yeah ");
startActivity(in);
}
});
}
public void onResume(){
super.onResume();
db = new DatabaseHandler(this);
candidates = db.getAllCandidates(1);
db.close();
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain = getListView();
lvMain.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
adapter
public class CandidateAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
ArrayList<Candidate> objects;
CandidateAdapter(Context context, ArrayList<Candidate> candidates) {
ctx = context;
objects = candidates;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return objects.size();
}
public Object getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
Candidate getCandidate(int position) {
return ((Candidate) getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.inbox_list_item, parent, false);
}
Candidate p = getCandidate(position);
((TextView) view.findViewById(R.id.from)).setText(p.get_name());
((TextView) view.findViewById(R.id.subject)).setText(p.get_office());
((RatingBar) view.findViewById(R.id.rateindicator)).setRating(p.get_ranking());
int loader = R.drawable.loader;
ImageView image = (ImageView) view.findViewById(R.id.photo);
String image_url = p.get_photograph();
ImageLoader imgLoader = new ImageLoader(ctx);
imgLoader.DisplayImage(image_url, loader, image);
return view;
}
}
If you are not finishing your activity, than you no need to write all thing in onResume()
you should write just this in onResume().
public void onResume(){
adapter = new CandidateAdapter(this,(ArrayList) candidates);
lvMain.setAdapter(adapter);
adapter.notifyDataSetChanged()
}
define your CandidateAdapter as a class variable.

Categories

Resources