如何将MainActivity类中使用共享首选项存储的数据检索到SplashScreen活动类?

时间:2014-09-12 11:30:25

标签: java android facebook sharedpreferences splash-screen

我成功地将Facebook api集成到我的第一个Android应用程序中,但是现在我在第一次成功登录后,仍然坚持使用access_token来避免我的应用程序中的Login步骤。我在登录后成功存储了token_access,但在重新启动应用后无法使用它。

App flow as:SplashScreen Activity - > LoginRegister活动 - > MainActivity

我的代码

SplashScreen活动类:

public class Splash_Screen extends Activity {
    Login log;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash__screen);

        Thread thread = new Thread() {
            public void run() {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {

                    Class classs;
                    log=new Login();
                    if (log.get() == false)
                        classs = Login_Register.class;
                    else
                        classs = Main.class;

                    Intent intent = new Intent(Splash_Screen.this, classs);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

                    startActivity(intent);
                    overridePendingTransition(0, 0);
                }
            }
        };
        thread.start();
    }

}

登录类(Login是LloginRegister Activity类中的Fragment):

public class Login extends Fragment implements 
        OnClickListener{
    boolean me;
    Facebook fb;
    static String access_token;;
    static SharedPreferences Logininfo;
    static long expires;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View login = inflater.inflate(R.layout.login, container, false);
        // TODO Auto-generated method stub
        login.findViewById(R.id.Login).setOnClickListener(this);
        login.findViewById(R.id.googlepluslog).setOnClickListener(this);
        login.findViewById(R.id.facebooklog).setOnClickListener(this);

        return login;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        fb = new Facebook(getString(R.string.APP_ID));

    }

    @SuppressWarnings("deprecation")
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.Login:

            if (UN.getText().length() == 0 || Pass.getText().length() == 0) {
                Toast.makeText(getActivity(),
                        "Please enter valid Username and Password",
                        Toast.LENGTH_SHORT).show();
            }
            break;
        case R.id.facebooklog:
            me=true;
            if (!fb.isSessionValid()) {
                fb.authorize(getActivity(), new String[] { "email" },
                        new DialogListener() {

                            @Override
                            public void onFacebookError(FacebookError e) {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onError(DialogError e) {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onComplete(Bundle values) {
                                // TODO Auto-generated method stub
                                set();
                                Toast.makeText(getActivity(), "successful",
                                        Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(getActivity()
                                        .getApplicationContext(), Main.class);
                                startActivity(intent);
                            }

                            @Override
                            public void onCancel() {
                                // TODO Auto-generated method stub

                            }
                        });
            }
            break;
        case R.id.googlepluslog:
            me=false;

            break;

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            Session.getActiveSession().onActivityResult(getActivity(), requestCode,
                    resultCode, data);

    }

    @SuppressWarnings("deprecation")
    public void set() {
        Logininfo = PreferenceManager.getDefaultSharedPreferences(getActivity()
                .getApplicationContext());
        // Logininfo = getSharedPreferences(MODE_PRIVATE);
        Editor edit = Logininfo.edit();
        edit.putString("access_token", fb.getAccessToken());
        edit.putLong("access_expires", fb.getAccessExpires());
        edit.commit();
    }

    @SuppressWarnings("deprecation")
    public boolean get() {
        boolean b = false;
        Log.i("dfsafw", "22222");
        SharedPreferences Logininfo = PreferenceManager
                .getDefaultSharedPreferences(getActivity().getBaseContext());
        Log.i("dfsafw", "11111");
        access_token = Logininfo.getString("access_token", null);
        expires = Logininfo.getLong("access_expires", 0);
        if (access_token != null) {
            fb.setAccessToken(access_token);
            if (expires != 0)
                fb.setAccessExpires(expires);
            b = true;
        }
        return b;

    }
}

我试图在Login类中定义的启动画面活动中检索访问令牌,并且我是android和java的初学者,我尝试了这种没有锻炼的方式。请帮帮我。

1 个答案:

答案 0 :(得分:1)

假设您已经保存了偏好设置,您可以随时阅读这些偏好设置,如下所示。

在共享首选项文件上写:

  SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
  SharedPreferences.Editor editor = prefs.edit();
  editor.putString("yourStringName", "this_is_the_saved_value");
  editor.commit(); // This line is IMPORTANT. If you miss this one its not going to work!

从共享首选项文件中读取:

SharedPreferences prefs = getSharedPreferences("your_file_name",MODE_PRIVATE);
String string = prefs.getString("yourStringName", "default_value_here_if_string_is_missing");

您可以使用默认文件来保存/阅读您的偏好设置。只需用以下内容替换上面两个代码段的第一行:SharedPreferences prefs = getDefaultSharedPreferences(getApplicationContext());

Check the Android Developers dedicated page.