共享首选项始终返回相同的值

时间:2017-07-01 01:48:33

标签: android sharedpreferences

我正在开发一个Android应用程序,其中有两种类型的用户。当用户注册或登录系统时,它们将被重定向到同一主屏幕,并根据其类型查看不同的视图片段。在第一次注册时,我能够使用共享首选项实现此目的。我唯一的问题是,如果用户退出然后再次尝试登录,那么无论他是什么类型的用户,都会加载相同的主屏幕。我怀疑,活动使用最后一组共享偏好。

在我的片段中,基于userType,我膨胀了相应的xml文件。我的要求是,当用户登录时,如何给相应的xml文件充气,即。如何获取SignInActivity中的Shared首选项以加载相应的片段xml。

这是我到目前为止所尝试的内容。

MainMenuActivity.java

{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    ButterKnife.bind(this);

    setSupportActionBar(toolbar);

    gaFragmentStack = new Stack<>();

    Fragment home_fragment = new HomeFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container_gaFragments, home_fragment);
    transaction.commit();

    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (getUid() != null) {
        String userId = getUid();
        firebaseAuth = FirebaseAuth.getInstance();
        databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(userId);

    } else {
        onAuthFailure();
    }

    final PrimaryDrawerItem home = new PrimaryDrawerItem().withName("Home").withIdentifier(1).withIcon(GoogleMaterial.Icon.gmd_home);
    final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Profile").withIdentifier(2).withIcon(GoogleMaterial.Icon.gmd_account);
    final PrimaryDrawerItem gallery = new PrimaryDrawerItem().withName("Gallery").withIdentifier(3).withIcon(R.drawable.ic_perm_media_black_24dp);
    final PrimaryDrawerItem recognition = new PrimaryDrawerItem().withName("Recognition").withIdentifier(4).withIcon(GoogleMaterial.Icon.gmd_face);
    final PrimaryDrawerItem maps = new PrimaryDrawerItem().withName("Maps").withIdentifier(5).withIcon(R.drawable.ic_place_black_24dp);
    final PrimaryDrawerItem tagAndLocate = new PrimaryDrawerItem().withName("Tag & Locate").withIdentifier(6).withIcon(R.drawable.ic_remove_red_eye_black_24dp);
    final PrimaryDrawerItem gamesAndPuzzle = new PrimaryDrawerItem().withName("Games & Puzzles").withIdentifier(7).withIcon(R.drawable.ic_casino_black_24dp);
    final PrimaryDrawerItem backup = new PrimaryDrawerItem().withName("Backup").withIdentifier(8).withIcon(GoogleMaterial.Icon.gmd_save);
    final PrimaryDrawerItem logout = new PrimaryDrawerItem().withName("Logout").withIdentifier(9).withIcon(FontAwesome.Icon.faw_sign_out);

    DrawerImageLoader.init(new AbstractDrawerImageLoader() {
        @Override
        public void set(ImageView imageView, Uri uri, Drawable placeholder) {
            Picasso.with(imageView.getContext()).load(uri).placeholder(placeholder).fit().centerCrop().into(imageView);
        }

        @Override
        public void cancel(ImageView imageView) {
            Picasso.with(imageView.getContext()).cancelRequest(imageView);
        }
    });

    String name = preferences.getString(Preferences.NAME, "");
    String email = preferences.getString(Preferences.EMAIL, "");
    final ProfileDrawerItem userProfile = new ProfileDrawerItem().withName(name).withEmail(email).withIcon(R.drawable.ic_account_circle_white_24dp);

    headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withHeaderBackground(R.drawable.header)
            .withSelectionListEnabledForSingleProfile(false)
            .addProfiles(userProfile)
            .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                @Override
                public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                    return false;
                }
            })
            .build();

    String userType = preferences.getString(Preferences.USER_TYPE, "");

    if(userType !=null && userType.equalsIgnoreCase("Standard")) {

        result = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(headerResult)
                .withToolbar(toolbar)
                .withDisplayBelowStatusBar(false)
                .withTranslucentStatusBar(true)
                .withSavedInstance(savedInstanceState)
                .withActionBarDrawerToggle(true)
                .withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(home)
                .addDrawerItems(profile)
                .addDrawerItems(gallery)
                .addDrawerItems(recognition)
                .addDrawerItems(maps)
                .addDrawerItems(tagAndLocate)
                .addDrawerItems(gamesAndPuzzle)
                .addDrawerItems(backup)
                .addDrawerItems(new DividerDrawerItem())
                .addDrawerItems(logout)
                .buildForFragment();

        result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
            @Override
            public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                int drawItemId = (int) drawerItem.getIdentifier();
                Intent intent;
                Fragment fragment;
                switch (drawItemId) {

                    case 1:
                        fragment = new HomeFragment();
                        gaFragmentStack.add(home);
                        break;
                    case 2:
                        fragment = new ProfileFragment();
                        gaFragmentStack.add(profile);
                        break;
                    case 3:
                        fragment = new GalleryFragment();
                        gaFragmentStack.add(gallery);
                        break;
                    case 4:
                        fragment = new RecognitionFragment();
                        gaFragmentStack.add(recognition);
                        break;
                    case 5:
                        fragment = new MapsFragment();
                        gaFragmentStack.add(maps);
                        break;
                    case 6:
                        fragment = new TagLocateFragment();
                        gaFragmentStack.add(tagAndLocate);
                        break;
                    case 7:
                        fragment = new GamesPuzzlesFragment();
                        gaFragmentStack.add(gamesAndPuzzle);
                        break;
                    case 8:
                        fragment = new BackupFragment();
                        gaFragmentStack.add(backup);
                        break;
                    default:
                        fragment = new HomeFragment();
                        break;
                }
                if (drawItemId == 9) {
                    FirebaseAuth.getInstance().signOut();
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.clear();
                    editor.apply();
                    intent = new Intent(MainMenuActivity.this, SplashScreen.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                }

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container_gaFragments, fragment);
                transaction.commit();
                return false;
            }
        });

    }else {
        result = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(headerResult)
                .withToolbar(toolbar)
                .withDisplayBelowStatusBar(false)
                .withTranslucentStatusBar(true)
                .withSavedInstance(savedInstanceState)
                .withActionBarDrawerToggle(true)
                .withActionBarDrawerToggleAnimated(true)
                .addDrawerItems(home)
                .addDrawerItems(profile)
                .addDrawerItems(maps)
                .addDrawerItems(backup)
                .addDrawerItems(new DividerDrawerItem())
                .addDrawerItems(logout)
                .buildForFragment();


        result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
            @Override
            public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                int drawItemId = (int) drawerItem.getIdentifier();
                Intent intent;
                Fragment fragment;
                switch (drawItemId) {

                    case 1:
                        fragment = new HomeFragment();
                        gaFragmentStack.add(home);
                        break;
                    case 2:
                        fragment = new ProfileFragment();
                        gaFragmentStack.add(profile);
                        break;
                    case 5:
                        fragment = new MapsFragment();
                        gaFragmentStack.add(maps);
                        break;
                    case 8:
                        fragment = new BackupFragment();
                        gaFragmentStack.add(backup);
                        break;
                    default:
                        fragment = new HomeFragment();
                        break;
                }
                if (drawItemId == 9) {
                    FirebaseAuth.getInstance().signOut();
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.clear();
                    editor.apply();
                    intent = new Intent(MainMenuActivity.this, SplashScreen.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                }

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.container_gaFragments, fragment);
                transaction.commit();
                return false;
            }
        });
    }

}

SignInActivity.java

{

    String email;

    if(view.getId() == R.id.loginButton){
        email = emailLoginTextInputEditText.getText().toString();
        String password = passwordLoginEditText.getText().toString();

        if (!validateEmail(email)) {
            return;
        }
        if (!validateSetPass(password)) {
            return;
        }
        showProgressDialog("Signing in...");
        mAuth.signInWithEmailAndPassword(email,password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        progressDialog.dismiss();
                        if(task.isSuccessful()){
                            hideProgressDialog();
                            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(getUid());
                            databaseReference.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    Profile profile = dataSnapshot.getValue(Profile.class);
                                    Log.e("key", dataSnapshot.getKey());
                                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SignInActivity.this);
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    if(profile !=null){
                                        editor.putString(Preferences.EMAIL, profile.getEmail());
                                        editor.putString(Preferences.NAME, profile.getFullName());
                                    }
                                    editor.putString(Preferences.USERID, getUid());
                                    editor.apply();

                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });

                            Intent loginIntent = new Intent(SignInActivity.this,MainMenuActivity.class);
                            loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(loginIntent);
                            finish();
                        }
                    }
                });
    }
    else if(view.getId() == R.id.singinGoogleButton)
    {
        Toast.makeText(SignInActivity.this,"Signing in with google...",Toast.LENGTH_SHORT).show();
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);

    }
    else if(view.getId() == R.id.signupTV)
    {
        Intent intent = new Intent(SignInActivity.this,SignUpActivity.class);
        startActivity(intent);
        finish();
    }
    else if (view.getId() == R.id.forgotPasswordTextView) {

        Intent intent = new Intent(SignInActivity.this,ResetPasswordActivity.class);
        startActivity(intent);
        finish();
        }
    }

SignUpActivity.java

{

    showProgressDialog("Saving...");
    Intent intent = getIntent();

    String fullName = intent.getStringExtra("fullName");
    String userEmailAddress = intent.getStringExtra("emailAddress");
    String userType = intent.getStringExtra("userType");

    String phoneNumber = phoneNumberTextInputEditText.getText().toString().trim();
    String dateOfBirth = dateofBirthTextInputEditText.getText().toString().trim();
    String securityAnswer = securityAnswerTextInputEditText.getText().toString().trim();

    if (!validateForm(phoneNumber, dateOfBirth, securityAnswer)) {
        hideProgressDialog();
        return;
    }

    if(userType.equalsIgnoreCase("Standard")){
        hideProgressDialog();
        Toast.makeText(this, "User details saved!",Toast.LENGTH_SHORT).show();
        Intent guardianIntent = new Intent(ContactDetailsActivity.this, AddGuardianActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        guardianIntent.putExtra("fullName", fullName);
        guardianIntent.putExtra("userEmailAddress", userEmailAddress);
        guardianIntent.putExtra("phoneNumber", phoneNumber);
        guardianIntent.putExtra("dateofBirth", dateOfBirth);
        guardianIntent.putExtra("userType", userType);
        guardianIntent.putExtra("securityAnswer", securityAnswer);
        guardianIntent.putExtra("securityQuestion", securityQuestion);
        startActivity(guardianIntent);
        finish();
    }else{
        databaseReference.child("fullName").setValue(fullName);
        databaseReference.child("phoneNumber").setValue(phoneNumber);
        databaseReference.child("dateOfBirth").setValue(dateOfBirth);
        databaseReference.child("securityAnswer").setValue(securityAnswer);
        databaseReference.child("securityQuestion").setValue(securityQuestion);
        databaseReference.child("userType").setValue(userType);

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Profile profile = dataSnapshot.getValue(Profile.class);
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ContactDetailsActivity.this);
                SharedPreferences.Editor editor = preferences.edit();
                if(profile != null) {
                    editor.putString(Preferences.NAME, profile.getFullName());
                    editor.putString(Preferences.EMAIL, profile.getEmail());
                    editor.putString(Preferences.USER_TYPE, profile.getUserType());
                }
                editor.putString(Preferences.USERID, getUid());
                editor.apply();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        hideProgressDialog();
        Toast.makeText(this, "Profile Created", Toast.LENGTH_SHORT).show();
        Intent mainMenuIntent = new Intent(ContactDetailsActivity.this, MainMenuActivity.class);
        mainMenuIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mainMenuIntent);
        finish();
    }

}

HomeFragment.java

{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String userType = sharedPreferences.getString(Preferences.USER_TYPE, "");
    View view;
    if(userType != null && userType.equalsIgnoreCase("STANDARD")) {

         view = inflater.inflate(R.layout.fragment_home, container, false);
    }else{
         view = inflater.inflate(R.layout.fragment_home_guardian, container, false);
    }
    toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.homeScreen));
    initControls(view,userType);
    return view;
}

当用户登录应用程序时,如何加载相应的片段xml?我错过了什么?请帮助。

1 个答案:

答案 0 :(得分:0)

您正在使用getDefaultSharedPreferences()获取SharedPreference实例,但每次都使用不同的上下文。

使用getApplicationContext()代替Activity.thisthis