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();
Related
I have an ArrayList that keeps getting overwritten instead of adding new values to the list. I'm not recreating the list each time its only getting made once. If I add the details in manually that data doesn't get overwritten but when I try to add per the method populate data it doesn't stay. so I'm not sure as to what the issue is. Here is my full Main Activity class where everything goes down.
public class MainActivity extends AppCompatActivity {
ListView listView;
Button button;
public static final String PREFS_NAME = "MyPreferencesFile";
String date_out,date_in;
String part_number,serial_number;
int employee_number;
Context context;
ArrayList<Toolinfo> toolinfos = new ArrayList<>();
String currentDateandTime;
Toolinfo tool1;
public static String TAG = "Main";
ToolListAdapter myadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myadapter = new ToolListAdapter(this,R.layout.logrowlayout,toolinfos );
button = findViewById(R.id.button);
listView = findViewById(R.id.listview);
listView.setAdapter(myadapter);
loadData();
//Toolinfo too = new Toolinfo("part number","serial number",333,"date","out");
// Toolinfo too1 = new Toolinfo("part number","serial number",333,"date","out");
// toolinfos.add(too);
// toolinfos.add(too1);
for (int i = 0; i < toolinfos.size() ; i++) {
Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
}
Intent getData = getIntent();
if(getData.hasExtra("part number")&& getData.hasExtra("serial number") && getData.hasExtra("employee number")) {
final String part_number = getData.getStringExtra("part number");
showToast("has extras");
String serial_number = getData.getStringExtra("serial number");
showToast(serial_number);
int employee_number = getData.getIntExtra("employee number", 0);
populateData(part_number,serial_number,employee_number,date_out,"out");
}else {
showToast("info not present");
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTool();
}
});
}
public void populateData(String part_number,String serial_number,int employee_number, String date_out, String date_in) {
//loadData();
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
String currentDateandTime = sdf.format(new Date());
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
myadapter.notifyDataSetChanged();
for (int i = 0; i < 1 ; i++) {
//Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
toolinfos.add(tool);
}
saveData(tool);
}
private void saveData(Toolinfo tool) {
SharedPreferences preferences = getSharedPreferences("Shared prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(tool);
editor.putString("toolobj",json);
showToast(json);
editor.commit();
editor.apply();
showToast("Data Saved");
}
private void loadData(){
SharedPreferences preferences = getSharedPreferences("Shared prefs", MODE_PRIVATE);
Gson gson = new Gson();
String json = preferences.getString("toolobj","");
if (json.isEmpty()){
showToast("no data");
}else {
Toolinfo tool1 = gson.fromJson(json, Toolinfo.class);
if (tool1 != null)
toolinfos.add(tool1);
else{
showToast("Object is null ");
}
}
}
private void addTool(){
Intent i = new Intent(MainActivity.this,Toolsignout.class);
startActivity(i);
//saveData(tool1);
}
public void showToast(String msg){
Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}
#Override
protected void onResume() {
// loadData();
super.onResume();
}
}
here is the arrayadapter class
public class ToolListAdapter extends ArrayAdapter<Toolinfo> {
private Context mcontext;
int mResource;
ArrayList<Toolinfo> objects;
public ToolListAdapter(Context context, int resource, ArrayList<Toolinfo> objects) {
super(context, resource, objects);
mcontext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String part_number = getItem(position).getPart_number();
String serial_number = getItem(position).getSerial_number();
int employee_number = getItem(position).getEmployee_nummber();
String date_out = getItem(position).getOut_time();
String date_in = getItem(position).getIn_time();
Toolinfo toolinfo = new Toolinfo(part_number,serial_number,employee_number,date_out,date_in);
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
TextView parnum = (TextView)convertView.findViewById(R.id.patnum);
TextView sernum = (TextView)convertView.findViewById(R.id.sernum);
TextView empnum = (TextView)convertView.findViewById(R.id.empnum);
TextView timeout = (TextView)convertView.findViewById(R.id.timeout);
TextView timein = (TextView)convertView.findViewById(R.id.timein);
parnum.setText(part_number);
sernum.setText(serial_number);
empnum.setText(String.valueOf(employee_number));
timeout.setText((date_out));
timein.setText((date_in));
return convertView;
}
}
in your Adapter make the following changes
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// **added the if else condition**
View listItem = convertView;
if (listItem == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
}
String part_number = getItem(position).getPart_number();
String serial_number = getItem(position).getSerial_number();
int employee_number = getItem(position).getEmployee_nummber();
String date_out = getItem(position).getOut_time();
String date_in = getItem(position).getIn_time();
Toolinfo toolinfo = new Toolinfo(part_number,serial_number,employee_number,date_out,date_in);
TextView parnum = (TextView)convertView.findViewById(R.id.patnum);
TextView sernum = (TextView)convertView.findViewById(R.id.sernum);
TextView empnum = (TextView)convertView.findViewById(R.id.empnum);
TextView timeout = (TextView)convertView.findViewById(R.id.timeout);
TextView timein = (TextView)convertView.findViewById(R.id.timein);
parnum.setText(part_number);
sernum.setText(serial_number);
empnum.setText(String.valueOf(employee_number));
timeout.setText((date_out));
timein.setText((date_in));
return convertView;
}
I just put your Inflater inside the if Statement
View listItem = convertView;
if (listItem == null)
{
LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
convertView = layoutInflater.inflate(mResource,parent,false);
}
Although your code is not easy to read, I found that in populateData() you do something inexplicable:
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
myadapter.notifyDataSetChanged();
for (int i = 0; i < 1 ; i++) {
//Log.d(TAG, "onCreate: tools:" + toolinfos.get(i).getPart_number());
toolinfos.add(tool);
}
why do you use a for loop to add 1 element? and myadapter.notifyDataSetChanged(); should be called after the addition:
Toolinfo tool = new Toolinfo(part_number, serial_number, employee_number, currentDateandTime, "out");
toolinfos.add(tool);
myadapter.notifyDataSetChanged();
I am able to display the toast in my menuactivity but now i will need to get the selected data from listview and display it on another page. I have tried alot of methods and search on it but i cant seem to get it.
menuactivity :
public class MenuActivity extends Activity {
private String server = "http://172.16.156.56";
private String sql_table = "orders";
private ListView list;
private TextView txtOrder, txtMember, txtPrice;
private Button btnAdd;
ArrayList<String> rows;
ListView listView1;
Button btnSubmit;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
list=(ListView) findViewById(R.id.listView);
btnAdd = (Button)findViewById(R.id.button);
rows = new ArrayList<String>();
itemList=new ArrayList<CustomItem>();
itemList.add(new CustomItem("Fried Rice","description","1","Quantity"));
itemList.add(new CustomItem("Fried Noodle","description","2","Quantity"));
itemList.add(new CustomItem("Prawn noodle","description","3","Quantity"));
itemList.add(new CustomItem("Chicken Rice","description","4","Quantity"));
int[] prgmImages={R.drawable.friedrice,R.drawable.friednoodle,R.drawable.pnoodle,R.drawable.chickenrice};
listView1 = (ListView) findViewById(R.id.listView);
final CustomLVAdapter customLVAdapter = new CustomLVAdapter(this, itemList,prgmImages);
listView1.setAdapter(customLVAdapter);
txtOrder = (TextView) findViewById(R.id.txt1);
txtMember = (TextView) findViewById(R.id.txt2);
txtPrice = (TextView) findViewById(R.id.txt3);
btnSubmit = (Button) findViewById(R.id.button);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
selectedList = new ArrayList<CustomItem>();
int total = 0;
for (int i = 0; i < itemList.size(); i++) {
CustomItem object = itemList.get(i);
if (object.isSelected()) {
responseText.append(object.getItem() + "," + object.getQty() + ",");//item
selectedList.add(object);
//calculate price
total = total + Integer.parseInt(object.getQty()) * Integer.parseInt(object.getPrice());
}
}
Add(responseText.toString(), "5565", String.valueOf(total));
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
startActivity(i);
Toast.makeText(getApplicationContext(), responseText + " $" + total,
Toast.LENGTH_SHORT).show();
SelectAll();
//store in database
//go to ReceiptActivity - membership, item, totalprice
}
});
}
public void Add(final String item, final String membership, final String price)
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/insertorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("item",item );
MyData.put("membership",membership );
MyData.put("price",price );
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
SelectAll();
}
public void SelectAll()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
String url = server + "/fetchorder.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray(sql_table);
rows.clear();
for(int i=0; i < jsonMainNode.length(); i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String order = jsonChildNode.optString("item").toString();
String membership = jsonChildNode.optString("membership").toString();
String price = jsonChildNode.optString("price").toString();
rows.add(order + ", " + membership + ", " + price );
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MenuActivity.this,
android.R.layout.simple_list_item_1, rows);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue.add(MyStringRequest);
}
}
Receipt activity ( the page i wan to display my results)
public class ReceiptActivity extends Activity {
static public String txtOrder = "";
TextView foodorder;
ArrayList<CustomItem> itemList, selectedList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
CustomLVAdapter item = (CustomLVAdapter) parent.getItemAtPosition(position);
TextView foodorder = (TextView)findViewById(R.id.foodorder);
foodorder.setText("Order:" +strOrder+" ");
Custom adapter
public class CustomLVAdapter extends BaseAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<CustomItem> objectList;
private int[] imageId;
public static ArrayList<CustomItem> arl_food=new ArrayList<>();
private class ViewHolder {
TextView txt1,txt2,txt3;
CheckBox ckBox;
ImageView image;
NumberPicker np;
}
public CustomLVAdapter(Context context, ArrayList<CustomItem> objectList,int[]prgmImages){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.objectList = objectList;
this.imageId = prgmImages;
}
public int getCount(){
return objectList.size();
}
public CustomItem getItem (int position) {
return objectList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row_checkbox_textview, null);
holder.txt1 = (TextView) convertView.findViewById(R.id.txt1);
holder.txt2 = (TextView) convertView.findViewById(R.id.txt2);
holder.txt3 = (TextView) convertView.findViewById(R.id.txt3);
holder.image=(ImageView) convertView.findViewById(R.id.image);
holder.ckBox = (CheckBox) convertView.findViewById(R.id.ckBox);
holder.np = (NumberPicker) convertView.findViewById(R.id.numberPicker);
holder.np.setMinValue(0);
holder.np.setMaxValue(10);
convertView.setTag(holder);
holder.ckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
CustomItem object = (CustomItem) cb.getTag();
Toast.makeText(context,
"You have selected: " + object.getItem() +
"Price: " + object.getPrice() +
"Qty: " + object.getQty(),
Toast.LENGTH_LONG).show();
object.setSelected(cb.isChecked());
}
}
);
holder.np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
NumberPicker p = picker;
CustomItem object = (CustomItem) p.getTag();
object.setQty(String.valueOf(newVal));
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
CustomItem object = objectList.get(position);
holder.txt1.setText(object.getItem());
holder.txt2.setText(object.getDesc());
holder.txt3.setText(object.getPrice());
holder.np.setTag(object);
holder.image.setImageResource(imageId[position]);
holder.ckBox.setChecked(object.isSelected());
holder.ckBox.setTag(object);
return convertView;
}
}
It looks like you are already starting an activity when the submit button is clicked. Now all you have to do is pass a couple extras in the intent you are creating.
So when you make the intent you should also do this:
...
Intent i = new Intent(v.getContext(), ReceiptActivity.class);
i.putExtra("PRICE", price);
i.putExtra("MEMBERSHIP", membership);
i.putExtra("ITEM", item);
startActivity(i);
...
Then in your new activity you will read out the extras in your onCreate method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
int price = getIntent().getStringExtra("PRICE");
String membership = getIntent().getStringExtra("MEMBERSHIP");
CustomItem item = getIntent().getStringExtra("ITEM");
...
One Caveat! It looks like you are representing your items with the object CustomItem. In order to pass that as an extra it will have to implement Parcelable. When you implement Parcelable you will define how to turn the object and its fields into a "parcel" and how to turn a "parcel" back into your object. The google docs give a pretty good example for it.
I lied, another caveat! I would recommend that you make the keys for the extras "public static final String"s inside of your ReceiptActivity. That way you will have an easier time managing them.
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);
}
}
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()
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