1

I am saving the value in sharedPreferences in one Class and trying to access it from another class but get null pointer exception. the value that i enter is url for web service. please help me.

UrlSetting.java

public class UrlSetting extends Activity {
EditText editUrl;
TextView Savedurl;
Button bSaveUrl, bback;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.urlsetting);

    Savedurl = (TextView)findViewById(R.id.savedurl);
    editUrl = (EditText)findViewById(R.id.editurl);
    bback = (Button)findViewById(R.id.back);
    bSaveUrl = (Button)findViewById(R.id.saveurl);
    bSaveUrl.setOnClickListener(buttonSaveUrlOnClickListener);
    bback.setOnClickListener(new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(UrlSetting.this, Login.class);
            /*intent.setClass(UrlSetting.this, Login.class);*/
            startActivity(intent);
        }});

    LoadPreferences();
}
Button.OnClickListener buttonSaveUrlOnClickListener
= new Button.OnClickListener(){

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        SavePreferences("URL", editUrl.getText().toString());
        LoadPreferences();
    }

private void SavePreferences(String key, String value){
    SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}

private void LoadPreferences(){
    SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
    String strSavedurl = sharedPreferences.getString("URL", "");
    Savedurl.setText(strSavedurl);
}

and this is my Koneksi.java

public class Koneksi{

SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String url = sharedPreferences.getString("URL", "");
public Koneksi(String urlml){

    url= url + urlml;
}

public String getUrl(){

    return url;
}

this is the LogCat

> 05-21 11:39:44.542: W/KeyCharacterMap(339): No keyboard for id 0
05-21 11:39:44.542: W/KeyCharacterMap(339): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-21 11:39:51.826: D/TryLoginCheck(339): Here
05-21 11:39:51.826: I/System.out(339): UserNametes
05-21 11:39:51.831: I/System.out(339): passwordTes12345*
05-21 11:39:51.831: D/Parameters(339): username=tes&password=Tes12345*
05-21 11:39:51.831: D/AndroidRuntime(339): Shutting down VM
05-21 11:39:51.831: W/dalvikvm(339): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-21 11:39:51.851: E/AndroidRuntime(339): FATAL EXCEPTION: main
05-21 11:39:51.851: E/AndroidRuntime(339): java.lang.NullPointerException
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
05-21 11:39:51.851: E/AndroidRuntime(339):  at mobile.config.Koneksi.<init>(Koneksi.java:13)
05-21 11:39:51.851: E/AndroidRuntime(339):  at com.karismaelearning.Login.tryLogin(Login.java:131)
05-21 11:39:51.851: E/AndroidRuntime(339):  at com.karismaelearning.Login$3.onClick(Login.java:80)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.view.View.performClick(View.java:2485)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.view.View$PerformClick.run(View.java:9080)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.os.Handler.handleCallback(Handler.java:587)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.os.Looper.loop(Looper.java:123)
05-21 11:39:51.851: E/AndroidRuntime(339):  at android.app.ActivityThread.main(ActivityThread.java:3683)
05-21 11:39:51.851: E/AndroidRuntime(339):  at java.lang.reflect.Method.invokeNative(Native Method)
05-21 11:39:51.851: E/AndroidRuntime(339):  at java.lang.reflect.Method.invoke(Method.java:507)
05-21 11:39:51.851: E/AndroidRuntime(339):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-21 11:39:51.851: E/AndroidRuntime(339):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-21 11:39:51.851: E/AndroidRuntime(339):  at dalvik.system.NativeStart.main(Native Method)
05-21 11:39:54.301: I/Process(339): Sending signal. PID: 339 SIG: 9

please help me to know what the mistake is. I don't understand what's wrong. thank you very much

blackneko
  • 91
  • 1
  • 12
  • Where do you get null pointer? Please post logcat so we can help you easier – codeMagic May 21 '13 at 04:36
  • @codeMagic, I already edited my question with the LogCat. Thank you – blackneko May 21 '13 at 04:42
  • What is at line 131 of `Login`? That's where your error is – codeMagic May 21 '13 at 04:44
  • @codeMagic, linkurl = new Koneksi("/Login.php"); this is line 131... – blackneko May 21 '13 at 04:49
  • I'm sorry, the error is in `Koneksi Activity`. See my answer. I believe it will fix your problem – codeMagic May 21 '13 at 04:50
  • @codeMagic, I already try your answer but I still got same error :(... for Koneksi i didn't make any layout because it just save the value. and i use it to other class like Log in. – blackneko May 21 '13 at 05:06
  • What is line 13 of `Koneksi`? Also, if you aren't using a `layout` then you don't need to `extend Activity`. Just pass `context` to the class and use that to access your `SharedPreferences`. They are available app-wide but they require a `context` – codeMagic May 21 '13 at 05:08
  • @codeMagic, line 13 is public Koneksi(String urlml){ ,this line is before i edited. if I didn't put extends Activity in there the MODE_PRIVATE get red... so, i just try to put in there,because i don't know what i must put for preferences.. sorry, this is first time i make preferences so I don't really understand how to do it... – blackneko May 21 '13 at 05:16
  • @codeMagic, can you give me the one the use context, please? because i don't understand where i must apply it. thank you – blackneko May 21 '13 at 05:24

6 Answers6

0

try these two methods :p works well

public static void SavePreferences(String key, String name, String value,Context c) {
    SharedPreferences sf = c.getSharedPreferences(key, 0);
    SharedPreferences.Editor editor = sf.edit();
    editor.putString(name, value);
    editor.commit();
    Log.w("Preference saved  .", value);

}

public static String LoadPreferences(String key, String name, Context c) {
    SharedPreferences sf = c.getSharedPreferences(key, 0);
    String val = null;
    val = sf.getString(name, "");
    return val;

}
Saad Asad
  • 2,528
  • 3
  • 20
  • 27
  • Code only answers are generally frowned upon on SO. Please explain your answers so people will know why your code should work – codeMagic May 21 '13 at 04:53
0

These will give you NPE

SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);                                                          
String url = sharedPreferences.getString("URL", "");

Move the initializations to onCreate() which I don't see but assuming you have since you are extending Activity

public class Koneksi extends Activity {

    SharedPreferences sharedPreferences; //declare them here
    String url;

    public void onCreate(Bundle bundle)
   {
        super.onCreate(bundle);
        setContentView(R.layout.your_layout);

       sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);  // initialize them here
       url = sharedPreferences.getString("URL", "");  // intialize here

    public Koneksi(String urlml){   
        url= url + urlml;
    }

SharedPreferences needs a Context which isn't available until after onCreate() is called. You can declare them before this as you are but you need to initialize them in onCreate() or another Activity method after onCreate()is called

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • where I must put the context? O.o – blackneko May 21 '13 at 05:52
  • Use the `Context` like `context.getSharedPreferences*"MY_SHARED_PREF", MODE_PRIVVATE);` You can pass it to a constructor of the class like MyClass myClass = new MyClass(this); – codeMagic May 21 '13 at 12:59
  • You're welcome. Sorry I couldn't respond sooner but I had to get to sleep...it was late for me – codeMagic May 21 '13 at 13:11
  • hi codeMagic may I ask another question [link]http://stackoverflow.com/questions/16882865/i-need-help-have-error-when-receive-messages-chat , I really need help to solve this because i don't know where is my mistake. if you have time please look at that question. thank you very much – blackneko Jun 05 '13 at 00:50
  • codeMagic, can you help me with this question, it still about the chat. i already know the problem is on the stream, the stream always empty can't get the content, but i don't know to solve it. if you have time, please look at this [link]http://stackoverflow.com/questions/16983482/unable-to-receive-chat-messages .thank you very much – blackneko Jun 10 '13 at 02:02
0
   - you should be pass the context 



   mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);




  other wise use following code :-
  import android.preference.PreferenceManager;
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
  // then you use
  prefs.getBoolean("keystring", true);
Shyam
  • 6,376
  • 1
  • 24
  • 38
  • This doesn't answer the question at all. "you can do so in a non-Activity ..." what does this refer to? – codeMagic May 21 '13 at 04:49
0

try this way:

SharedPreferences sharedPreferences;

onCreate(Bundle savedInstanceState){
  sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
  // your code..
}

private void SavePreferences(String key, String value){

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}

private void LoadPreferences(){

    String strSavedurl = sharedPreferences.getString("URL", "");
    Savedurl.setText(strSavedurl);
}

Edited:

    public class Koneksi{

    SharedPreferences sharedPreferences;
    Context myC;
    String url = "";

    public Koneksi(Context con){
       myC = con;
       sharedPreferences = PreferenceManager.getDefaultSharedPreferences(con);
    }


    public Koneksi(String urlml){

        url= url + urlml;
    }


    public String getUrl(){
        String url = sharedPreferences.getString("URL", "");
        return url;
    }
}

for call above class from activity:

Koneksi ob = new Koneksi(this);
String URL = ob.getUrl();
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
  • i got error for koneksi class, but for koneksi class i didn't use layout. so how to call the preferences? O.o – blackneko May 21 '13 at 05:58
  • for urlSetting class, am i must erase the MODE_PRIVATE and change it become like ur ans or not? O.o and for string url = sha... is it after public string get url? because for the public koneksi got red.. or i must put it in both? O.o – blackneko May 21 '13 at 06:17
  • i can't understand what you are trying to say. but just use my code. – Dhaval Parmar May 21 '13 at 06:49
  • hmm, i got error at url =url +urlml, it got red mark.. O.o thank you – blackneko May 21 '13 at 07:09
  • add this String url = ""; after Context myC; check my edited ans – Dhaval Parmar May 21 '13 at 07:15
  • It success!! thank you very much.. but in every class like Login. java when i call it Koneksi linkurl = new Koneksi("/Login.php"); String SERVER_URL = linkurl.getUrl(); it got error.. every class has own .php, so how i can call it? O.o thank you – blackneko May 21 '13 at 12:37
  • for this no need to set url every time just store base url. like i have many php file at www.abc.com/webs/ then i save only "www.abc.com/webs/". after String URL = ob.getUrl(); i add like URL += "login.php" or "register.php" whatever page name. so, now my URL is 'www.abc.com/webs/login.php' or 'www.abc.com/webs/register.php' – Dhaval Parmar May 21 '13 at 12:44
  • add your activity name before this like: Koneksi ob = new Koneksi(MainActivity.this); where MainActivity is my activity name – Dhaval Parmar May 21 '13 at 13:32
  • may I ask again? i got error when i type that Koneksi linkurl = new Koneksi (this) in public void Onclick.. one of my class has that `public void onClick(View v) { // TODO Auto-generated method stub try {linkurl = new Koneksi(this); SERVER_URL = linkurl.getUrl(); SERVER_URL += "uploadProses.php?idc="+param1+"&idtgs="+param2+"&idu="+param3;...` it say : The constructor Koneksi(new View.OnClickListener(){}) is undefined what is the solution? Thank you – blackneko May 21 '13 at 13:36
  • oops, sorry the answer is above my question because i edited my question and got deleted, but thank you very much once again @Dhawal.. it works :D – blackneko May 21 '13 at 13:40
  • may I ask again? I try to write like this `String urlws = "/mobile/"`, mobile is my folder for my php. and i write `url = url + urlws + urlml` and got error what is the correct one? i want to make like that, so the user only insert www.abc.com . i think it's easier for the client. thank you – blackneko May 22 '13 at 06:13
  • instead of this use: url += urlml; where urlml = "/mobile/login.php" – Dhaval Parmar May 22 '13 at 06:16
  • Dhawal, may I ask u another question in here [link]http://stackoverflow.com/questions/16953355/got-error-when-try-to-download-pdf-file . If you have time, please look at that question, because I really need help and I don't know where is my mistake. thank you – blackneko Jun 06 '13 at 03:56
0

SharedPreference is common over your application you can use anywhere in your application,

http://developer.android.com/reference/android/content/SharedPreferences.html

MohsinSyd
  • 175
  • 2
  • 13
0

i dont know what is the problem with your code, i have working implementation for same..

    public class GreetingCardData {
    public static final String SHARED_PREF_FILE     =   "greetingCardData";
    public static final String KEY_DO_NOT_SHOW      =   "doNotShow";
    public static final String KEY_CATEGORIES_JSON  =   "categoriesJson";   
    private SharedPreferences sharedPrefs;
    private Editor prefsEditor;

    public GreetingCardData(Context context) {
        this.sharedPrefs = context.getSharedPreferences(SHARED_PREF_FILE, 0);
        this.prefsEditor = sharedPrefs.edit();
    }   

    public void setDoNotShowFlag ( boolean flag ){
        prefsEditor.putBoolean( KEY_DO_NOT_SHOW, flag );
        prefsEditor.commit();
    }

    public boolean getDoNotShowFlag(){
        return sharedPrefs.getBoolean( KEY_DO_NOT_SHOW, false );
    }

    public void setGreetingcardJson( String jsonString ){
        prefsEditor.putString( KEY_CATEGORIES_JSON, jsonString );
        prefsEditor.commit();
    }

    public String getGreetingcardJsonString(){
        return sharedPrefs.getString(KEY_CATEGORIES_JSON, "");
    }    
}

and you can access your pref. anywhere by just calling it like..

if( !new GreetingCardData(ActivityMain.this).getDoNotShowFlag())
     startHomeActivity();   


new GreetingCardData(context).setGreetingcardJson(resBuffer.toString());
NaserShaikh
  • 1,576
  • 2
  • 23
  • 39