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

时间:2018-12-14 12:52:47

标签: java android

所以我创建了三个类:

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

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

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)中的“同意”复选框并关闭并重新启动的情况下,直接将其显示为主要活动,这违背了同意按钮。就像该应用程序仅在用户单击“同意”按钮后才显示主要活动。

4 个答案:

答案 0 :(得分:2)

为了简化代码控制,我将为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);
}

现在,当用户同意时,我们可以保存真值;如果用户不同意,我们可以保存假值,仅当您的用户同意/不同意呼叫时:

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值,希望对您有帮助

答案 1 :(得分:1)

您可能想要也可能不想使用它,但是我提供了一个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文件中,而且还将其添加到该类中的RAM保留字段中...因此可以快速获取。

答案 2 :(得分:1)

为便于实施,您可以使用PowerPrefernce

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

保存数据

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

获取数据

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

答案 3 :(得分:0)

尝试更改这行,并以Customlide片段

  

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

成为

  

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

也使用

  

editor.apply();

当您想优先保存新数据时。希望对您有帮助