Android getting empty first activity when device is rotated is Second Activity and back button is pressed beside using LoaderManager in First Activity -


the title of question might bit confusing being beginner find tough write accurate title. coming point making app fetches data google books api , shows them in recyclerview. data loaded in recyclerview after click of search button. when click on individual item of adapter opens detailactivity. app works fine if rotate device in mainactivity if rotate device in detailactivity , press button mainactivity adapter empty. mainactivity.java

package com.example.setha.booklisting;  import android.app.loadermanager; import android.content.context; import android.content.intent; import android.content.loader; import android.net.connectivitymanager; import android.net.networkinfo; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.util.log; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.textview; import android.widget.toast;  import java.util.arraylist; import java.util.list;  public class mainactivity extends appcompatactivity implements loadermanager.loadercallbacks<list<books>> {      public static final string log_tag = mainactivity.class.getname();     private static final int books_loader_id = 1;     private static final string book_list = "book in list";      private recyclerview.adapter adapter;     private recyclerview recyclerview;     private textview emptyview;     private list<books> books_list;     private string book_searched = "";      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          setcontentview(r.layout.activity_main);          log.i(log_tag, "test: oncreate() called ...");          //calling adapter on empty book list         recyclerview = (recyclerview) findviewbyid(r.id.recyclerview);         recyclerview.sethasfixedsize(false);         recyclerview.setlayoutmanager(new linearlayoutmanager(mainactivity.this));         adapter = new myadapter(new arraylist<books>());         recyclerview.setadapter(adapter);          button searchbutton = (button) findviewbyid(r.id.button_search);          searchbutton.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view view) {                 log.i(log_tag, "test: search button clicked ...");                 book_searched = getsearchterm();                 log.i(log_tag, "test: " + book_searched);                 if (!book_searched.equals("")) {                      view loadingindicator = findviewbyid(r.id.loading_spinner);                     loadingindicator.setvisibility(view.visible);                      emptyview = (textview) findviewbyid(r.id.emptylist);                      getloadermanager().restartloader(books_loader_id, null, mainactivity.this);                      recyclerview.addonitemtouchlistener(                             new recycleritemclicklistener(mainactivity.this, recyclerview, new recycleritemclicklistener.onitemclicklistener() {                                 @override                                 public void onitemclick(view view, int position) {                                     if (isonline()) {                                         log.i(log_tag, "test: detail activity clicked ...");                                         books book = books_list.get(position);                                         intent = new intent(mainactivity.this, detailactivity.class);                                         i.putextra("imagelink", book.getimageurl());                                         i.putextra("title", book.gettitle());                                         i.putextra("authors", book.getwriter());                                         i.putextra("description", book.getdescription());                                         i.putextra("infolink", book.getinfolink());                                         startactivity(i);                                     }                                     else {                                         toast.maketext(mainactivity.this,"no internet connection",toast.length_short).show();                                     }                                 }                                  @override                                 public void onlongitemclick(view view, int position) {                                     // whatever                                 }                             })                     );                 }             }         });         getloadermanager();         log.i(log_tag, "test: oncreate() finish ...");     }      //update adapter books data     private void updateui(list<books> books) {         adapter = new myadapter(books);         recyclerview.setadapter(adapter);     }      @override     public loader<list<books>> oncreateloader(int i, bundle bundle) {         log.i(log_tag, "test: oncreateloader called ...");         return new bookloader(mainactivity.this, book_searched);     }      @override     public void onloadfinished(loader<list<books>> loader, list<books> books) {         books_list = books;         log.i(log_tag, "test: onloaderfinished called ...");         // hide loading indicator because data has been loaded         view loadingindicator = findviewbyid(r.id.loading_spinner);         loadingindicator.setvisibility(view.gone);          if (books == null) {             emptyview.settext("no books found");             emptyview.setvisibility(view.visible);         }          if (isonline()) {             //code if online             if (books != null) {                 emptyview.setvisibility(view.gone);                 updateui(books);             }         } else {             books = new arraylist<>();             updateui(books);             emptyview.settext("no internet connection");             emptyview.setvisibility(view.visible);         }      }      @override     public void onloaderreset(loader<list<books>> loader) {         log.i(log_tag, "test: onloaderreset called ...");         new myadapter(new arraylist<books>());     }      //helper method check device connected internet or not     public boolean isonline() {         connectivitymanager conmgr = (connectivitymanager) getsystemservice(context.connectivity_service);         networkinfo netinfo = conmgr.getactivenetworkinfo();          if (netinfo == null || !netinfo.isconnected() || !netinfo.isavailable()) {              return false;         }         return true;     }      public string getsearchterm() {         edittext search_term = (edittext) findviewbyid(r.id.text_search_term);         book_searched = search_term.gettext().tostring();         book_searched = book_searched.replace(' ', '+');         return book_searched;     } } 

`

detailactivity.java

    package com.example.setha.booklisting;  import android.content.intent; import android.net.uri; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.imageview; import android.widget.textview;  import com.squareup.picasso.picasso;  import java.util.arraylist;  public class detailactivity extends appcompatactivity {      private string imagelink;     private string title;     private arraylist<string> authors;     private string details;     private string infolink;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_detail);          bundle b = getintent().getextras();         imagelink = b.getstring("imagelink");         title = b.getstring("title");         authors = b.getstringarraylist("authors");         details = b.getstring("description");         infolink = b.getstring("infolink");          //code show image of book         imageview imageview = (imageview) findviewbyid(r.id.img_thumbnail);         picasso.with(getbasecontext()).load(imagelink).into(imageview);          textview title_textview = (textview) findviewbyid(r.id.text_title);         title_textview.settext(title);          //code show authors of book         stringbuilder list_authors = new stringbuilder();         for(string author : authors){             list_authors.append(author + ", ");         }         textview authors_textview = (textview) findviewbyid(r.id.text_authors);         authors_textview.settext(list_authors.tostring().substring(0,list_authors.length()-2));          textview details_textview = (textview) findviewbyid(r.id.text_description);         details_textview.settext(details);          button moreinfo = (button) findviewbyid(r.id.more_info_button);         moreinfo.setonclicklistener(new view.onclicklistener() {             @override             public void onclick(view view) {                 uri webpage = uri.parse(infolink);                 intent intent = new intent(intent.action_view, webpage);                 startactivity(intent);             }         });     } } 

bookloader

    package com.example.setha.booklisting;  import android.content.asynctaskloader; import android.content.context; import android.util.log;  import java.util.list;  /**  * created setha on 14-08-2017.  */  public class bookloader extends asynctaskloader<list<books>> {      private string log_tag = bookloader.class.getsimplename();     private static final string google_books_api_request_url =             "https://www.googleapis.com/books/v1/volumes?q=&maxresults=40&key=aizasyaspsjnbnpmnf_eq03by1ioalftzsbpu14";     private string search_term;      public bookloader(context context, string search_term) {         super(context);         this.search_term = search_term;     }      @override     protected void onstartloading() {         forceload();     }      @override     public list<books> loadinbackground() {         log.i(log_tag,"test: loadinbackground() called ...");          string str = google_books_api_request_url;         int index_to_add_search_term = str.indexof("?q=");         string url = str.substring(0,index_to_add_search_term + 3) + search_term + str.substring(index_to_add_search_term + 3);         string[] urls = {url};         log.i(log_tag,"test: url " + url);         // don't perform request if there no urls, or first url null.         if (urls.length < 1 || urls[0] == null) {             return null;         }         return utils.fetchbooksdata(urls[0]);     } } 

using bunch of log message figured out on device rotation in second activity followed button set loader in first activity null. have initialize loader when loader set null call loadinbackground method load data. here code snippet solved problem.

//this handle case of recyclerview getting empty on rotation. reload recyclerview fetched loader data without calling loadinbackground method     if (getloadermanager().getloader(books_loader_id) != null) {         log.i(log_tag, "test: loader showing fetched data ...");         getloadermanager().initloader(books_loader_id, null, mainactivity.this);         onsinglebooktouchlistener();     }     //this handle case of loader being set null if rotate device in detailactivity (e.g if in mainactivity device in portrait mode , clicking on recyclerview item start detailactivity. if rotate device in detail activity landscape mode , press button mainactivity recyclerview gets empty). restart loader.     else {         log.i(log_tag, "test: loadermanager reloaded ...");         if (!book_searched.equals("")) {             getloadermanager().initloader(books_loader_id, null, mainactivity.this);             onsinglebooktouchlistener();         }     }     log.i(log_tag, "test: oncreate() finish ..."); } 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -