我认为这是一个Context
问题,但我无法理解。
我正在使用JavascriptInterface
界面从webview中检索用户ID。我使用WebAppInterface
类来检索值并将其保存在sharedprefs中。我可以测试返回的值,它没问题。当我从WebAppInterface
内部拉出它时,它会保存在SharedPreferences中,但当我尝试在另一个活动中检索它时,检索到的值是默认值。
webview活动:
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
}
...
}
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);
}
}
然后在MainActivity.class中,我尝试用getSharedPreferences("My_Prefs", 0).getInt("uid",0);
检索此值,它总是返回0.
答案 0 :(得分:1)
[更新]
调用getSharedPreferences(String name, int mode)时,mode
参数确定存储的值是私有的,还是全局可读和/或可写的。
MODE_PRIVATE(其值为0)可能是您在最初存储数据的应用中使用的值。这意味着没有其他应用可以访问该数据。
但是,您应该知道其他模式自API级别17以来已被弃用,因为它们会打开安全漏洞。
您应该考虑让第一个应用实现ContentProvider或Service来提供共享数据。
请参阅this question及其接受的答案。但请注意,{23}在API级别23中已弃用,因为它在某些Android版本中无法可靠地运行,并且不会尝试协调跨进程的并发修改。
您应该考虑实施ContentProvider或Service来提供共享数据。对于非常简单的数据,MODE_MULTI_PROCESS(文件的ContentProvider)可能就足够了。
答案 1 :(得分:1)
粗略的想法是:
Intent intent = new Intent(mContext, MainActivity.class);
intent.putExtra("uid", uid);
mContext.startActivity(intent);
然后在MainActivity中
getIntent().getIntExtra("uid", -1);
将返回您的值或-1