2016-07-29 59 views
0

Data on main activity doesn't save/load properly with SharedPreferences应用程序不保存数据 - SharedPreferences

见上文从其他人的原始的问题和答案的链接......概括起来讲,SharedPreferences或者不保存或不正确加载数据...看到我的应用程序的照片,这将更好地说明问题:由不同的人提出

Screenshots of my app in progress

至于主要活动背后的代码,我曾尝试不同的东西,并且我感谢任何曾经或愿意帮助的人:)在在这个时候,这是与MainActivity中的问题相关的代码:(请注意:为了节省空间,我只显示一个Bundle(getFromQuizOne),但是对于所有10个测验,我都有相同类型的Bundle/Bundle代码。此外,我只放入一个测验按钮setOnClickListener,但同样的代码适用于所有其他测验按钮)。

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

请不要在问题中发布整个代码。在大多数情况下,只有相关的代码是足够的。 –

+0

这么多重复的代码。尝试将这些代码放在方法中,也许使用int数组来表示点等等。我们只需要你正在读取和保存值的代码。 – Shaishav

+0

您需要查看onSaveInstanceState和onRestoreInstanceState。在我的电话,否则我会详细说明。 – ziondreamt

回答

0

我不能完全肯定,我知道你想要什么,但是从我的理解,你应该加载和保存该你知道的状态时的数据将被调用,如onPause();。你也应该看看的Android Activity Lifecycle

这里是从我的应用程序有点相关的片断

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

编辑:现在我正在寻找你的其他链接的问题想明白你的问题更好。你可以做一些简单的检查与Log.d()找出你失去了包/数据

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

如果你想明确地保存的东西,而无需等待,您可以将它移动到你自己的方法,并调用它,只要你想(这使用共享首选项而不是绑定):

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

听起来好像onSaveInstanceState和onRestoreInstanceState用于关闭活动时对系统约束(例如转动手机,从肖像转换为风景),而我的MainActivity由于正常的应用程序行为而关闭时,我正在调用终点();方法在每个测验按钮...一旦用户点击一个测验按钮,主要活动关闭,测验#活动打开...然后主要活动在测验#完成后再次创建并通过积分...我应该仍然使用onSaveInstanceState和onRestoreInstanceState在我的情况? –

+0

这就是我在回答中所链接的内容,你是否仔细阅读并了解它? – ziondreamt

+0

我需要阅读更多我认为,但感谢您的帮助:) –