我通过@JavascriptInterface从webview获取用户值,这个没有问题。
接下来我将获得的值记录在首选项中,以供进一步使用。然而,正如日志所示,值写入不正确。
我有什么错吗?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences sPref;
public static final String PREFS_FILE = "MyPrefsFile";
................
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showUser(String data) {
Log.d("MyTAG", "INPUT: "+data);
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray;
try {
jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
Log.d("MyTAG", "i="+i+" :"+jsonArray.getString(i));
}
Log.d("MyTAG", "Array: "+stringArray);
} catch (JSONException e) {
e.printStackTrace();
}
sPref = getSharedPreferences(PREFS_FILE, 0);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(NAME,stringArray.get(0));
ed.putString(AVATAR,stringArray.get(1));
ed.putString(USER_ID, stringArray.get(2));
ed.commit();
Log.d("MyTAG", "name="+sPref.getString(NAME, ""));
Log.d("MyTAG", "avatar="+sPref.getString(AVATAR, ""));
Log.d("MyTAG", "user_id="+sPref.getString(USER_ID, ""));
}
}
}
日志:
D/MyTAG: INPUT: ["myname","src","2"]
D/MyTAG: i=0 :myname
D/MyTAG: i=1 :src
D/MyTAG: i=2 :2
D/MyTAG: Array: [myname, src, 2]
D/MyTAG: name=src
D/MyTAG: avatar=src
D/MyTAG: user_id=2
由于某种原因,含义更改为以下内容。
如何获取偏好值name = myname
慕田峪9158850
相关分类