android - Can I not use SharedPreference inside a constructor? -


i'm using simple class perform actions (calculations) , want write value in sharedpreferences may later used.

however, not working. extended class activity can use getsharedpreferences() method. incorrect , not allowed?

i'm getting null pointer exception trying initialize sharedpreference editor

code below:

public class jsonparser extends activity {      // store our preferences json route info     public static final string my_prefs_json = "jsonprefs";      // construct object json values     public jsonparser(string jsonstring){          try {             jsonobject jsonobject = new jsonobject(jsonstring);             jsonarray routesarray = jsonobject.getjsonarray("routes");              // fails nullpointer                         sharedpreferences.editor editor = getsharedpreferences(my_prefs_json, mode_private).edit();               // store in sharedpreferences our json value             editor.putstring("json", routesarray.tostring());             editor.commit();         }     } } 

adding error message:

java.lang.nullpointerexception: attempt invoke virtual method 'android.content.sharedpreferences android.content.context.getsharedpreferences(java.lang.string, int)' on null object reference

the activity context not created till oncreate() gets invoked. so, if want involves context in oncreate().

@override     protected void oncreate(bundle savedinstancestate) {          try {             jsonobject jsonobject = new jsonobject(jsonstring);             jsonarray routesarray = jsonobject.getjsonarray("routes");              // fails nullpointer                         sharedpreferences.editor editor = getsharedpreferences(my_prefs_json, mode_private).edit();               // store in sharedpreferences our json value             editor.putstring("json", routesarray.tostring());             editor.commit();         }     } 

so in case - pass jsonstring activity using intent.putextra() when starting activity , fetch in oncreate() using getintent().getstringextra()


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -