Automatically refresh listview on sqlite database change - Chat Application Android -


i building chat application response in broadcastreceiver. send data intentservice insert data sqlite database. refresh listview in fragment according database change automatically. list populated using cursoradapter.

my code massageview fragment follows:

public class messageview_fragment extends fragment {  view rootview; listview lv; chatlistadapter chatadapter; arraylist<message_master> arr; matrixcursor cr; dbhelper db; static string rmob; actionmode actionmode; sharedpreferences prefs; simpledateformat sdf,sdf_old,sdf_today; framelayout attacher;  boolean isbottom = true;  @suppresslint("defaultlocale") @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate)  {     // todo auto-generated method stub     rootview = inflater.inflate(r.layout.fragment_message, container, false);     getactivity().getwindow().setbackgrounddrawableresource(r.drawable.chat_back);     rmob = getarguments().getstring("rmob");     log.e("rmob", rmob);     lv= (listview)rootview.findviewbyid(r.id.chat_msg_list);     db = new dbhelper(getactivity());     db.updateunseentoseen(long.valueof(rmob));     contact_master cm = db.getcontactdetails(rmob);     actionbar mactionbar = ((actionbaractivity)getactivity()).getsupportactionbar();     mactionbar.setdisplayshowhomeenabled(true);     mactionbar.setdisplayshowtitleenabled(false);     layoutinflater minflater = layoutinflater.from(getactivity());     view mcustomview = minflater.inflate(r.layout.custom_action_bar_chat, null);     roundedimageview prof_pic = (roundedimageview)mcustomview.findviewbyid(r.id.imageview1);     textview tv_name = (textview)mcustomview.findviewbyid(r.id.textview1);     if(cm.getname() == null)     {         tv_name.settext(rmob);     }     else     {         tv_name.settext(cm.getname());     }      textview tv_details = (textview)mcustomview.findviewbyid(r.id.textview2);     tv_details.settext(cm.getstatus());     mactionbar.setcustomview(mcustomview);     mactionbar.setdisplayshowcustomenabled(true);     attacher = (framelayout)rootview.findviewbyid(r.id.attacher);     prefs = getactivity().getsharedpreferences(splashscreen_activity.myprefs, context.mode_private);     sdf = new simpledateformat("dd mmm");     sdf_old = new simpledateformat("mmmm dd, yyyy");     sdf_today = new simpledateformat("h:mm a");     arr = db.getmessages(rmob);     cr = new matrixcursor(new string[]{"_id","msg","type","dt","stat"});     boolean timeadded = false;     if(arr.size()>0)     {         calendar c = calendar.getinstance();         for(int = 0; i<arr.size();i++)         {                    if(arr.get(i).gettype() == 0)             {                 cr.addrow(new string[]{string.valueof(arr.get(i).getid()),arr.get(i).getmsg(),"0", sdf.format(arr.get(i).getmsgtime()),arr.get(i).getstatus()});             }             else             {                 cr.addrow(new string[]{string.valueof(arr.get(i).getid()),arr.get(i).getmsg(),"1",sdf.format(arr.get(i).getmsgtime()),arr.get(i).getstatus()});             }         }     }     chatadapter = new chatlistadapter(getactivity(),cr);      lv.setadapter(chatadapter);     chatadapter.notifydatasetchanged();      final emojiconedittext emojiconedittext = (emojiconedittext) rootview.findviewbyid(r.id.msg_edit);     final imagebutton emojibutton = (imagebutton) rootview.findviewbyid(r.id.smiley_btn);     final imagebutton submitbutton = (imagebutton) rootview.findviewbyid(r.id.send_btn);        //on submit, add edittext text listview , clear edittext     submitbutton.setonclicklistener(new onclicklistener() {          @override         public void onclick(view v) {             string newtext = emojiconedittext.gettext().tostring();             if(newtext.trim().length()>0)             {                  emojiconedittext.gettext().clear();                 long _id = db.insertmessage(1, newtext, prefs.getstring("regmobile", "0"), rmob); //              madapter.add(newtext);                 send(newtext,_id,getactivity().getapplicationcontext(),prefs.getstring("regmobile", "0"));                 cr.addrow(new string[]{string.valueof(_id),newtext,"1", sdf.format(calendar.getinstance().gettime()),"w"});                 chatadapter.notifydatasetchanged();                 lv.setselection(lv.getadapter().getcount() - 1);              }         }        });       sethasoptionsmenu(true);     return rootview; }  @suppresslint("simpledateformat") public void refreshlist(long id,string msg) {     simpledateformat sdf = new simpledateformat("dd mmm");     cr.addrow(new string[]{string.valueof(id),msg,"0", sdf.format(calendar.getinstance().gettime()),"w"});     chatadapter.notifydatasetchanged();     lv.setselection(lv.getadapter().getcount() - 1); }  private void send(final string txt, final long _id, final context context, final string mynumber) {     new asynctask<void, void, string>() {         @override         protected string doinbackground(void... params) {             string msg = "";             try {                 serverutilities.send(txt, rmob,_id,context,mynumber);              } catch (ioexception ex) {                 msg = "message not sent";             }             return msg;         }          @override         protected void onpostexecute(string msg) {             if (!textutils.isempty(msg)) {                 //toast.maketext(getactivity(), msg, toast.length_long).show();             }         }     }.execute(null, null, null);         }} 

broadcastreceiver follows:

public class gcmbroadcastreceiver extends wakefulbroadcastreceiver {  private static final string tag = "gcmbroadcastreceiver"; public static final string constant_for_receiver = "msg_type"; private context ctx;     dbhelper db;  @override public void onreceive(context context, intent intent) {     ctx = context;     db = new dbhelper(ctx);     powermanager mpowermanager = (powermanager) context.getsystemservice(context.power_service);     wakelock mwakelock = mpowermanager.newwakelock(powermanager.partial_wake_lock, tag);     mwakelock.acquire();     try {         googlecloudmessaging gcm = googlecloudmessaging.getinstance(context);         string messagetype = gcm.getmessagetype(intent);         if (googlecloudmessaging.message_type_send_error.equals(messagetype))          {             //sendnotification("send error", false);         }         else if (googlecloudmessaging.message_type_deleted.equals(messagetype))          {             //sendnotification("deleted messages on server", false);         }         else          {             componentname comp = new componentname(context.getpackagename(),messageview_fragment.esendservice.class.getname());                 startwakefulservice(context, (intent.setcomponent(comp)));                 setresultcode(activity.result_ok);          }         setresultcode(activity.result_ok);     } {         mwakelock.release();     } }} 

sendservice follows:

public class sendservice extends intentservice { dbhelper db; context ctx; public sendservice() {     // todo auto-generated constructor stub     super("name"); }  public sendservice(string name) {     super(name);     // todo auto-generated constructor stub }  @override protected void onhandleintent(intent intent) {     db = new dbhelper(getapplicationcontext());     ctx = getapplicationcontext();     // todo auto-generated method stub     string msg = intent.getstringextra(dbhelper.messages_column_message);     string sendermob = intent.getstringextra(dbhelper.messages_column_sender_mobile);     string receivermob = intent.getstringextra(dbhelper.messages_column_receiver_mobile);     string chattype = intent.getstringextra("chattype");     log.e("rmob", receivermob);     log.e("smob", sendermob);     db.insertmessage(0, msg,receivermob ,sendermob,"open");     contact_master cm = db.getcontactdetails(sendermob);     string sender_name = "";     if(cm !=null)     {          sender_name = cm.getname();     }     else     {         sender_name = sendermob;     }       db.close();  }} 

currently, flow of receiving email follows:

gcm -> broadcardreceiver -> sendservice -> messageviewfragment

thanks in advance.

you have use intentservice update listview ui.

override onreceiveresult(int, bundle)

see answer so:

check link answer

sample code solution:

@override protected void onreceiveresult (int resultcode, bundle resultdata) {      cttobjects.clear();     cttobjectsdatasource datasource = new cttobjectsdatasource(context);     datasource.open();     cttobjects.addall(datasource.getallobjects());     datasource.close();     arrayadapter.notifydatasetchanged();  } 

you have pass activity's context when initialize resultreceiver.

sample code:

public class mainactivity extends activity {  .... .... ....      public void showresults() {         cttobjects.clear();         cttobjectsdatasource datasource = new cttobjectsdatasource(mainactivity.this);         datasource.open();         cttobjects.addall(datasource.getallobjects());         datasource.close();         arrayadapter.notifydatasetchanged();     }  .... .... ....        class updateobjectresultreceiver extends resultreceiver {      ....     ....     ....          @override         protected void onreceiveresult (int resultcode, bundle resultdata) {             mainactivity.this.showresults();         }      } } 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -