java - Android RecyclerView isn't restored on rotate -
when rotate app content disappears, have recyclerview
card list obtains content external db using json , webservice. trying save content in following way:
@override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); if(items != null) { outstate.putparcelablearraylist("items", items); items = null; } } @override protected void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); if (items == null) { items = savedinstancestate.getparcelablearraylist("items"); recycler.setadapter(adapter); } }
but still same problem occurs.
my mainactivity.java
file:
public class mainactivity extends appcompatactivity { drawerlayout drawerlayout; toolbar toolbar; actionbar actionbar; intent intent; private sqlitehandler db; private sessionmanager session; private recyclerview recycler; private recyclerview.adapter adapter; private recyclerview.layoutmanager lmanager; private progressdialog pdialog; jsonparser jparser; private static final string tag_success = "success"; private static final string tag_recipes = "recipes"; private static final string tag_recipe_id = "recipe_id"; private static final string tag_name = "name"; private static final string tag_username = "username"; private static final string tag_photo = "photo"; arraylist<recipe> items; hashmap<string, string> user; string uns; textview usernamesessiontv; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //uns = session.getusername(); intent = getintent(); if (i.hasextra("user")) { bundle bd = getintent().getextras(); if (!bd.getstring("user").equals(null) || bd.getstring("user").trim().length() > 0) { uns = bd.getstring("user"); } } usernamesessiontv = (textview) findviewbyid(r.id.navigation_view).findviewbyid(r.id.usernamesession); items = new arraylist<>(); new loadallrecipes().execute(); recycler = (recyclerview) findviewbyid(r.id.recycler); recycler.sethasfixedsize(true); lmanager = new linearlayoutmanager(this); recycler.setlayoutmanager(lmanager); adapter = new recipeadapter(this, items); recycler.setadapter(adapter); toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); findviewbyid(r.id.fab).setonclicklistener(new view.onclicklistener() { public void onclick(view v) { intent intent = new intent(mainactivity.this, newrecipe.class); intent.putextra("usersession", (string)uns); startactivity(intent); } }); actionbar = getsupportactionbar(); actionbar.sethomeasupindicator(r.drawable.ic_menu_white_24dp); actionbar.setdisplayhomeasupenabled(true); drawerlayout = (drawerlayout) findviewbyid(r.id.navigation_drawer_layout); navigationview navigationview = (navigationview) findviewbyid(r.id.navigation_view); textview usersession = (textview) findviewbyid(r.id.navigation_view).findviewbyid(r.id.usernamesession); usersession.settext(uns); if (navigationview != null) { setupnavigationdrawercontent(navigationview); view header = (view) getlayoutinflater().inflate(r.layout.navigation_drawer_header, null); usernamesessiontv.settext(uns); } setupnavigationdrawercontent(navigationview); adapter.notifydatasetchanged(); db = new sqlitehandler(getapplicationcontext()); session = new sessionmanager(getapplicationcontext()); if (!session.isloggedin()) { logoutuser(); } user = db.getuserdetails(); } @override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); if(items != null) { outstate.putparcelablearraylist("items", items); items = null; } } @override protected void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); if (items == null) { items = savedinstancestate.getparcelablearraylist("items"); recycler.setadapter(adapter); } } @override public boolean oncreateoptionsmenu(menu menu) { return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case android.r.id.home: drawerlayout.opendrawer(gravitycompat.start); return true; } return super.onoptionsitemselected(item); } private void setupnavigationdrawercontent(navigationview navigationview) { navigationview.setnavigationitemselectedlistener( new navigationview.onnavigationitemselectedlistener() { @override public boolean onnavigationitemselected(menuitem menuitem) { switch (menuitem.getitemid()) { case r.id.item_navigation_drawer_allrecipes: menuitem.setchecked(true); drawerlayout.closedrawer(gravitycompat.start); intent = new intent(mainactivity.this, mainactivity.class); intent.putextra("usersession", (string)uns); startactivity(intent); return true; case r.id.item_navigation_drawer_myrecipes: menuitem.setchecked(true); drawerlayout.closedrawer(gravitycompat.start); intent = new intent(mainactivity.this, myrecipes.class); intent.putextra("usersession", (string)uns); startactivity(intent); return true; case r.id.item_navigation_drawer_logout: menuitem.setchecked(true); drawerlayout.closedrawer(gravitycompat.start); logoutuser(); return true; } return true; } }); } public static drawable loadimagefromweboperations(string url) { try { inputstream = (inputstream) new url(url).getcontent(); drawable d = drawable.createfromstream(is, "src name"); return d; } catch (exception e) { return null; } } private void logoutuser() { session.setlogin(false); db.deleteusers(); intent intent = new intent(mainactivity.this, loginactivity.class); startactivity(intent); finish(); } class loadallrecipes extends asynctask<string, string, string> { /** * muestra progress dialog mientras carga. */ @override protected void onpreexecute() { super.onpreexecute(); if (pdialog != null) { pdialog = null; } pdialog = new progressdialog(mainactivity.this); pdialog.setmessage(getresources().getstring(r.string.loadingrecipes)); pdialog.setindeterminate(false); pdialog.setcancelable(false); pdialog.show(); } /** * obtiene todas las recetas desde una url */ protected string doinbackground(string... args) { // construye los parámetros enviar list<namevaluepair> params = new arraylist<namevaluepair>(); jsonarray recipes = new jsonarray(); // obtiene un json string desde la url jparser = new jsonparser(); jsonobject json = jparser.makehttprequest(appconfig.url_get_all_recipes, "get", params); log.d("all recipes: ", json.tostring()); try { // comprueba si devolvió success tag int success = json.getint(tag_success); if (success == 1) { // recetas encontradas // obtiene array de recetas recipes = json.getjsonarray(tag_recipes); // recorre todas las recetas agregándolas al list (int = 0; < recipes.length(); i++) { jsonobject c = recipes.getjsonobject(i); items.add(new recipe(c.getint(tag_recipe_id), c.getstring(tag_photo), c.getstring(tag_name), c.getstring(tag_username))); } pdialog.dismiss(); } else { // no se han encontrado recetas intent = new intent(getapplicationcontext(), newrecipe.class); // cierra todas las activities previas i.addflags(intent.flag_activity_clear_top); startactivity(i); } } catch (jsonexception e) { e.printstacktrace(); } return null; } } }
recipeadapter.java:
public class recipeadapter extends recyclerview.adapter<recipeadapter.recipeviewholder> { private arraylist<recipe> items; private static context context; public view view; public static class recipeviewholder extends recyclerview.viewholder { public int recipe_id; public imageview image; public textview name; public textview username; //public textview method; public textview username; public recipe currentitem; public recipeviewholder(view v) { super(v); v.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(context, recipeactivity.class); intent.putextra("recipe_id", currentitem.getrecipe_id()); context.startactivity(intent); } }); image = (imageview) v.findviewbyid(r.id.recipeimage); name = (textview) v.findviewbyid(r.id.recipename); //username = (textview) v.findviewbyid(r.id.username); //method = (textview) v.findviewbyid(r.id.recipemethod); username = (textview) v.findviewbyid(r.id.username); } /*@override public void onclick(adapterviewcompat<?> parent, view view, int position, long id) { intent intent = new intent(context, recipeactivity.class); context.startactivity(intent); }*/ } public recipeadapter(context context, arraylist<recipe> items) { this.context = context; this.items = items; } private string[] mdataset; public recipeadapter(string[] dataset) { mdataset = dataset; } public interface onitemclicklistener { public void onitemclick(view view , int position); } @override public recipeviewholder oncreateviewholder(viewgroup viewgroup, int i) { view v = layoutinflater.from(viewgroup.getcontext()).inflate(r.layout.recipe_card, viewgroup, false); recipeviewholder vh = new recipeviewholder(v); return vh; } @override public void onbindviewholder(recipeviewholder viewholder, int i) { viewholder.recipe_id = items.get(i).getrecipe_id(); //viewholder.image.setimageresource(items.get(i).getimage()); new downloadimagetask((imageview) viewholder.image).execute(items.get(i).getimage()); viewholder.name.settext(items.get(i).getname()); viewholder.username.settext(context.getresources().getstring(r.string.usertag)+" "+string.valueof(items.get(i).getusername())); viewholder.currentitem = items.get(i); } private class downloadimagetask extends asynctask<string, void, bitmap> { imageview bmimage; public downloadimagetask(imageview bmimage) { this.bmimage = bmimage; } protected bitmap doinbackground(string... urls) { string urldisplay = urls[0]; bitmap imagebm = null; try { inputstream in = new java.net.url(urldisplay).openstream(); imagebm = bitmapfactory.decodestream(in); } catch (exception e) { log.e("error", e.getmessage()); e.printstacktrace(); } return imagebm; } protected void onpostexecute(bitmap result) { bmimage.setimagebitmap(result); } } @override public int getitemcount() { return items.size(); } } recipe.java: public class recipe implements parcelable { private int recipe_id; private string image; private string name; private string username; private string method; public recipe(int recipe_id, string imagen, string name, string username) { this.recipe_id = recipe_id; this.image = imagen; this.name = name; this.username = username; this.method = method; } public int getrecipe_id() { return recipe_id; } public string getname() { return name; } public string getusername() { return username; } public string getmethod() { return method; } public string getimage() { return image; } @override public int describecontents() { return 0; } @override public void writetoparcel(parcel parcel, int i) { parcel.writestring(name); parcel.writestring(method); parcel.writestring(username); parcel.writestring(image); } }
Comments
Post a Comment