繁体   English   中英

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

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

因此,我创建了三个类:

1)启动画面课程2)简介课程3)主要活动课程

我的意图是,在启动屏幕之后,如果该应用程序是首次启动,那么它应该显示出正常运行的介绍活动。

在介绍活动中,我添加了“条款和条件”复选框,该复选框仅在被选中也可以正常运行的情况下才启动应用程序。

问题是启动画面-每次启动该应用程序时,我的应用程序都会检查它是第一次还是不是第一次,然后它将检查用户是否同意条款以及两者是否一致。通过,开始主要活动。

我正在为此使用SharedPreferences,但是它没有按我预期的那样工作,因此需要您的帮助!

这是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();
        }
    }
}

活动简介:

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片段(“隐私策略”复选框片段)

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没有任何传递,只是开始。

谢谢您,期待获得帮助。

编辑:我的应用程序在我第一次启动时显示IntroSlider,但是在没有选中“隐私策略”(CustomSlide Fragment)中的“同意”复选框并关闭并关闭它的情况下直接关闭它,直接显示“主要活动”,这违背了拥有同意按钮的目的。 就像该应用程序仅在用户单击“同意”按钮后才显示主要活动。

为了简化代码控制,我将为SharedPreferences上的get / put布尔值创建2个静态方法,以检查用户是否同意/不同意:

对于布尔值:

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();
}

获取布尔值:

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

现在,我们可以在同意用户的情况下保存true值,而在不同意用户的情况下可以保存false,仅当您的用户同意/不同意调用时:

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

当您要检查用户同意/不同意使用时:

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

我使用了静态方法,因此我可以使用相同的方法从任何活动中获取/放置SharedPreferences值,希望这对您有所帮助

您可能想要也可能不想使用它,但是我做了一个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);
        }
    }
}

当您调用writeToPreferences("key","value")时,它将数据添加到SharedPreferences文件中writeToPreferences("key","value")但也将其添加到类中的RAM保留字段中...因此可以快速获取。

为了更容易实现,可以使用PowerPrefernce

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

保存数据

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

获取数据

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

尝试更改这行,在customlide片段中

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

成为

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

也用

editor.apply();

当您想优先保存新数据时。 希望能帮助到你

暂无
暂无

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

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