android - My list is loading again when I am Pressing Back Button -


i getting arraylistindexoutofbound when pressing list item when orientation changed.as far knowledge of android have written parcelable code correctly.but think issues recycler view setup.i confused 2 declaration of adapter.help me

mainactivity.class

 package com.reader.ashishyadav271.hackernewsmaterial;   import android.content.context; import android.content.intent; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.database.sqlite.sqlitestatement; import android.net.connectivitymanager; import android.net.networkinfo; import android.os.asynctask; import android.os.bundle; import android.os.parcelable; import android.os.persistablebundle; import android.support.v4.util.lrucache; import android.support.v7.app.appcompatactivity; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.support.v7.widget.toolbar; import android.util.log; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.listview; import android.widget.toast;  import com.wang.avi.avloadingindicatorview;  import org.json.jsonarray; import org.json.jsonobject;  import java.io.inputstream; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.url; import java.text.simpledateformat; import java.util.arraylist; import java.util.date; import java.util.hashmap; import java.util.list; import java.util.map;  public class mainactivity extends appcompatactivity implements mycustomadapter.clicklistener {      private static final string state_list = "state_list";     map<integer, string> articleurls = new hashmap<>();     map<integer, string> articletitles = new hashmap<>();     map<integer, string> articledates =new hashmap<>();     map<integer, string> articleauthors =new hashmap<>();     arraylist<integer> articleids=new arraylist<>();      sqlitedatabase articlesdb;      arraylist<information> data=new arraylist<>();      arraylist<string> titles=new arraylist<>();     arraylist<string> urls=new arraylist<>();     arraylist<string> authors=new arraylist<>();     arraylist<string> dateandtimes=new arraylist<>();     mycustomadapter adapter;     recyclerview recyclerview;     avloadingindicatorview av;     list<downloadtask> tasks;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);          av= (avloadingindicatorview) findviewbyid(r.id.avloadingindicatorview);         av.setvisibility(view.invisible);         tasks = new arraylist<>();          toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar);         setsupportactionbar(toolbar);          recyclerview= (recyclerview) findviewbyid(r.id.recyclerview);         recyclerview.setlayoutmanager(new linearlayoutmanager(getapplicationcontext()));          recyclerview.additemdecoration(new simpledivideritemdecoration(                 getapplicationcontext()         ));            articlesdb = this.openorcreatedatabase("articles", mode_private, null);          articlesdb.execsql("create table if not exists article (id integer primary key," +                 " articleid integer," +                 " url varchar," +                 " title varchar," +                 " author varchar," +                 " date varchar)");          if(savedinstancestate != null) {              data=savedinstancestate.getparcelablearraylist(state_list);             adapter=new mycustomadapter(getapplicationcontext(),data);             adapter.setclicklistener(this);             recyclerview.setadapter(adapter);           }else{             if (isonline()) {                  requestdata("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty");             } else {                 updatedisplay();                 toast.maketext(this, "network isn't available", toast.length_long).show();             }          }          //adapter=new mycustomadapter(getapplicationcontext(),getdata());         //adapter.setclicklistener(this);         //recyclerview.setadapter(adapter);     }       protected boolean isonline() {         connectivitymanager cm = (connectivitymanager) getsystemservice(context.connectivity_service);         networkinfo netinfo = cm.getactivenetworkinfo();         if (netinfo != null && netinfo.isconnectedorconnecting()) {             return true;         } else {             return false;         }     }      private void requestdata(string uri) {         downloadtask task = new downloadtask();         task.execute(uri);     }      @override     public void itemclicked(view view, int position) {         intent = new intent(getapplicationcontext(), main2activity.class);         i.putextra("articleurl", urls.get(position));         startactivity(i);      }      protected void updatedisplay() {         adapter=new mycustomadapter(getapplicationcontext(),getdata());         adapter.setclicklistener(this);         recyclerview.setadapter(adapter);;     }      @override     protected void onsaveinstancestate(bundle outstate) {         super.onsaveinstancestate(outstate);          outstate.putparcelablearraylist(state_list, data);      }      public class downloadtask extends asynctask<string, void, string> {         @override         protected void onpreexecute() {             super.onpreexecute();             if (tasks.size() == 0) {                 av.setvisibility(view.visible);             }             tasks.add(this);         }          @override         protected string doinbackground(string... urls) {              string result = "";             url url;             httpurlconnection urlconnection;              try {                  url = new url(urls[0]);                  urlconnection = (httpurlconnection) url.openconnection();                  inputstream in = urlconnection.getinputstream();                  inputstreamreader reader = new inputstreamreader(in);                  int data = reader.read();                  while (data != -1) {                      char current = (char) data;                      result += current;                      data = reader.read();                  }                  jsonarray jsonarray = new jsonarray(result);                  articlesdb.execsql("delete article");                  (int = 0; < 15; i++) {                      string articleid = jsonarray.getstring(i);                      url = new url("https://hacker-news.firebaseio.com/v0/item/" + articleid + ".json?print=pretty");                      urlconnection = (httpurlconnection) url.openconnection();                      in = urlconnection.getinputstream();                      reader = new inputstreamreader(in);                      data = reader.read();                      string articleinfo = "";                      while (data != -1 ) {                          char current = (char) data;                          articleinfo += current;                          data = reader.read();                      }                      jsonobject jsonobject = new jsonobject(articleinfo);                      string articletitle = jsonobject.getstring("title");                      string articleurl = jsonobject.getstring("url");                      string articledate=jsonobject.getstring("time");                      string articleauthor=jsonobject.getstring("by");                       long unixseconds = long.valueof(articledate);                     date date = new date(unixseconds*1000l); // *1000 convert seconds milliseconds                     simpledateformat sdf = new simpledateformat("dd/mm/yyyy hh:mm:ss"); // format of date                     string formattedarticledate = sdf.format(date);                      articleids.add(integer.valueof(articleid));                     articletitles.put(integer.valueof(articleid), articletitle);                     articleurls.put(integer.valueof(articleid), articleurl);                     articledates.put(integer.valueof(articleid), formattedarticledate);                     articleauthors.put(integer.valueof(articleid), articleauthor);                      string sql = "insert article (articleid, url, title, author, date) values (? , ? , ? , ?, ?)";                       sqlitestatement statement = articlesdb.compilestatement(sql);                      statement.bindstring(1, articleid);                     statement.bindstring(2, articleurl);                     statement.bindstring(3, articletitle);                     statement.bindstring(4, articleauthor);                     statement.bindstring(5, formattedarticledate);                      statement.execute();                    }               }catch (exception e) {                  e.printstacktrace();              }               return result;         }          @override         protected void onpostexecute(string s) {             super.onpostexecute(s);             tasks.remove(this);             if (tasks.size() == 0) {                 av.setvisibility(view.invisible);             }             updatedisplay();         }     }      private list<information> getdata() {         /*list<information> data=new arraylist<>();         for(int i=0;i<20;i++){             titles.add(i,"wikileaks asssange wins un ruling on arbitrary detention");             url.add(i,"https://www.google.co.in/search?q=best+custom+list+row");             date.add(i,"3 hrs");             author.add(i,"aburan28");         }         for(int i=0;i<20;i++){             information current=new information();             current.title=titles.get(i);             current.url=url.get(i);             current.author=author.get(i);             current.date=date.get(i);             data.add(current);         }         return data;*/          cursor c = articlesdb.rawquery("select * article", null);          try {             int urlindex = c.getcolumnindex("url");             int titleindex = c.getcolumnindex("title");             int authorindex = c.getcolumnindex("author");             int dateindex = c.getcolumnindex("date");              c.movetofirst();              titles.clear();             //urls.clear();             authors.clear();             dateandtimes.clear();               int i=0;             while (c != null) {                 titles.add(c.getstring(titleindex));                 urls.add(c.getstring(urlindex));                 authors.add(c.getstring(authorindex));                 dateandtimes.add(c.getstring(dateindex));                 information current=new information();                 current.title=titles.get(i);                 current.url=urls.get(i);                 current.author=authors.get(i);                 current.date = dateandtimes.get(i);                 data.add(current);                 i++;                 c.movetonext();              }           }catch (exception e) {              e.printstacktrace();          }finally {             c.close();         }         return data;     }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.menu_main, menu);         return true;     }      @override     public boolean onoptionsitemselected(menuitem item) {         // handle action bar item clicks here. action bar         // automatically handle clicks on home/up button, long         // specify parent activity in androidmanifest.xml.         int id = item.getitemid();          //noinspection simplifiableifstatement         if (id == r.id.action_settings) {             startactivity(new intent(getapplicationcontext(),settingsactivity.class));             return true;         }         if (id == r.id.action_about) {             startactivity(new intent(getapplicationcontext(),about.class));             return true;         }         return super.onoptionsitemselected(item);     } } 

information.class

package com.reader.ashishyadav271.hackernewsmaterial;  import android.os.parcel; import android.os.parcelable;  public class information implements parcelable {     public string title;     public string author;     public string date;     public string url;      public information(){      }      protected information(parcel in) {         title = in.readstring();         author = in.readstring();         date = in.readstring();         url = in.readstring();     }      public static final creator<information> creator = new creator<information>() {         @override         public information createfromparcel(parcel in) {             return new information(in);         }          @override         public information[] newarray(int size) {             return new information[size];         }     };      @override     public int describecontents() {         return 0;     }      @override     public void writetoparcel(parcel dest, int flags) {         dest.writestring(title);         dest.writestring(author);         dest.writestring(date);         dest.writestring(url);     } } 

log cat error

02-06 14:52:58.106 8369-8369/com.reader.ashishyadav271.hackernewsmaterial e/androidruntime: fatal exception: main process: com.reader.ashishyadav271.hackernewsmaterial, pid: 8369 java.lang.indexoutofboundsexception: invalid index 0, size 0     @ java.util.arraylist.throwindexoutofboundsexception(arraylist.java:255)     @ java.util.arraylist.get(arraylist.java:308)     @ com.reader.ashishyadav271.hackernewsmaterial.mainactivity.itemclicked(mainactivity.java:137)     @ com.reader.ashishyadav271.hackernewsmaterial.mycustomadapter$myviewholder.onclick(mycustomadapter.java:77)     @ android.view.view.performclick(view.java:4471)     @ android.view.view$performclick.run(view.java:18778)     @ android.os.handler.handlecallback(handler.java:808)     @ android.os.handler.dispatchmessage(handler.java:103)     @ android.os.looper.loop(looper.java:193)     @ android.app.activitythread.main(activitythread.java:5345)     @ java.lang.reflect.method.invokenative(native method)     @ java.lang.reflect.method.invoke(method.java:515)     @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:828)     @ com.android.internal.os.zygoteinit.main(zygoteinit.java:644)     @ dalvik.system.nativestart.main(native method) 

now after years.i have used. flag_activity_clear_top - if set, , activity being launched running in current task, instead of launching new instance of activity, of other activities on top of closed , intent delivered (now on top) old activity new intent.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -