android 使用SharedPreferences保存int

gzszwxb4  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(104)

我希望用户能够在购买“删除广告”项目时,每个级别最多使用“显示回复”功能2次,并在应用程序关闭并重新启动时使用“SharedPreferences”继续此功能。
在游戏中,我确保“显示答案”在每个关卡中最多可以点击2次,但当你退出关卡并返回或游戏关闭和打开时,这个消失,可以再次按2次。

public class MainActivity extends Activity implements View.OnClickListener {
    
    SharedPreferences preferences;
    Button revealButton, askButton, doneButton;
    SharedPreferences.Editor editor;
    public static final String SHARED_PREFS = "sharedPrefs";
    private int clicks;

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

        preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        editor = preferences.edit();
        CurrentQuestion = preferences.getInt("CurrentQuestion" + code, 0);
        currentLevelQuestion = preferences.getInt("currentLevelQuestion" + code + "_" + branch, 1);

        //AdMob Ads
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
        //=======Designed for children==========//
        RequestConfiguration requestConfiguration = MobileAds.getRequestConfiguration()
                .toBuilder().setTagForChildDirectedTreatment(TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE)
                .setMaxAdContentRating(MAX_AD_CONTENT_RATING_G)
                .build();
        MobileAds.setRequestConfiguration(requestConfiguration);
//=======================================//

        mAdView = findViewById(R.id.adView);
        String purchasedItem = preferences.getString("purchased", null);
        if (purchasedItem == null) {
            AdRequest adRequest = new AdRequest.Builder()
                    .build();
            mAdView.loadAd(adRequest);
        } else {
            mAdView.setVisibility(View.GONE);
        }

        loadRewardedAd();
        progressBar = findViewById(R.id.progressBar);

        //Initialize views
        questionNumberTV = findViewById(R.id.questionNumber);
        scoreTV = findViewById(R.id.score);
        questionTV = findViewById(R.id.questionText);
        LevelNumberTV = findViewById(R.id.level_number);
        revealButton = findViewById(R.id.reveal);
        askButton = findViewById(R.id.ask);
        resetButton = findViewById(R.id.reset);
        skipButton = findViewById(R.id.skip);
        doneButton = findViewById(R.id.done);
        questionImage = findViewById(R.id.questionImage);
        voiceImage = findViewById(R.id.voiceImage);
        answerGridview = findViewById(R.id.answerGridview);
        choicesGridview = findViewById(R.id.choicesGridview);

        //Scroll textView
        questionTV.setMovementMethod(new ScrollingMovementMethod());
        //Initialize the new question
//        LevelNumberTV.setText(getString(R.string.level) + " " + code);
        retrieveQuestionTile();
        retrieveData();
    }

case R.id.reveal:
//                NextQuestion();
                clicks++;
                Log.e("Click+1", Integer.toString(clicks));
                Log.e("Test", "Click test break");
                if (isRunning == true) {
                    countDownTimer.cancel();
                    if (tickPlayer != null && tickPlayer.isPlaying()) {
                        tickPlayer.stop();
                    }
                }if (purchasedItem != null && clicks >= 2){
                    SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt("clicks", clicks);
                    editor.apply();
                    revealButton.setEnabled(false);
                    Toast.makeText(this, getString(R.string.purchased_warning), Toast.LENGTH_LONG).show();
                }
                if (purchasedItem == null) {
                    Reveal_Answer_Dialog();
                } else {
                    currentLetter = 0;
                    for (int i = 0; i < answer.length; i++) {
                        String Letter = String.valueOf(answer[i]);
                        char compare = Letter.charAt(0);
                        user_submit_answer[currentLetter] = compare;
                        if (currentLetter + 1 < answer.length) {
                            currentLetter = currentLetter + 1;
                        }

                        //Update UI
                        recyclerAnswersAdapter = new RecyclerAnswersAdapter(user_submit_answer, this);
                        answerGridview.setAdapter(recyclerAnswersAdapter);
                        recyclerAnswersAdapter.notifyDataSetChanged();
                    }

                }
                break;
public void Failed_Level_Dialog() {
    wrongPlayer = MediaPlayer.create(MainActivity.this, R.raw.wrong);
}

    clicks = 0;
public void Finish_Level_Dialog() {
    editor.putString("done" + "_" + code + "_" + branch, "yes");
    editor.apply();

    clicks = 0;
}

字符串
1.我用SharedPreferences将数据保存为int,然后读取case中的数据:点击++。
1.我设法去激活按钮时,按钮被按下2后,在每个级别,但这重置时,游戏来到主页或当游戏关闭和打开。

tf7tbtn2

tf7tbtn21#

SharedPreferences旨在在应用执行之间持久保存数据。但是,它不会持久化应用卸载。这意味着如果用户卸载并重新安装应用程序,数据就会丢失。因此,在您的情况下,SharedPreferences听起来可能不是最佳解决方案。如果你想知道用户是否在每个级别中点击了最多2次,无论应用程序是否卸载,那么你应该将此信息保存在数据库中。
在我看来,最好的选择,你有是保存点击次数内的数据库。然后,您可以在用户每次单击“显示答案”选项时执行检查。如果单击次数少于两次,则应显示该选项,否则可以隐藏该选项或显示一条消息。
因此,在实时数据库中,这样的结构可以做到这一点:

db
|
--- $uid
     |
     --- $levelId: 1

字符串
其中levelId是级别的ID,1是点击次数。

相关问题