android - how to set the view to last item in recyclerview -


i displaying list of messages in chat room , i'm using recycleview display. want view set recent message(last message, last item in list) instead of first item. used smoothscrolltoposition don't want list scrolled first last view recent message. want whatsapp when clicked on chat show view of last message. how can achieve this?

package com.wipro.chat.activity;  import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.os.bundle; import android.support.v4.content.localbroadcastmanager; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.defaultitemanimator; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.support.v7.widget.toolbar; import android.text.textutils; import android.util.log; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.toast;  import com.android.volley.defaultretrypolicy; import com.android.volley.networkresponse; import com.android.volley.request; import com.android.volley.response; import com.android.volley.retrypolicy; import com.android.volley.volleyerror; import com.android.volley.toolbox.stringrequest;  import org.json.jsonarray; import org.json.jsonexception; import org.json.jsonobject;  import java.sql.timestamp; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; import java.util.hashmap; import java.util.map;  import com.wipro.chat.r; import com.wipro.chat.adapter.chatroomthreadadapter; import com.wipro.chat.app.config; import com.wipro.chat.app.endpoints; import com.wipro.chat.app.myapplication; import com.wipro.chat.gcm.notificationutils; import com.wipro.chat.model.message; import com.wipro.chat.model.user;  public class chatroomactivity extends appcompatactivity {      private string tag = chatroomactivity.class.getsimplename();      private string userchatroomid;     private recyclerview recyclerview;     private chatroomthreadadapter madapter;     private arraylist<message> messagearraylist;     private broadcastreceiver mregistrationbroadcastreceiver;     private edittext inputmessage;     private button btnsend;     private string selfuserid;     private string selfusername;     @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_chat_room);         toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar);         setsupportactionbar(toolbar);          inputmessage = (edittext) findviewbyid(r.id.message);         btnsend = (button) findviewbyid(r.id.btn_send);          intent intent = getintent();         userchatroomid = intent.getstringextra("user_id");         string title = intent.getstringextra("name");          getsupportactionbar().settitle(title);         getsupportactionbar().setdisplayhomeasupenabled(true);          if (userchatroomid == null) {             toast.maketext(getapplicationcontext(), "user chat room not found!", toast.length_short).show();             finish();         }          recyclerview = (recyclerview) findviewbyid(r.id.recycler_view);          messagearraylist = new arraylist<>();          // self user id identify message owner         selfuserid = myapplication.getinstance().getprefmanager().getuser().getid();         selfusername = myapplication.getinstance().getprefmanager().getuser().getname();          madapter = new chatroomthreadadapter(this, messagearraylist, selfuserid);          linearlayoutmanager layoutmanager = new linearlayoutmanager(this);         recyclerview.setlayoutmanager(layoutmanager);         recyclerview.setitemanimator(new defaultitemanimator());         recyclerview.setadapter(madapter);          mregistrationbroadcastreceiver = new broadcastreceiver() {             @override             public void onreceive(context context, intent intent) {                 if (intent.getaction().equals(config.push_notification)) {                     // new push message received                     handlepushnotification(intent);                 }             }         };          btnsend.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view v) {                 sendmessage();             }         });          fetchchatthread();     }      @override     protected void onresume() {         super.onresume();          // registering receiver new notification         localbroadcastmanager.getinstance(this).registerreceiver(mregistrationbroadcastreceiver,                 new intentfilter(config.push_notification));          notificationutils.clearnotifications();     }      @override     protected void onpause() {         localbroadcastmanager.getinstance(this).unregisterreceiver(mregistrationbroadcastreceiver);         super.onpause();     }      /**      * handling new push message, add message      * recycler view , scroll bottom      * */     private void handlepushnotification(intent intent) {         message message = (message) intent.getserializableextra("message");         string userchatroomid = intent.getstringextra("user_id");          if (message != null && userchatroomid != null) {             messagearraylist.add(message);             madapter.notifydatasetchanged();             if (madapter.getitemcount() > 1) {                 recyclerview.getlayoutmanager().smoothscrolltoposition(recyclerview, null, madapter.getitemcount() - 1);             }         }     }      /**      * posting new message in chat room      * make http call our server. our server again sends message      * devices push notification      * */     private void sendmessage() {         final string message = this.inputmessage.gettext().tostring().trim();          if (textutils.isempty(message)) {             toast.maketext(getapplicationcontext(), "enter message", toast.length_short).show();             return;         }           /** create chatroom other user after sending message**/         string endpointinsert = endpoints.chat_room.replace("_id_", selfuserid) + "/" + userchatroomid;         log.e(tag, "endpointinsert: " + endpointinsert);          stringrequest strreque = new stringrequest(request.method.get,                 endpointinsert, new response.listener<string>() {              @override             public void onresponse(string response) {                 log.e(tag, "response: " + response);             }             }, new response.errorlistener() {              @override             public void onerrorresponse(volleyerror error) {                 networkresponse networkresponse = error.networkresponse;                 log.e(tag, "volley error: " + error.getmessage() + ", code: " + networkresponse);                 toast.maketext(getapplicationcontext(), "volley error: " + error.getmessage(), toast.length_short).show();             }         });          date date = new date();         string createdat = new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date);         log.e(tag, "timestamp:" + createdat);          user user = new user(selfuserid, selfusername);          final message msg = new message();         msg.setid("");         msg.setmessage(message);         msg.setcreatedat(createdat);         msg.setuser(user);          messagearraylist.add(msg);          madapter.notifydatasetchanged();         if (madapter.getitemcount() > 1) {             // scrolling bottom of recycler view             recyclerview.getlayoutmanager().smoothscrolltoposition(recyclerview, null, madapter.getitemcount() - 1);         }          //log.e(tag,msg.getid());          string endpoint = endpoints.user_message.replace("_id_", userchatroomid);          log.e(tag, "endpoint: " + endpoint);          this.inputmessage.settext("");          stringrequest strreq = new stringrequest(request.method.post,                 endpoint, new response.listener<string>() {              @override             public void onresponse(string response) {                 log.e(tag, "response: " + response);                  try {                     jsonobject obj = new jsonobject(response);                      // check error                     if (obj.getboolean("error") == false) {                         jsonobject commentobj = obj.getjsonobject("message");                          string commentid = commentobj.getstring("message_id");                         string commenttext = commentobj.getstring("message");                         string createdat = commentobj.getstring("created_at");                          jsonobject userobj = obj.getjsonobject("user");                         string userid = commentobj.getstring("from_user_id");                         string username = userobj.getstring("name");                         user user = new user(userid, username);                          log.e(tag, commentid);                          msg.setid(commentid);                          /*message message = new message();                         message.setid(commentid);                         message.setmessage(commenttext);                         message.setcreatedat(createdat);                         message.setuser(user);*/                          /*messagearraylist.add(msg);                          madapter.notifydatasetchanged();                         if (madapter.getitemcount() > 1) {                             // scrolling bottom of recycler view                             recyclerview.getlayoutmanager().smoothscrolltoposition(recyclerview, null, madapter.getitemcount() - 1);                         }*/                      } else {                         toast.maketext(getapplicationcontext(), "" + obj.getstring("message"), toast.length_long).show();                     }                  } catch (jsonexception e) {                     log.e(tag, "json parsing error: " + e.getmessage());                     toast.maketext(getapplicationcontext(), "json parse error: " + e.getmessage(), toast.length_short).show();                 }             }         }, new response.errorlistener() {              @override             public void onerrorresponse(volleyerror error) {                 networkresponse networkresponse = error.networkresponse;                 log.e(tag, "volley error: " + error.getmessage() + ", code: " + networkresponse);                 toast.maketext(getapplicationcontext(), "volley error: " + error.getmessage(), toast.length_short).show();                 inputmessage.settext(message);             }         }) {              @override             protected map<string, string> getparams() {                 map<string, string> params = new hashmap<string, string>();                 params.put("user_id", myapplication.getinstance().getprefmanager().getuser().getid());                 params.put("message", message);                  log.e(tag, "params: " + params.tostring());                  return params;             };         };           // disabling retry policy won't make         // multiple http calls         int sockettimeout = 0;         retrypolicy policy = new defaultretrypolicy(sockettimeout,                 defaultretrypolicy.default_max_retries,                 defaultretrypolicy.default_backoff_mult);          strreq.setretrypolicy(policy);          //adding request request queue         myapplication.getinstance().addtorequestqueue(strreque);         myapplication.getinstance().addtorequestqueue(strreq);         log.i(tag,msg.getid());     }       /**      * fetching messages of single chat room      * */     private void fetchchatthread() {          string endpointi = endpoints.chat_user_thread.replace("_id_", userchatroomid);         string endpoint = endpointi + "/" + selfuserid;         log.e(tag, "endpoint: " + endpoint);          stringrequest strreq = new stringrequest(request.method.get,                 endpoint, new response.listener<string>() {              @override             public void onresponse(string response) {                 log.e(tag, "response: " + response);                  try {                     jsonobject obj = new jsonobject(response);                      // check error                     if (obj.getboolean("error") == false) {                         jsonarray commentsobj = obj.getjsonarray("messages");                          (int = 0; < commentsobj.length(); i++) {                             jsonobject commentobj = (jsonobject) commentsobj.get(i);                              string commentid = commentobj.getstring("message_id");                             string commenttext = commentobj.getstring("message");                             string createdat = commentobj.getstring("created_at");                              jsonobject userobj = commentobj.getjsonobject("user");                             string userid = userobj.getstring("user_id");                             string username = userobj.getstring("username");                             user user = new user(userid, username);                              message message = new message();                             message.setid(commentid);                             message.setmessage(commenttext);                             message.setcreatedat(createdat);                             message.setuser(user);                              messagearraylist.add(message);                         }                          madapter.notifydatasetchanged();                         if (madapter.getitemcount() > 1) {                             recyclerview.getlayoutmanager().smoothscrolltoposition(recyclerview, null, 1);                         }                         } else {                         toast.maketext(getapplicationcontext(), "" + obj.getjsonobject("error").getstring("message"), toast.length_long).show();                     }                  } catch (jsonexception e) {                     log.e(tag, "json parsing error: " + e.getmessage());                     toast.maketext(getapplicationcontext(), "json parse error: " + e.getmessage(), toast.length_short).show();                 }             }         }, new response.errorlistener() {              @override             public void onerrorresponse(volleyerror error) {                 networkresponse networkresponse = error.networkresponse;                 log.e(tag, "volley error: " + error.getmessage() + ", code: " + networkresponse);                 toast.maketext(getapplicationcontext(), "volley error: " + error.getmessage(), toast.length_short).show();             }         });          //adding request request queue         myapplication.getinstance().addtorequestqueue(strreq);     }  }  package com.wipro.chat.adapter;  /**  * created comp on 17-06-2016.  */ import android.content.context; import android.support.v7.widget.recyclerview; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.textview;  import java.text.parseexception; import java.text.simpledateformat; import java.util.arraylist; import java.util.calendar; import java.util.date;  import com.wipro.chat.r; import com.wipro.chat.model.message;  public class chatroomthreadadapter extends recyclerview.adapter<recyclerview.viewholder> {      private static string tag = chatroomthreadadapter.class.getsimplename();      private string userid;     private int self = 100;     private static string today;      private context mcontext;     private arraylist<message> messagearraylist;      public class viewholder extends recyclerview.viewholder {         textview message, timestamp;          public viewholder(view view) {             super(view);             message = (textview) itemview.findviewbyid(r.id.message);             timestamp = (textview) itemview.findviewbyid(r.id.timestamp);         }     }       public chatroomthreadadapter(context mcontext, arraylist<message> messagearraylist, string userid) {         this.mcontext = mcontext;         this.messagearraylist = messagearraylist;         this.userid = userid;          calendar calendar = calendar.getinstance();         today = string.valueof(calendar.get(calendar.day_of_month));     }      @override     public recyclerview.viewholder oncreateviewholder(viewgroup parent, int viewtype) {         view itemview;          // view type identify render chat message         // left or right         if (viewtype == self) {             // self message             itemview = layoutinflater.from(parent.getcontext())                     .inflate(r.layout.chat_item_self, parent, false);         } else {             // others message             itemview = layoutinflater.from(parent.getcontext())                     .inflate(r.layout.chat_item_other, parent, false);         }           return new viewholder(itemview);     }       @override     public int getitemviewtype(int position) {         message message = messagearraylist.get(position);         if (message.getuser().getid().equals(userid)) {             return self;         }          return position;     }      @override     public void onbindviewholder(final recyclerview.viewholder holder, int position) {         message message = messagearraylist.get(position);         ((viewholder) holder).message.settext(message.getmessage());          string timestamp = gettimestamp(message.getcreatedat());          if (message.getuser().getname() != null)             timestamp = message.getuser().getname() + ", " + timestamp;          ((viewholder) holder).timestamp.settext(timestamp);     }      @override     public int getitemcount() {         return messagearraylist.size();     }      public static string gettimestamp(string datestr) {         simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");         string timestamp = "";          today = today.length() < 2 ? "0" + today : today;          try {             date date = format.parse(datestr);             simpledateformat todayformat = new simpledateformat("dd");             string datetoday = todayformat.format(date);             format = datetoday.equals(today) ? new simpledateformat("hh:mm a") : new simpledateformat("dd lll, hh:mm a");             string date1 = format.format(date);             timestamp = date1.tostring();         } catch (parseexception e) {             e.printstacktrace();         }         return timestamp;     } } 

set setreverselayout=true layoutmanager layout items end.

something this:

linearlayoutmanager layoutmanager = new linearlayoutmanager(this); layoutmanager.setreverselayout(true); recyclerview.setlayoutmanager(linearlayoutmanager); 

edit: reverse data order not scroll recyclerview last item. keeping data order same , scrolling recyclerview last item set setstackfromend=true

sample:

linearlayoutmanager layoutmanager = new linearlayoutmanager(this); layoutmanager.setstackfromend(true); recyclerview.setlayoutmanager(linearlayoutmanager); 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -