我有一个Facebook登录,我需要在我的共享首选项中保存用户,用户ID和电子邮件的变量,以便在我的第二个在另一个类中有片段的活动中使用它们。
这是我的Facebook登录onSuccess方法:
public void onSuccess(LoginResult loginResult) {
// App code
Toast.makeText(getApplicationContext(), "Login successful" + loginResult.getAccessToken().toString(), Toast.LENGTH_LONG).show();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//textView.setText(response.toString());
JSONObject j_user = response.getJSONObject();
try {
id = j_user.getString("id");
email = j_user.getString("email");
name = j_user.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("string", response.toString());
Log.i("string", id);
Log.i("string", email);
Log.i("string", name);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
SavePreferences("id", id);
SavePreferences("email", email);
SavePreferences("name", name);
}
这是我的保存偏好设置方法和" gotootheractivity"按钮
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
//Intent sd=new Intent(this,SampleActivity.class);
//startActivity(sd);
}
public void goToEvents(View view)
{
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
Intent intent = new Intent(FbLoginActivity.this, SampleActivity.class);
startActivity(intent);
}
在第一个活动中,我是' m" Toast"作品, 这是第二个活动的代码:
private void LoadPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sharedPreferences.getString("name", "0") ;
String email = sharedPreferences.getString("email", "0") ;
String id = sharedPreferences.getString("id", "0") ;
Toast.makeText(this, name, Toast.LENGTH_LONG).show();
Toast.makeText(this, id, Toast.LENGTH_LONG).show();
Toast.makeText(this, email, Toast.LENGTH_LONG).show();
}
我在setContentView()和" Toast"之后使用此方法。不起作用,它们都显示" 0",当我关闭应用程序并点击我的按钮时,第一个按钮也显示我" " ,似乎SharedPrefs没有很好地存储..