简体   繁体   English

我的SharedPreferences值由于某种原因未通过

[英]My SharedPreferences value isn't passing for some reason

So I've created three classes : 因此,我创建了三个类:

1) Splash Screen Class 2) Intro Class 3) Main Activity Class 1)启动画面课程2)简介课程3)主要活动课程

My intention is, after the splash screen, if the app has been launched for the first time, it is supposed to show the intro activity which works fine. 我的意图是,在启动屏幕之后,如果该应用程序是首次启动,那么它应该显示出正常运行的介绍活动。

In intro activity, I have added terms and conditions checkbox which will start the app only if it is checked which also works fine. 在介绍活动中,我添加了“条款和条件”复选框,该复选框仅在被选中也可以正常运行的情况下才启动应用程序。

The issue is, Splash Screen - Each time the app is launched, my app will check if it is the first time or if it isn't the first time, then it will check if the user has agreed to the terms and if both are passed, start the main activity. 问题是启动画面-每次启动该应用程序时,我的应用程序都会检查它是第一次还是不是第一次,然后它将检查用户是否同意条款以及两者是否一致。通过,开始主要活动。

I'm using SharedPreferences for this but it isn't working as I expected it to, so need your help! 我正在为此使用SharedPreferences,但是它没有按我预期的那样工作,因此需要您的帮助!

Here's the code for SplashActivity 这是SplashActivity的代码

public class SplashActivity extends AppCompatActivity {

    private static final int SPLASH_DELAY = 200;

    private final Handler mHandler   = new Handler();
    private final Launcher mLauncher = new Launcher();

    @Override
    protected void onStart() {
        super.onStart();

        mHandler.postDelayed(mLauncher, SPLASH_DELAY);
    }

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

    @Override
    protected void onStop() {
        mHandler.removeCallbacks(mLauncher);
        super.onStop();
    }

    private void launch() {
        if (!isFinishing()) {

            SharedPreferences settings=getSharedPreferences("prefs",0);
            boolean firstRun=settings.getBoolean("firstRun",false);

            if(!firstRun)
            {
                SharedPreferences.Editor editor=settings.edit();
                editor.putBoolean("firstRun",true).apply();
                editor.commit();
                Intent i=new Intent(SplashActivity.this, IntroActivity.class);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                startActivity(i);
                finish();
            }
            else
            {
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                String name=preferences.getString("Policy","Disagreed");
                if(!name.equals("Agreed"))
                {
                    Intent a=new Intent(SplashActivity.this, MainActivity.class);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    startActivity(a);
                    finish();
                } else
                {
                    Intent i=new Intent(SplashActivity.this, IntroActivity.class);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    startActivity(i);
                    finish();
                }

            }
        }

    }

    private class Launcher implements Runnable {
        @Override
        public void run() {
            launch();
        }
    }
}

IntroActivity : 活动简介:

public class IntroActivity extends MaterialIntroActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        enableLastSlideAlphaExitTransition(true);

        getBackButtonTranslationWrapper()
                .setEnterTranslation(new IViewTranslation() {
                    @Override
                    public void translate(View view, @FloatRange(from = 0, to = 1.0) float percentage) {
                        view.setAlpha(percentage);
                    }
                });

        addSlide(new SlideFragmentBuilder()
                        .backgroundColor(R.color.myWindowBackground)
                        .buttonsColor(R.color.myAccentColor)
                        .image(R.mipmap.ic_splash_screen)
                        .title("Organize your time with us")
                        .description("Would you try?")
                        .build(),
                new MessageButtonBehaviour(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showMessage("We provide solutions to make you love your work");
                    }
                }, "Work with love"));

        addSlide(new SlideFragmentBuilder()
                .backgroundColor(R.color.myWindowBackground)
                .buttonsColor(R.color.myAccentColor)
                .title("Want more?")
                .description("Go on")
                .build());

        addSlide(new CustomSlide());

    }

    @Override
    public void onFinish() {
        Intent a=new Intent(IntroActivity.this, MainActivity.class);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        startActivity(a);
        finish();
    }
}

CustomSlide Fragment (Privacy Policy checkbox fragment) CustomSlide片段(“隐私策略”复选框片段)

public class CustomSlide extends SlideFragment {
    private CheckBox checkBox;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private String terms;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_custom_slide, container, false);

        prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
        editor = prefs.edit();
        terms = prefs.getString("Policy", "Disagreed");

        checkBox = (CheckBox) view.findViewById(R.id.checkBox);
        return view;
    }

    @Override
    public int backgroundColor() {
        return R.color.myWindowBackground;
    }

    @Override
    public int buttonsColor() {
        return R.color.myAccentColor;
    }

    @Override
    public boolean canMoveFurther() {

        editor.putString("Policy", "Agreed");
        editor.commit();

        return checkBox.isChecked();
    }

    @Override
    public String cantMoveFurtherErrorMessage() {

        editor.putString("Policy", "Disagreed");
        editor.commit();

        return getString(R.string.error);
    }
}

MainActivity has nothing passed on and just starts. MainActivity没有任何传递,只是开始。

Thank you, looking forward for some help. 谢谢您,期待获得帮助。

Edit: My app shows the IntroSlider the first time I launch, but closing it without the checking the "Agree" checkbox in Privacy Policy (CustomSlide Fragment) and re-launching it directly shows Main Activity which defeats the purpose of having an agree button. 编辑:我的应用程序在我第一次启动时显示IntroSlider,但是在没有选中“隐私策略”(CustomSlide Fragment)中的“同意”复选框并关闭并关闭它的情况下直接关闭它,直接显示“主要活动”,这违背了拥有同意按钮的目的。 Like the app should only show the main activity once the user has clicked on agree button. 就像该应用程序仅在用户单击“同意”按钮后才显示主要活动。

For easier code control i will create 2 static method for get/put boolean on SharedPreferences for check if user Agreed/Disagreed: 为了简化代码控制,我将为SharedPreferences上的get / put布尔值创建2个静态方法,以检查用户是否同意/不同意:

for put boolean: 对于布尔值:

public static void Put_boolean(String key, boolean value, Context context) {
    SharedPreferences sharedPreferences =  context.getSharedPreferences("prefname", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.apply();
}

for get boolean: 获取布尔值:

public static boolean Get_boolean(String key, boolean defvak, Context context) {
    SharedPreferences sharedPreferences =  context.getSharedPreferences("prefname", 0);
    return sharedPreferences.getBoolean(key, defvak);
}

now we can save true value when user is agreed and false if user Disagreed, simply when your user Agreed/Disagreed call: 现在,我们可以在同意用户的情况下保存true值,而在不同意用户的情况下可以保存false,仅当您的用户同意/不同意调用时:

YourActivity.Put_boolean("isAgreed", true, context); //when Agreed
YourActivity.Put_boolean("isAgreed", false, context); //when Disagreed

when you want to check if user Agreed/Disagreed use: 当您要检查用户同意/不同意使用时:

final boolean checkifAgreed = YourActivity.Get_boolean("isAgreed", false, context);
if(checkifAgreed){
            //user is Agreed
        }else{
            //user is Disagreed
        }

i used static methods, so i can Get/Put SharedPreferences values from any activity using the same methods, hope this help you 我使用了静态方法,因此我可以使用相同的方法从任何活动中获取/放置SharedPreferences值,希望这对您有所帮助

You may or may not want to use it, but I made a Singleton service which handles my Shared preferences for me. 您可能想要也可能不想使用它,但是我做了一个Singleton服务,可以为我处理“共享”首选项。

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class SharedPreferencesService {
    private static final String DEBUG = "SharedPreferencesService";
    private static final String sharedPreferencesFileName = "SharedPrefsDB";
    private static SharedPreferencesService ourInstance = null;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ExecutorService executorService;
    private HashMap<String, String> data = new HashMap<>();

    private SharedPreferencesService(Context context) {
        sharedPreferences = context.getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        executorService = Executors.newSingleThreadExecutor(new NamedThreadFactory());
        //Add data from file to RAM:
        Map<String, ?> entries = sharedPreferences.getAll();
        for (String key : entries.keySet()) {
            data.put(key, entries.get(key).toString());
        }
    }

    public static SharedPreferencesService getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new SharedPreferencesService(context.getApplicationContext());
        }
        return ourInstance;
    }

    public void writeToPreferences(String key, String value) {
        executorService.execute(() -> editor.putString(key, value).commit());
        data.put(key, value);
        //Log.d(DEBUG,"Added "+key + " bytes:"+value.length() + " To prefs.");
    }

    public String getPreferenceSafe(String key) throws NoSuchPreferenceException {
        try {
            if (data.get(key) == null)
                throw new NoSuchPreferenceException("Token does not exist in RAM");
            return data.get(key);
        } catch (Exception e) {
            throw new NoSuchPreferenceException(key);
        }
    }

    public String getPreference(String key) {
        return data.get(key);
    }

    public void clearPreference(String key) {
        editor.putString(key, null).commit();
    }

    private class NamedThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(@NonNull Runnable r) {
            Thread thread = new Thread(r, "sp-db");
            thread.setDaemon(true);
            thread.setPriority(Thread.NORM_PRIORITY);
            return thread;
        }
    }

    public class NoSuchPreferenceException extends Exception {
        public NoSuchPreferenceException(String message) {
            super(message);
        }
    }
}

It adds data to the SharedPreferences file when you call writeToPreferences("key","value") but also adds it to a RAM held field in the class...so it is quick to get. 当您调用writeToPreferences("key","value")时,它将数据添加到SharedPreferences文件中writeToPreferences("key","value")但也将其添加到类中的RAM保留字段中...因此可以快速获取。

For easier implementation, you can use PowerPrefernce 为了更容易实现,可以使用PowerPrefernce

https://github.com/AliAsadi/Android-Power-Preference https://github.com/AliAsadi/Android-Power-Preference

Save data 保存数据

PowerPreference.getDefaultFile().put("isAgreed",true);

Get Data 获取数据

PowerPreference.getDefaultFile().getBoolean("isAgreed");

Try change this line, in customslide fragment 尝试更改这行,在customlide片段中

prefs = getActivity().getPreferences(Context.MODE_PRIVATE); prefs = getActivity()。getPreferences(Context.MODE_PRIVATE);

to be 成为

prefs = getActivity().getSharedPreferences("prefs", MODE_PRIVATE); prefs = getActivity()。getSharedPreferences(“ prefs”,MODE_PRIVATE);

also use 也用

editor.apply(); editor.apply();

when you want to save your new data in preference. 当您想优先保存新数据时。 Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM