I think taht's a Context
problem, but I could not figure it out.
I'm retrieving a user id from webview with JavascriptInterface
Interface. I'm using WebAppInterface
class to retrieve the value and save it in sharedprefs. I could test the returned value and it's ok. It is saved in the SharedPreferences when I pull it from inside WebAppInterface
but when I try to retrieve it in another activity the value retrieved is default.
The webview activity:
public class Login extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.loadUrl("mydomain.com/retrieveid"); //here I use the real url
}
...
}
The WebAppInterfaceClass
public class WebAppInterface {
Context mContext;
SharedPreferences mPrefs;
WebAppInterface(Context c) {
mContext = c;
mPrefs = c.getSharedPreferences("My_Prefs", 0);
}
@JavascriptInterface
public void returnUserID(String uid) {
Editor editor = mPrefs.edit();
editor.putInt("uid", Integer.valueOf(uid));
editor.commit();
Integer uid2 = mPrefs.getInt("uid", 0);
Log.i("uid after update", String.valueOf(uid2)); //this value is correct
Intent intent = new Intent(mContext, MainActivity.class);
mContext.startActivity(intent);
}
}
Then in MainActivity.class I try to retrive this value with getSharedPreferences("My_Prefs", 0).getInt("uid",0);
and it always return 0.