简体   繁体   中英

App does not save data before activity closes, or not loading data after activity is created - SharedPreferences

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

See link above to original questions and responses from other people... to sum it up, SharedPreferences is either not saving or not loading data properly... see pictures of my app, it will better show the problem:

Screenshots of my app in progress

As far as the code behind main activity, I have tried different things suggested by different people, and i appreciate anyone who was or is willing to help :) At this very moment, this is the code relevant to the problem in MainActivity: (Please note: To save on space, I am only showing one Bundle (getFromQuizOne), but I have the same kind of Bundle / Bundle code for all 10 quizzes. Also, I only put in one quiz button setOnClickListener, but same kind of code applies for all other quiz buttons).

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

                //Call arrayMethod, which uses for loop to get and display value of points for each quiz
                arrayMethod();
            }//end if

            //My actual project has same kind of Bundle for all other quizzes, but to save space, i am just listing Bundle for quiz 1


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

            //My project has button click listeners for all 10 quizzes, that look similar to quizOneButton onClick action listener, but to save on space, I didn't paste it here


        public void arrayMethod()
        {
            int[] points = {numberQuizOnePoints, numberQuizTwoPoints, numberQuizThreePoints,
            numberQuizFourPoints, numberQuizFivePoints, numberQuizSixPoints, numberQuizSevenPoints,
            numberQuizEightPoints, numberQuizNinePoints, numberQuizTenPoints};

            String[] prefKeys = {"quizOnePointsYeah", "quizTwoPointsYeah", "quizThreePointsYeah",
            "quizFourPointsYeah", "quizFivePointsYeah", "quizSixPointsYeah", "quizSevenPointsYeah",
            "quizEightPointsYeah", "quizNinePointsYeah", "quizTenPointsYeah"};

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

            for (int i = 0; i < 10; i++)
            {
                if (shareInt.getInt(prefKeys[i], 0) > 0)
                {
                    points[i] = shareInt.getInt(prefKeys[i], 0);
                }//end if
                else
                {
                    points[i] = 0;
                }//end else
            }//end for loop

            //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 void arrayMethod
    }//end class MainMenu

I'm not completely sure that I know what you want, but from my understanding you should be loading and saving that data during a state that you know will get called such as onPause(); . You should also take a look at the Android Activity Lifecycle

here's a somewhat related snippet from my app

@Override
protected void onPause(){
    super.onPause();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState); // the UI component values are saved here.
    outState.putStringArrayList("mList", new ArrayList<>(fretList));
    Toast.makeText(this, "Activity state saved", Toast.LENGTH_SHORT).show();
}

@Override
protected void onRestoreInstanceState(Bundle inState) {
    super.onRestoreInstanceState(inState); // the UI component values are saved here.
    // if there is a non empty bundle, then pull arraylist from it, clear old list
    // just in case, and add all bundle items to it.
    if (inState != null) {
        ArrayList bundledList = inState.getStringArrayList("mList");
        if (bundledList != null && bundledList.size() > 0) {
            fretList.clear();
            fretList.addAll(bundledList);
        }
    }
    mAdapter.notifyDataSetChanged();
    Toast.makeText(this, "Activity state restored", Toast.LENGTH_SHORT).show();
}

Edit: I'm now looking over your other linked question trying to understand your question better. You can do some simple checking with Log.d() to find out where you lose the bundle/data

if (getFromQuizOne != null)
    {
        Log.d("Test", "not null");
    } else {
        Log.d("Test", "null");
    }

If you want to explicitly save something without waiting you can move it to your own method and call it whenever you want (this is using shared prefs rather than bundle):

public void save(Context context, String text) {
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    editor.putString("someString", text);
    editor.commit();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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