Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

java - Data on main activity doesn't save / load properly with SharedPreferences

If you look through each picture, from left to right, you'll notice on the last picture on the right, the points for Quiz One goes to 0... this is my problem

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 :(

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...

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! :)

Different blocks of code, most important blocks of code that pertain or relate to the problem I'm having

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

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 :(

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...