SharedPreferences 无法正确保存/加载有关主要活动的数据 [英] Data on main activity doesn't save / load properly with SharedPreferences

查看:45
本文介绍了SharedPreferences 无法正确保存/加载有关主要活动的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您从左到右查看每张图片,您会注意到最后一张图片在右边,测验一的分数变为 0...这是我的问题

这是我正在使用 Android Studio 开发的测验应用程序...我正在尝试使用 SharedPreferences,使用 putInt 和 getInt 方法将每个测验的得分值放入变量中,并存储在字符串下名称,然后 onCreate 的一部分是使用 putInt 方法中引用的字符串名称来 getInt ......当用户第一次打开应用程序时,主要活动应该加载为全 0......当用户完成测验时,分数是传递回主要活动,积分应该留在那里......无论用户继续前进,转到另一个屏幕,另一个应用程序还是完全关闭应用程序,每个测验的得分都应该保留,但他们不't :(

This is a quiz app that i'm working on, with Android Studio... I am trying to use SharedPreferences, using putInt and getInt methods to put the value of points scored for each quiz into variables, stored under a String name, then part of onCreate is to getInt using the String name referenced in the putInt m ethods... main activity should load with all 0s when user first opens the app for the first time... when user completes a quiz, points are passed back to main activity, and the points should STAY there... doesn't matter if user moves on, goes to another screen, another app, or close the app altogether, the points scored for each quiz should stay, but they don't :(

目前,主活动上的每个测验按钮关闭主活动(完成();),每个测验的最后一个活动调用主活动并通过得分......我之前也有每个测验按钮调用onStop()方法主要活动关闭,并且 onStop() 方法使用 SharedPreferences.Editor 和 putInt 方法将每个点值的值放在主要活动上...然后我在 onCreate 开始时有 SharedPreferences 和 getInt 方法...

Currently, each quiz button on main activity closes main activity ( finish(); ), and the last activity of each quiz calls main activity and passes points scored... I also have each quiz button calling onStop() method before main activity closes, and the onStop() method uses SharedPreferences.Editor and putInt methods to put the value of each point value on main activity... and then I have SharedPreferences and getInt methods towards the beginning of onCreate...

所以基本上,我想要发生的是,每次用户单击测验按钮时,应该使用 putInt 方法、使用 String 名称和实际的 int 变量保存每个测验的得分m 用于每个测验的积分,当用户在完成测验后返回主要活动时,用户已经得分的任何积分都应通过 getInt 方法自动加载...请参阅下图了解我的程序中的一些编码...让我知道是否有人需要查看更多代码,我希望有人可以帮助我!:)

So basically, what i want to have happen, is every time user clicks on a quiz button, the points scored for each quiz should be saved, using putInt methods, using a String name, and the actual int variable that i'm using for the points for each quiz, and when user goes back to main activity after completing a quiz, any points that user already scored should automatically load, via getInt methods... see picture below for some of the coding in my program... let me know if anyone needs to see more code, and I hope someone can help me out! :)

不同的代码块,与我遇到的问题相关或相关的最重要的代码块有

我已经尝试了以前人们的建议,但它仍然不起作用...请参阅下面的部分代码并告诉我需要修复的内容:

I've tried what previous people have suggested, but it's still not working... see parts of my code below and let me know what needs fixed:

//Get points from Quiz One
        Bundle getFromQuizOne = getIntent().getExtras();
        if(getFromQuizOne != null)
        {
            //Get points from Quiz One
            numberQuizOnePoints = getFromQuizOne.getInt("PointsFromAllQuizOne");

            SharedPreferences shareInt = getApplicationContext().getSharedPreferences(QUIZ, MODE_PRIVATE);
            SharedPreferences.Editor editInt = shareInt.edit();

            //Save the value of points from Quiz One with SharedPreferences
            editInt.putInt("quizOnePointsYeah", numberQuizOnePoints);
            editInt.commit();

            //Get the value of points from all other quizzes with getInt from SharedPreferences
            numberQuizTwoPoints = shareInt.getInt("quizTwoPointsYeah", 0);
            numberQuizThreePoints = shareInt.getInt("quizThreePointsYeah", 0);
            numberQuizFourPoints = shareInt.getInt("quizFourPointsYeah", 0);
            numberQuizFivePoints = shareInt.getInt("quizFivePointsYeah", 0);
            numberQuizSixPoints = shareInt.getInt("quizSixPointsYeah", 0);
            numberQuizSevenPoints = shareInt.getInt("quizSevenPointsYeah", 0);
            numberQuizEightPoints = shareInt.getInt("quizEightPointsYeah", 0);
            numberQuizNinePoints = shareInt.getInt("quizNinePointsYeah", 0);
            numberQuizTenPoints = shareInt.getInt("quizTenPointsYeah", 0);

            //Sum up points from each quiz, and put sum in totalPoints variable
            totalPoints = numberQuizOnePoints + numberQuizTwoPoints + numberQuizThreePoints
                    + numberQuizFourPoints + numberQuizFivePoints + numberQuizSixPoints
                    + numberQuizSevenPoints + numberQuizEightPoints + numberQuizNinePoints
                    + numberQuizTenPoints;


            quizOnePointsText.setText(String.format("%d", numberQuizOnePoints));
            quizTwoPointsText.setText(String.format("%d", numberQuizTwoPoints));
            quizThreePointsText.setText(String.format("%d", numberQuizThreePoints));
            quizFourPointsText.setText(String.format("%d", numberQuizFourPoints));
            quizFivePointsText.setText(String.format("%d", numberQuizFivePoints));
            quizSixPointsText.setText(String.format("%d", numberQuizSixPoints));
            quizSevenPointsText.setText(String.format("%d", numberQuizSevenPoints));
            quizEightPointsText.setText(String.format("%d", numberQuizEightPoints));
            quizNinePointsText.setText(String.format("%d", numberQuizNinePoints));
            quizTenPointsText.setText(String.format("%d", numberQuizTenPoints));
            actualPointsText.setText(String.format("%d", totalPoints));
        }//end if

这是每个测验捆绑包的样子,除了为相应测验适当命名的变量和字符串名称......我开始认为这可能不是获得 int 值的最佳方法从另一个活动传递给主活动,但我想不出另一种方法来做到这一点......在这种情况下,我试图保存我从测验中立即获得的 numberQuiz#Points 的值,并从所​​有其他 int 变量中获取点的值,然后在应用程序的主屏幕上显示所有...但这不起作用:(

This is what each quiz Bundle looks like, with the exception of the variables and string names named appropriately for the corresponding quiz... I'm starting to think maybe this isn't the best way to get an int value that is passed to Main Activity from another activity, but I can't think of another way to do it... in this instance, I'm trying to save the value of numberQuiz#Points that I'm getting from a quiz right away, and getting the value of points from all other int variables, and then displaying all on the main screen of the app... but this isn't working :(

以下是测验按钮 setOnClickListener 背后的代码示例:

Here is an example of what the code behind a quiz button setOnClickListener looks like:

//Directs user to Quiz One, first screen
        quizOneButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Subtract out any points that user already got for Quiz 1 from total...
                //In case user wants to or has to re-take Quiz 1
                totalPoints = totalPoints - numberQuizOnePoints;

                //Subtract out any points that user already got for Quiz 1 from itself, equal 0
                numberQuizOnePoints -= numberQuizOnePoints;



                //Go to the Quiz One, first screen

                Intent directToQuizOnePartOne = new Intent();
                directToQuizOnePartOne.setClass(getBaseContext(), QuizOnePartOne.class);
                startActivity(directToQuizOnePartOne);
                finish();
            }//end void onClick quizOne
        });//end setOnClickListener quizOne

这是给定测验的最后一个活动的代码:(在本例中,测验 1 的最后一个活动,即传递点回到 MainAcvitity 的活动:

And this is what the code looks like for the last activity of a given quiz: (In this case, the last activity for Quiz 1, the activity that is passing points back to MainAcvitity:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class QuizOnePartFour extends AppCompatActivity
{
    //Create variables for button and TextViews

    TextView totalPointsQuizOneTextView;
    Button returnToMainOne;
    int actualPointsAllQuizOne;

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

        Bundle bundleFour = getIntent().getExtras();
        actualPointsAllQuizOne = bundleFour.getInt("CarryOverThreeQuizOne");

        //Assign variables to appropriate buttons and TextViews

        totalPointsQuizOneTextView = (TextView) findViewById(R.id.txtTotalPointsQuizOne);
        returnToMainOne = (Button) findViewById(R.id.btnReturnToMainOne);

        totalPointsQuizOneTextView.setText(String.format("%d", actualPointsAllQuizOne));

        returnToMainOne.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //Return to main menu screen

                Bundle bundleFive = new Bundle();
                bundleFive.putInt("PointsFromAllQuizOne", actualPointsAllQuizOne);

                Intent directToMainMenuOne = new Intent();
                directToMainMenuOne.setClass(getBaseContext(), MainMenu.class);
                directToMainMenuOne.putExtras(bundleFive);
                startActivity(directToMainMenuOne);
                finish();
            }//end void onClick returnToMainOne
        });//end setOnClickListener returnToMainOne
    }//end void onCreate QuizOnePartFour
}//end class QuizOnePartFour

推荐答案

不要手动调用 onStop 这些是您重写的特殊方法,仅用于执行一些清理工作.

Don't manually call onStop these are special methods that you override only to perform some clean ups.

它是活动生命周期方法之一.您应该将该代码移至按钮单击事件.

It is one of the activity life cycle method. You should move that code to the button click event.

这篇关于SharedPreferences 无法正确保存/加载有关主要活动的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆