如何保存片段onButtonClick并加载下一个程序启动

时间:2018-02-14 09:03:30

标签: java android fragment android-savedstate

我有一个应用程序,我有一个片段。让我们称之为mainScreen。在mainScreen中有一个buttononClick()打开第二个片段。我们称之为FragmentHomePage。在FragmentHomePage中,我有一个retrofit。有一个名为logOut的按钮。我的问题是,当用户没有点击logOut时,我想保存这个片段并加载这个片段。默认情况下,当app启动时,打开mainScreen,但如果用户没有单击logOut,我需要在app start上打开FragmentHomePage。我怎么能这样做?

public class FragmentHomePage extends BaseFragment {

View mainView;
TextView fullName, userName, email;
Button logOut;
ApiClient apiClient = ApiClient.getInstance();
SupportObjToken supportopToken = new SupportObjToken();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate(R.layout.home_page, container, false);

    init(mainView);
    newTokenCall();

    return mainView;
}

private void init(View v) {
    fullName = v.findViewById(R.id.fullName);
    userName = v.findViewById(R.id.user);
    email = v.findViewById(R.id.mail);
    logOut = v.findViewById(R.id.logOut);
}

public void newTokenCall() {

    String clientID = SharedPreferencesManager.getInstance().getClientID();
    String clientSecret = SharedPreferencesManager.getInstance().getClientSecret();
    String refreshToken = SharedPreferencesManager.getInstance().getRefreshToken();
    String newRefreshToken = SharedPreferencesManager.getInstance().getNewRefreshToken();
    final String firstName = SharedPreferencesManager.getInstance().getFirstName();
    final String lastName = SharedPreferencesManager.getInstance().getLastName();
    final String mail = SharedPreferencesManager.getInstance().getEmail();
    final String user = SharedPreferencesManager.getInstance().getUsername();

    supportopToken.setGrantType("refresh_token");
    supportopToken.setClientId(clientID);
    supportopToken.setClientSecret(clientSecret);
    supportopToken.setRefreshToken(refreshToken);

    Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
    newToken.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                try {
                    String newDataAccess = response.body().string();
                    JSONObject obj = new JSONObject(newDataAccess);

                    String newAccessToken = obj.getString("accessToken");
                    String newRefreshToken = obj.getString("refreshToken");

                    SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
                    SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);

                    fullName.setText(firstName + " " + lastName);
                    userName.setText(user);
                    email.setText(mail);

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            } else if (response.code() == 401) {
                supportopToken.setRefreshToken(SharedPreferencesManager.getInstance().getNewRefreshToken());

                Call<ResponseBody> newToken1 = apiClient.newToken(supportopToken);
                newToken1.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            try {
                                String newDataAccess = response.body().string();
                                JSONObject obj = new JSONObject(newDataAccess);

                                String newAccessToken = obj.getString("accessToken");
                                String newRefreshToken = obj.getString("refreshToken");

                                SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
                                SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);

                                fullName.setText(firstName + " " + lastName);
                                userName.setText(user);
                                email.setText(mail);

                            } catch (JSONException | IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
        }
    });
}}

我该怎么做这部分?谢谢。是的,不要投反对票。我是这个网站的初学者))。

这是我发布片段的活动。

public class MainActivity extends AppCompatActivity implements FragmentChangeListener {
FragmentActivity fragmentActivity;

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

    ApiClient.initializeInstance("simple web page");

    fragmentActivity = new FragmentActivity();

    this.replaceFragment(fragmentActivity, true);

    SharedPreferencesManager.init(this);
}

@Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
    String backStateName = fragment.getClass().getName();
    FragmentManager manager = getFragmentManager();

    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.container, fragment, fragment.toString());
    transaction.addToBackStack(backStateName);
    transaction.commit();
}}

2 个答案:

答案 0 :(得分:0)

在SharedPreferences中保存一个默认值为false的布尔值。

 PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();

当你来到FragmentHomePage时,将此值设置为true。

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", true).apply();

当用户点击退出按钮时,再次将此值设置为false。

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();

来自保留这些片段的基本活动, 启动mainScreen片段时,请使用以下代码检查此值:

PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);

如果值为true,则启动HomeFragment,否则启动mainScreen片段。

使用此功能启动片段:

public void launchFragmentByReplacing(Fragment fragment, String incomingFragmentTag) {

    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(frameLayout.getId(), fragment, incomingFragmentTag);
    transaction.commit();
    manager.executePendingTransactions();
}

在你的情况下,就在之前:

this.replaceFragment(fragmentActivity, true);

检查SharedPref值。

Boolean isloggedIn = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
    if(isloggedIn) //is true
    this.replaceFragment(new FragmentActivity(), true);
    else
    this.replaceFragment(new FragmentHomePage(), true);

答案 1 :(得分:0)

在主屏幕按钮onclick中,为此共享首选项添加密钥

 SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
 editor.putString("state", "logged_in");
 editor.apply();
在logOut按钮内点击FragmentHomePage,添加以下代码

 SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
 editor.putString("state", "logged_out");
 editor.apply();

现在在你的第一个片段的oncreate里面添加这个

SharedPreferences prefs = getSharedPreferences("APP_PREF", MODE_PRIVATE); 
  String state = prefs.getString("state", "state");
  if(state.equals("logged_in"){
   //load second fragment here
  }