android - java.lang.NullPointerException when resume activity in viewpager -
i resume activity have stored in share preferences in viewpager. have stored activity details in onsavestate , retrieve activity getpreferences in onresume. somehow, returns error key in null value in onsavestate. how save preferences in viewpager ?
here code
public class fullscreenimageactivity extends appcompatactivity { viewpager viewpager; imageview favbtn; private sharedpreference sharedpreference; activity context = this; private fragment contentfragment; @targetapi(build.version_codes.gingerbread) public void oncreate(bundle savedinstancestate) { this.requestwindowfeature(window.feature_no_title); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_fullscreen_image); //tbs fragmentmanager fragmentmanager = getsupportfragmentmanager(); if (build.version.sdk_int > 9) { strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build(); strictmode.setthreadpolicy(policy); } if (savedinstancestate.containskey("content")) { string content = savedinstancestate.getstring("content"); if (content.equals(favouritelistfragment.arg_item_id)) { if (fragmentmanager.findfragmentbytag(favouritelistfragment.arg_item_id) != null) { contentfragment = fragmentmanager .findfragmentbytag(favouritelistfragment.arg_item_id); } } } intent = getintent(); int position = i.getintextra("position", 0); string[] arr=i.getstringarrayextra("array"); string url = i.getstringextra("url"); sharedpreference = new sharedpreference(); viewpager = (viewpager) findviewbyid(r.id.slider); viewpager.setadapter(new galleryviewpageradapter(this, arr, position, url)); viewpager.setcurrentitem(position); } class galleryviewpageradapter extends pageradapter { private context context; layoutinflater inflater; private string[] imagearraylist; private string murl; private int mposition; private progressdialog mprogress; public galleryviewpageradapter(context _context, string[] imagearraylist, int position, string url) { context = _context; this.imagearraylist = imagearraylist; //null; this.mposition=position; inflater = (layoutinflater) context.getsystemservice(context.layout_inflater_service); murl=url; } @override public int getcount() { return imagearraylist.length; } @override public object instantiateitem(final viewgroup container, final int position) { showprogress(); favbtn = (imageview) findviewbyid(r.id.btn_favourite); string favoriteurl=sharedpreference.getprefsfavurl(context); //boolean statebtnnow=sharedpreference.getbtnstate(context,murl);//why murl change same url favourite boolean statebtnnow=false; if(statebtnnow) { favbtn.setcolorfilter(color.argb(255, 249, 0, 0));//red } else { favbtn.setcolorfilter(color.argb(255, 192, 192, 192)); } favbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { //boolean statebtn = sharedpreference.getbtnstate(context, murl); boolean statebtn=false; if (!statebtn) { sharedpreference.save(context, murl); //edit save url in array //sharepreference.add(context, product); sharedpreference.savebtnstate(context, statebtn); toast.maketext(context, "added favourite!", toast.length_short).show(); favbtn.setcolorfilter(color.argb(255, 249, 0, 0));//red toast.maketext(context, "button state " + statebtn, toast.length_short).show(); } else { sharedpreference.savebtnstate(context, statebtn); favbtn.setcolorfilter(color.argb(255, 192, 192, 192));//grey } } }); view photorow = inflater.inflate(r.layout.item_fullscreen_image, container, false); touchimageview fullscreenimg; fullscreenimg =(touchimageview)photorow.findviewbyid(r.id.img_flickr); // added imageloader better performance staggereddemoapplication.getimageloader().get(imagearraylist[position], imageloader.getimagelistener(fullscreenimg, r.drawable.bg_no_image, android.r.drawable.ic_dialog_alert), container.getwidth(), 0); ((viewpager) container).addview(photorow); stopprogress(); return photorow; } private void stopprogress() { mprogress.cancel(); } private void showprogress() { mprogress = progressdialog.show(fullscreenimageactivity.this, "", "loading..."); } @override public boolean isviewfromobject(view view, object object) { return view == ((relativelayout) object); } @override public void destroyitem(viewgroup container, int position, object object) { // remove viewpager_item.xml viewpager ((viewpager) container).removeview((relativelayout) object); } } @override protected void onsaveinstancestate(bundle outstate) { outstate.putstring("content", favouritelistfragment.arg_item_id); super.onsaveinstancestate(outstate); } @override public void onresume() { super.onresume(); } }
here code in sharepreferences
public class sharedpreference { public static final string prefs_name = "aop_prefs"; public static final string prefs_state="aop_btn"; public static final string prefs_fav_url="aop_fav_url"; public static final string prefs_key = "aop_prefs_string"; public static final string pref_btn_key = "aop_pref_btn"; public static final string pref_url_key = "aop_pref_url"; public sharedpreference() { super(); } public void save(context context, string text) { sharedpreferences settings; editor editor; //edit here add image array list //settings = preferencemanager.getdefaultsharedpreferences(context); settings = context.getsharedpreferences(prefs_name, context.mode_private); //1 editor = settings.edit(); //2 editor.putstring(prefs_key, text); //3 editor.commit(); //4 } public string getvalue(context context) { sharedpreferences settings; string text; //settings = preferencemanager.getdefaultsharedpreferences(context); settings = context.getsharedpreferences(prefs_name, context.mode_private); text = settings.getstring(prefs_key, null); return text; } public string getprefsfavurl(context context){ sharedpreferences settings; string favurl; settings = context.getsharedpreferences(prefs_fav_url, context.mode_private); favurl = settings.getstring(pref_url_key, null); return favurl; } public void clearsharedpreference(context context) { sharedpreferences settings; editor editor; //settings = preferencemanager.getdefaultsharedpreferences(context); settings = context.getsharedpreferences(prefs_name, context.mode_private); editor = settings.edit(); editor.clear(); editor.commit(); } public void removevalue(context context) { sharedpreferences settings; editor editor; settings = context.getsharedpreferences(prefs_name, context.mode_private); editor = settings.edit(); editor.remove(prefs_key); editor.commit(); } public void savebtnstate(context context, boolean statebtn) { sharedpreferences settings; editor editor; //settings = preferencemanager.getdefaultsharedpreferences(context); settings = context.getsharedpreferences(prefs_state, context.mode_private); //1 editor = settings.edit(); //2 editor.putboolean(pref_btn_key, statebtn);//added state button editor.commit(); //4 } public boolean getbtnstate(context context,string text)//edit store url here , check boolean here { sharedpreferences prefs; prefs = context.getsharedpreferences(prefs_name, context.mode_private); string favurl = getprefsfavurl(context); boolean switchstate = false; if(favurl.equals(text)) { switchstate=true; } return switchstate; } public void savefavourite(fragmentactivity activity, string favouriteurl) { sharedpreferences settings; editor editor; settings = activity.getsharedpreferences(prefs_fav_url, context.mode_private); //1 editor = settings.edit(); //2 editor.putstring(pref_url_key, favouriteurl); //3 editor.commit(); //4 } }
here error log file
02-03 09:48:57.928 15368-15368/com.example.myapp w/system.err: java.lang.nullpointerexception: attempt invoke virtual method 'java.lang.object java.lang.class.newinstance()' on null object reference 02-03 09:48:57.928 15368-15368/com.example.myapp w/system.err: @ com.example.myapp.mainactivity.displayview(mainactivity.java:141) 02-03 09:48:57.928 15368-15368/com.example.myapp w/system.err: @ com.example.myapp.mainactivity.oncreate(mainactivity.java:41) 02-03 09:48:57.928 15368-15368/com.example.myapp w/system.err: @ android.app.activity.performcreate(activity.java:5990)
here mainactivity program
public class mainactivity extends appcompatactivity implements navigationview.onnavigationitemselectedlistener, fragmentflickrgridimage.onfragmentinteractionlistener, shareactionprovider.onsharetargetselectedlistener { private int backstack_count; private boolean viewisathome; private fragment contentfragment; private shareactionprovider share; private intent shareintent=new intent(intent.action_send); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); if (savedinstancestate == null) { displayview(r.id.recent_picture); } drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout); actionbardrawertoggle toggle = new actionbardrawertoggle( this, drawer, toolbar, r.string.navigation_drawer_open, r.string.navigation_drawer_close); drawer.setdrawerlistener(toggle); toggle.syncstate(); navigationview navigationview = (navigationview) findviewbyid(r.id.nav_view); navigationview.setitemicontintlist(null); navigationview.setnavigationitemselectedlistener(this); shareintent.settype("text/plain"); } private void replacefragment(fragment fragment, boolean isaddtobackstack) { fragmenttransaction transaction = getsupportfragmentmanager().begintransaction(); transaction.replace(r.id.flcontent, fragment); if (isaddtobackstack) { transaction.addtobackstack(fragment.getclass().tostring()); backstack_count ++; } transaction.commit(); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); menuitem item = menu.finditem(r.id.share); share = new shareactionprovider(this); menuitemcompat.setactionprovider(item, share); return(super.oncreateoptionsmenu(menu)); } @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(); if (id == r.id.share) { onshareaction(); return true; } return super.onoptionsitemselected(item); } private void onshareaction() { string yoursharetext = "test"; intent shareintent = sharecompat.intentbuilder.from(this).settype("text/plain").settext(yoursharetext).getintent(); // set share intent if (share != null) { share.setshareintent(shareintent); } } @suppresswarnings("statementwithemptybody") @override public boolean onnavigationitemselected(menuitem item) { // handle navigation view item clicks here. int id = item.getitemid(); displayview(item.getitemid()); return true; } private void displayview(int itemid) { fragment fragment = null; class fragmentclass = null; string title=""; switch (itemid){ case r.id.one: fragment = new fragmentflickrgridimage("one"); title="one"; viewisathome=true; break; case r.id.two: fragment = new fragmentflickrgridimage(" two"); title ="two"; viewisathome=false; break; case r.id.three: fragment = new fragmentflickrgridimage("three"); title="three"; viewisathome=false; break; case r.id.four: fragment=new favouritelistfragment(); title="favourite"; viewisathome=false; break; } try { fragment = (fragment) fragmentclass.newinstance(); } catch (exception e) { e.printstacktrace(); } fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragmentmanager.begintransaction().replace(r.id.flcontent, fragment).commit(); getsupportactionbar().settitle(title); drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout); drawer.closedrawer(gravitycompat.start); } @override public void onfragmentinteraction(uri uri) { } @override public void onbackpressed() { drawerlayout drawer = (drawerlayout) findviewbyid(r.id.drawer_layout); if (drawer.isdraweropen(gravitycompat.start)) { drawer.closedrawer(gravitycompat.start); } if (!viewisathome) { //if current view not recent hot girl fragment displayview(r.id.recent_picture); } else { dialoginterface.onclicklistener dialogclicklistener = new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int which) { switch (which){ case dialoginterface.button_positive: //yes button clicked finish(); break; case dialoginterface.button_negative: //no button clicked break; } } }; alertdialog.builder builder = new alertdialog.builder(this) .setmessage("are sure?") .setpositivebutton("yes", dialogclicklistener) .setnegativebutton("no", dialogclicklistener) .setcancelable(false) .settitle("exit"); builder.show(); } } @override public boolean onsharetargetselected(shareactionprovider source, intent intent) { toast.maketext(this, intent.getcomponent().tostring(), toast.length_long).show(); return(false); } }
the error line is:
fragment = (fragment) fragmentclass.newinstance();
fragmentclass
assigned null
object when use in fragmentclass.newinstance()
, , have null
value because never assign other value. try remove these lines:
try { fragment = (fragment) fragmentclass.newinstance(); } catch (exception e) { e.printstacktrace(); }
anyway, using non-empty constructor fragments not practice. should use this pattern instead.
edit
check whether fragment empty or not:
if (fragment != null){ fragmentmanager fragmentmanager = getsupportfragmentmanager(); fragmentmanager.begintransaction().replace(r.id.flcontent, fragment).commit(); }
Comments
Post a Comment