How to make Android ListView get refresh automatically? - android

In my app i have a ListView. Data is populated in ListView using SimpleCursorAdapter. I want ListView to be refreshed automatically whenever there is change in database or when i click button. I have tried adapter.notifyDataSetChanged() but its not effective.i couldn,t findout a good solution. I want ListView to be refreshed whenever user enters value in EditText and then press Send Button and save entered data in SQLite database. Here is my Code :
public class chatCursor extends Activity {
static MyListAdapter adapter;
ArrayList<String> item_id;
ArrayList<String> item_phone_num;
ArrayList<String> item_msg_body;
ArrayList<String> item_time;
ArrayList<String> item_flag;
ArrayList<String> items;
private Button btn_send;
DbManager manager;
Cursor Cursor;
//ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
ListView lv_chat;
String[] from = new String[]{"Message_body","Time"};
int[] toIDs = new int[]{R.id.msg_body,R.id.time};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
contact_for_chat = bundle.getString("contact_name");
contact_for_chat = contact_for_chat.replace(" ", "");
contact_no = Util.getContactNumber(contact_for_chat, chatCursor.this);
Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
item_id = new ArrayList<String>(Cursor.getCount());
item_phone_num = new ArrayList<String>(Cursor.getCount());
item_msg_body = new ArrayList<String>(Cursor.getCount());
item_time = new ArrayList<String>(Cursor.getCount());
item_flag = new ArrayList<String>(Cursor.getCount());
findViews();
showList();
//setActionBar();
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
showList();
}
});
lv_chat.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Toast.makeText(getApplicationContext(), ""+position, Toast.LENGTH_LONG).show();
int itemId = Integer.valueOf(String.valueOf(position));
}});
}
private void showList() {
showEvents(Cursor);
adapter = new MyListAdapter(this,R.layout.activity_chat,
Cursor,
from,
toIDs);
lv_chat.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void findViews() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
lv_chat = (ListView)findViewById(R.id.list);
lv_chat.setDivider(this.getResources().getDrawable(android.R.color.transparent));
}
protected void SendSMS() {
SmsManager sms_manager = SmsManager.getDefault();
message_body = et_chat.getText().toString();
ArrayList<String> parts = sms_manager.divideMessage(message_body);
sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
flag = "1";
manager.Insert_sms_data(time, contact_for_chat, message_body,flag);
if(message_body.length()>0)
{
et_chat.setText("");
}
showList();
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_LONG).show();
private void showEvents(Cursor cursor) {
int i=0;
while (cursor.moveToNext()) {
item_id.add(i+"");
item_time.add(cursor.getString(1));
item_msg_body.add(cursor.getString(3));
item_phone_num.add(cursor.getString(2));
item_flag.add(cursor.getString(4));
i++;
}
}
public class MyListAdapter extends SimpleCursorAdapter {
Cursor myCursor;
Context myContext;
public MyListAdapter(Context context, int layout,
Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myCursor = c;
myContext = context;
}
public int getCount() {
return item_msg_body.size();
}
public Object getItem(int position) {
return item_msg_body.get(position);
}
public long getItemId(int position) {
return item_msg_body.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
LayoutInflater layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_chat, null);
holder = new ViewHolder();
// holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
holder.tv_time = (TextView) v.findViewById(R.id.time);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
if(item_flag.get(position).equals("1"))
{
RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
RelativeLayout.LayoutParams dateparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dateparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
dateparams.addRule(RelativeLayout.BELOW, R.id.msg_body);
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
holder.tv_sms_body.setLayoutParams(params);
holder.tv_time.setLayoutParams(dateparams);
}
else if(item_flag.get(position).equals("0"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);
}
//holder.tv_contact.setText("" + item_phone_num.get(position));
holder.tv_sms_body.setText(item_msg_body.get(position));
holder.tv_time.setText(item_time.get(position));
return v;
}
}
public class ViewHolder {
private TextView tv_contact;
private TextView tv_sms_body;
private TextView tv_time;
}
}
Any help will will be appreciated .Thanks in advance

call adapter.notifydatasetchanged() method to refresh listview

Related

Deleting listview item from database

I am deleting the title 2 list item item
But the last title gets deleted that is the title 8 gets deleted
When I then go back to the previous screen and reopen the list. The correct that is the 2nd item title 2 had been deleted.
Here is the DataAdapter
public class DataAdapter extends BaseAdapter {
String a[];
Context ctx;
View.OnClickListener onClickListener;
MyDBHandler dbHelper;
AlertDialog alertDialog;
ArrayList<Calendars> arrayList;
public DataAdapter(Context reminderList, ArrayList<Calendars> arrayList, MyDBHandler dbHelper) {
this.ctx = reminderList;
this.arrayList = arrayList;
this.dbHelper = dbHelper;
}
public void Swap(ArrayList<Calendars> arrayList) {
this.arrayList.clear();
this.arrayList.addAll(arrayList);
this.notifyDataSetChanged();
Log.e("arraylist", arrayList.toString());
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
final ViewHolder holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
holder.dateTextView.setText(arrayList.get(position).get_reminderdate());
holder.timeTextView.setText(arrayList.get(position).get_remindertime());
holder.titleTextView.setText(arrayList.get(position).get_remindertitle());
holder.idTextview.setText(arrayList.get(position).get_id() + "");
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.remove(arrayList.get(position).get_id());
Log.e("position", position + "");
arrayList.remove(position);
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
class ViewHolder {
TextView titleTextView, dateTextView, timeTextView, idTextview;
Button deleteButton;
}
}
Here is the ListActivity
public class ReminderList extends ActionBarActivity {
Calendars calendars;
Button deleteButton;
private MyDBHandler dbHelper;
private ListView listView;
private ArrayList<Calendars> arrayList;
private SimpleCursorAdapter adapter;
int pos;
DataAdapter dataAdapter;
final String[] from = new String[]{MyDBHandler.COLUMN_REMINDER_TITLE,
MyDBHandler.COLUMN_REMINDER_DATE, MyDBHandler.COLUMN_REMINDER_TIME, MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_REMINDER_DESCRIPTION, MyDBHandler.COLUMN_REMINDER_SNOOZE, MyDBHandler.COLUMN_REMINDER_REPEAT, MyDBHandler.COLUMN_ID};
final int[] to = new int[]{R.id.titlelist, R.id.datelist, R.id.timelist, R.id.idlist,
R.id.descriptionlist, R.id.snoozelist, R.id.repeatlist, R.id.deletelist};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
deleteButton = (Button) findViewById(R.id.deletelist);
// adapter=new DataAdapter(ReminderList.this,from);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
arrayList = new ArrayList<Calendars>();
dbHelper = new MyDBHandler(this);
Cursor cursor = dbHelper.fetch();
arrayList = dbHelper.databaseToArrayList();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
dataAdapter = new DataAdapter(this, arrayList, dbHelper);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
String title = arrayList.get(position).get_remindertitle();
Log.d("title", title);
String date = arrayList.get(position).get_reminderdate();
String time = arrayList.get(position).get_remindertime();
String id = arrayList.get(position).get_id() + "";
String description = arrayList.get(position).get_reminderdescription();
String snooze = arrayList.get(position).get_remindersnooze();
String repeat = arrayList.get(position).get_reminderrepeat();
Intent modify_intent = new Intent(getApplicationContext(), AlarmActivity.class);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
modify_intent.putExtra("time", time);
modify_intent.putExtra("date", date);
modify_intent.putExtra("description", description);
modify_intent.putExtra("snooze", snooze);
modify_intent.putExtra("repeat", repeat);
startActivity(modify_intent);
dataAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
super.onStart();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
NavUtils.navigateUpFromSameTask(this);
return true;
}
case R.id.add_record: {
Intent add_mem = new Intent(this, AlarmActivity.class);
startActivity(add_mem);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabasetoArraylist function
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
Change your getView() method of adapter by below code:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final Calendars calendars = arrayList.get(position);
if (convertView == null)
{
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.dateTextView.setText(calendars.get_reminderdate());
holder.timeTextView.setText(calendars.get_remindertime());
holder.titleTextView.setText(calendars.get_remindertitle());
holder.idTextview.setText(calendars.get_id() + "");
holder.deleteButton.setTag(calendars);
holder.deleteButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
final selectedCalendar = (Calendars) holder.deleteButton.getTag();
dbHelper.remove(selectedCalendar.get_id());
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}

i cannot set select all checkbox to listview here is my code

Code for custome adapter
public class CustomAdapter extends BaseAdapter{
private Context context;
private ArrayList<String> name;
private ArrayList<String> id;
private ArrayList<String> group;
boolean checkBoxState;
public CustomAdapter( Context c,ArrayList<String> Cid, ArrayList<String> Cname,ArrayList<String> Cgroup) {
this.name = Cname;
this.id=Cid;
this.group = Cgroup;
MsgActivity msg=new MsgActivity();
this.context = c;
}
#Override
public int getCount() {
return id.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View Child, ViewGroup parent) {
Holder mholder;
LayoutInflater layoutInflater;
if(Child==null) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
Child = layoutInflater.inflate(R.layout.listview, null);
mholder = new Holder();
mholder.txt_name = (TextView) Child.findViewById(R.id.tvlist_name);
mholder.txt_Grp = (TextView) Child.findViewById(R.id.tvlist_group);
mholder.txt_id = (TextView) Child.findViewById(R.id.tvlist_id);
mholder.chk_box=(CheckBox) Child.findViewById(R.id.cbList_hook);
Child.setTag(mholder);
}
else
{
mholder=(Holder) Child.getTag();
}
mholder.txt_name.setText(name.get(position));
mholder.txt_Grp.setText(group.get(position));
mholder.txt_id.setText(id.get(position));
mholder.chk_box.setChecked(true);
return Child;
}
public class Holder {
TextView txt_id;
TextView txt_name;
TextView txt_Grp;
CheckBox chk_box;
}
}
code for display activity
public class MsgActivity extends AppCompatActivity implements OnItemSelectedListener {
EditText tx1;
TextView tv;
Button b1,b2,b3;
Spinner sp;
ListView lv;
String dat3;
SQLiteDatabase dh;
DbHelper mhelper;
public Integer m=null;
AddgrpActivity addgrp;
public CheckBox cb;
private ArrayList<String> userId = new ArrayList<>();
private ArrayList<String> user_name = new ArrayList<>();
private ArrayList<String> user_num = new ArrayList<>();
ArrayList<String> groups = new ArrayList<>();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dat3=sp.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),dat3,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg);
tx1 = (EditText) findViewById(R.id.editText);
b1 = (Button) findViewById(R.id.button2_add_msg);
b2 = (Button) findViewById(R.id.button_snd);
sp = (Spinner) findViewById(R.id.spinner);
lv = (ListView) findViewById(R.id.listView);
sp.setOnItemSelectedListener(this);
mhelper = new DbHelper(this);
cb=(CheckBox)findViewById(R.id.checkBox_1);
tv=(TextView)findViewById(R.id.textView);
groups = addgrp.Addall();
groups.add("all");
ArrayAdapter<String> grps = new ArrayAdapter(this, android.R.layout.simple_spinner_item, groups);
grps.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(grps);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userId.clear();
user_name.clear();
user_num.clear();
dh = mhelper.getReadableDatabase();
Cursor mCursor;
if (dat3 == "all") {
mCursor = dh.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
} while (mCursor.moveToNext());
CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
//ArrayAdapter cst = new ArrayAdapter(MsgActivity.this, android.R.layout.simple_list_item_multiple_choice, user_name);
lv.setAdapter(cst);
}
} else {
mCursor = dh.rawQuery("select * from " + DbHelper.TABLE_NAME + " where " + DbHelper.KEY_GRP + " = ?", new String[]{dat3});
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
//user_sal.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_SAL)));
} while (mCursor.moveToNext());
}
}
final CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
// ArrayAdapter cst=new ArrayAdapter(MsgActivity.this,android.R.layout.simple_list_item_multiple_choice,user_name);
//lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
lv.setAdapter(cst);
mCursor.close();
}
});
}
public void onBackPressed() {
Intent in = new Intent(MsgActivity.this, MainActivity.class);
startActivity(in);
}
}

Listview is not updating inside baseadapter after changing database value

I use SQLITE database to store list items and Baseadapter to display listview in my application.
Each item in the listview have edit text value, By default the value is 1.
When user changes the value from 1 to 2 , then the value has to be updated in database.
This update has to be done inside Adapter.
Below is the Adapter code where I change the edit text value.
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>();
ArrayList<String> list_productid = new ArrayList<String>();
ArrayList<Integer> ids = new ArrayList<Integer>();
CustomAdapter_cart cart_refresh;
Bitmap b;
Context context;
AddToCart cart;
String value,name,price,image_new,model,product,qty;
private static LayoutInflater inflater = null;
Cursor cu;
String quant;
Holder holder = new Holder();
SharedPreferences sharedpreferences;
ArrayList<String>listMessages = new ArrayList<String>(new LinkedHashSet<String>());
ArrayList<String> quant_items = new ArrayList<String>();
Cursor mCursor;
ContentValues data=new ContentValues();
String model_item;
String id;
int id_final;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model, ArrayList<String> list_productid,ArrayList<String> qty, ArrayList<Integer>ids ) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.list_productid = list_productid;
this.quant_items = qty;
this.cart_refresh = this;
this.ids = ids;
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,tv_product,tv_id;
ImageView image;
Button delete;
EditText quantity;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View rowView = convertView;
if (convertView == null) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
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.tv_product = (TextView) rowView.findViewById(R.id.product_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.quantity = (EditText) rowView.findViewById(R.id.quantity);
holder.tv_id = (TextView)rowView.findViewById(R.id.ids);
rowView.setTag(holder);
}
else
holder = (Holder) rowView.getTag();
holder.tv_name.setText(list_name.get(position));
name = holder.tv_name.getText().toString();
holder.tv_price.setText(list_price.get(position));
price = holder.tv_price.getText().toString();
holder.tv_model.setText(list_model.get(position));
model = holder.tv_model.getText().toString();
holder.tv_product.setText(list_productid.get(position));
product = holder.tv_product.getText().toString();
holder.quantity.setText(quant_items.get(position));
quant = holder.quantity.getText().toString();
holder.tv_id.setText(Integer.toString(ids.get(position)));
id = holder.tv_id.getText().toString();
id_final = Integer.parseInt(id);
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
image_new = holder.image.toString();
final View finalRowView1 = rowView;
holder.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
value = s.toString();
quant.replace(quant, value);
updateTable();
Toast.makeText(finalRowView1.getContext(), "Updating Table", Toast.LENGTH_SHORT).show();
}
});
final View finalRowView = rowView;
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) finalRowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) finalRowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) finalRowView.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;
}
public void updateTable() {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db.updateContact(new Cart(id_final,name, price, image_new, model, product, value));
Log.v("LOG", "After text change value db " + value);
} catch (Exception e) {
}
}
}
Problem
When I try to update the edit text value, it gets updated in db but again it changes to default value "1".
I am not sure where I am going wrong.
Any help would be really greatfull.
Thanks.
Each time the system wants to redraw your ListView it calls the getView(...) method of your adapter. The following line sets the value of your quantity EditText:
holder.quantity.setText(quant_items.get(position));
When the user changes the value in the EditText you do the following:
quant.replace(quant, value);
updateTable();
As you can see, your adapter's datasource (quant_items) is not updated.
Since you are updating the database from within the adapter, you can just update the quant_items ArrayList and it should do the trick.
You need to notify your adapter if you change its data (and of, you need to update list_name with the new values).
The easiest way to notify your adapter is to use notifyDatasetChanged() after you updated your data.

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 ListView automatically?

In my app, i am populating ListView with received and sent SMS. Here is the code :
public class ChatActivity extends ListActivity {
private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_phone_num = new ArrayList<String>();
ArrayList<String> item_msg_body = new ArrayList<String>();
ArrayList<String> item_time = new ArrayList<String>();
ArrayList<String> item_flag = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>();
private Button btn_send;
DbManager manager;
Cursor Cursor;
ViewHolder holder12;
String contact_for_chat;
String contact_no;
String message_body = "";
Calendar c;
SimpleDateFormat sdf;
String time;
EditText et_chat;
String flag;
String msg = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
contact_for_chat = bundle.getString("contact_name");
contact_for_chat = contact_for_chat.replace(" ", "");
contact_no = Util.getContactNumber(contact_for_chat, ChatActivity.this);
Toast.makeText(getApplicationContext(), contact_no, Toast.LENGTH_LONG).show();
final ViewHolder holder = new ViewHolder();
manager = new DbManager(this);
Cursor = manager.Return_SMS(contact_for_chat);
showEvents(Cursor);
c = Calendar.getInstance();
sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
time = sdf.format(c.getTime());
setActionBar();
findViewsById();
adapter = new MyListAdapter(this);
adapter.notifyDataSetChanged();
setListAdapter(adapter);
btn_send = (Button) findViewById(R.id.button1);
btn_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SendSMS();
refreshCursor();
}
});
}
protected void SendSMS() {
SmsManager sms_manager = SmsManager.getDefault();
message_body = et_chat.getText().toString();
ArrayList<String> parts = sms_manager.divideMessage(message_body);
sms_manager.sendMultipartTextMessage(contact_no, null, parts, null, null);
flag = "1";
manager.Insert_sms_data(time, contact_for_chat, message_body,flag);
updateUI();
msg+= "SMS to :" + contact_for_chat + " \n";
msg += "having number:" + contact_no + " \n";
msg += "as" +message_body + " \n";
msg += "at"+ time + " \n";
Toast.makeText(getApplicationContext(), ""+msg , Toast.LENGTH_LONG).show();
}
private void setActionBar() {
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayHomeAsUpEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.actionbar_chat, null);
TextView tv_chat = (TextView)mCustomView.findViewById(R.id.title_text);
tv_chat.setText(contact_for_chat);
ColorDrawable colorDaawable = new ColorDrawable(Color.parseColor("#CFCFC4"));
mActionBar.setBackgroundDrawable(colorDaawable);
mActionBar.setLogo(R.drawable.ic_launcher);
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
private void updateUI() {
et_chat.setText("");
refreshCursor();
adapter.notifyDataSetChanged();
}
private void findViewsById() {
et_chat = (EditText)findViewById(R.id.et_chat);
btn_send = (Button)findViewById(R.id.button1);
}
private void showEvents(Cursor cursor) {
item_id = new ArrayList<String>(cursor.getCount());
item_phone_num = new ArrayList<String>(cursor.getCount());
item_msg_body = new ArrayList<String>(cursor.getCount());
item_time = new ArrayList<String>(cursor.getCount());
item_flag = new ArrayList<String>(cursor.getCount());
int i=0;
while (cursor.moveToNext()) {
item_id.add(i+"");
item_time.add(cursor.getString(1));
item_msg_body.add(cursor.getString(3));
item_phone_num.add(cursor.getString(2));
item_flag.add(cursor.getString(4));
i++;
}
}
public class MyListAdapter extends BaseAdapter {
Context con;
private LayoutInflater layoutinf;
ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
ArrayList<String> items_ = new ArrayList<String>();
public MyListAdapter(ChatActivity context) {
con = context;
}
public int getCount() {
return item_id.size();
}
public Object getItem(int position) {
return item_id.size();
}
public long getItemId(int position) {
return item_id.get(position).hashCode();
}
public View getView(final int position, View arg1, ViewGroup arg2) {
View v = arg1;
ViewHolder holder = null;
if (v == null) {
layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_chat, null);
holder = new ViewHolder();
holder.tv_contact = (TextView) v.findViewById(R.id.phone_num);
holder.tv_sms_body = (TextView) v.findViewById(R.id.msg_body);
holder.tv_time = (TextView) v.findViewById(R.id.time);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
if(item_flag.get(position).equals("1"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_green);
}
else if(item_flag.get(position).equals("0"))
{
holder.tv_sms_body.setBackgroundResource(R.drawable.bubble_yellow);
}
holder.tv_contact.setText("" + item_phone_num.get(position));
holder.tv_sms_body.setText(item_msg_body.get(position));
holder.tv_time.setText(item_time.get(position));
return v;
}
}
public class ViewHolder {
private TextView tv_contact;
private TextView tv_sms_body;
private TextView tv_time;
}
private void refreshCursor() {
manager.open();
Cursor = manager.Return_SMS(contact_for_chat);
setListAdapter(adapter);
manager.close();
}
I want that as soon as SMS is received or sent,ListView should be updated automatically. I have tried it using
adapter.notifyDataSetChanged();
but its not working . How can i make my app ListView updated as soon as SMS is sent or received. Any help will be appreciated.
notifyDataSetChanged tells the listview to reload its data. Its still going to call the adaptor functions getView and getItemCount to do this. Those need to return the correct new data. However, you're not updating the data they return- you're only setting the item_id array in onCreate. Since the array is never changed, the list view is never updated.
use this code:
adapter.notifyDataSetChanged();

Categories

Resources