2016-07-29 139 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

我需要閱讀更多我認爲,但感謝您的幫助:) –