2015-02-07 66 views
0

我有2個活動。在第一個我選擇一個級別。在第二個我玩遊戲。在第二個活動中,我回答問題,每次我正確回答時,我向我的數組列表中添加一個值。當遊戲結束時,用戶返回級別選擇活動,並在那裏他可以看到他的分數。例如:Level1:您正確回答了17個問題。我怎樣才能做到這一點?我嘗試使用sharedpreferences但沒有運氣。它總是顯示0.我猜測它是因爲它在遊戲開始時獲得了值,當列表爲空時。遊戲結束後,如何在列表填充後顯示值?使用SharedPreferences保存用戶得分

這是女巫的遊戲活動創建一個列表,在其中存儲值,並回答問題:

public class MainActivity extends Activity { 

    Button mYes; 
    Button mNo; 
    TextView mQuestion; 
    Button btnClosePopup; 
    TextView mPopupText; 




    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     final int[] count = {0}; // Global array. 
     final int[] score = {0}; 
     //final int[] intArray = new int[3]; 
     mYes = (Button) findViewById(R.id.button2); 
     mPopupText = (TextView)findViewById(R.id.popupTekstas); 
     btnClosePopup = (Button)findViewById(R.id.btn_close_popup); 
     mNo = (Button) findViewById(R.id.button); 
     mQuestion = (TextView) findViewById(R.id.textView); 



     //Creating questions. (Question, boolean, answer). 
     final Question first = new Question("Do i understand this code?", true, "Only Jesus knows"); 
     final Question second = new Question("Why dont i understand this code?", false, "Im not Jesus"); 
     final Question third = new Question("Why I am not Jesus?", true, "2fat."); 
     //Creating Lists for questions and boolean values. 
     final ArrayList<Question> questions = new ArrayList<Question>(); 
     final ArrayList<Boolean> type = new ArrayList<Boolean>(); 

     final ArrayList<Integer> points = new ArrayList<Integer>(); 

     SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE); 

     SharedPreferences.Editor editor = sharedPref.edit(); 

     editor.putInt("taskai", points.size()); 

     editor.commit(); 

     //mResult.setText("zdr"); 

     //Adding questions to the question list 
     questions.add(first); 
     questions.add(second); 
     questions.add(third); 



     // Adding boleans to the boolean list 
     type.add(first.correctAnswer); 
     type.add(second.correctAnswer); 
     type.add(third.correctAnswer); 

     //Show the first question on Activity start. 
     mQuestion.setText(questions.get(0).question); 


     // Open PopUp Window on true button click. 
     mYes.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       initiatePopupWindow(); 
       if(type.get(count[0])){ 

        ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!"); 
       } else { 
        ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!"); 
       } 
       //Show the first answer on first button click. 
       ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer); 
     // When PopUp button closes open the next question with the if/else conditions. 
      btnClosePopup.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        //if the question is true show next question/ else close app 
        if (type.get(count[0])) { 
         points.add(1); // if the answer is correct add +1 to the list. 
         score[0]++; 
         if(questions.size()-1 == count[0]) // if you count[0] is init to 0 
         { 

          AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
          builder.setTitle("WInner"); 
          builder.setMessage("You won, play again?"); 
          builder.setCancelable(false); 
          builder.setPositiveButton(android.R.string.yes, 
            new DialogInterface.OnClickListener() { 
             public void onClick(DialogInterface dialog, int id) { 
              // just close dialog 
              dialog.cancel(); 
             } 
            }); 
          builder.setNegativeButton(android.R.string.no, 
            new DialogInterface.OnClickListener() { 
             public void onClick(DialogInterface dialog, int id) { 
             finish(); 

             // mResult.setText("" + points.size()); 

             } 
            }); 

          // Create dialog from builder 
          AlertDialog alert = builder.create(); 

          // Show dialog 
          alert.show(); 
          count[0]=0; 


         } 
         else if(questions.size()-1 < count[0]) 
          try { 
           throw new Exception("Invalid "); 
          } catch (Exception e) { 
           e.printStackTrace(); 
          } 
         else 
         count[0]++; 

         mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore 
         pwindo.dismiss(); 
        } else { 
         count[0]++; 

         mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore 
         pwindo.dismiss(); 
        } 

       } 
      }); 

      } 
     }); 

     mNo.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       initiatePopupWindow(); 
       if(!type.get(count[0])){ 

        ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Correct!"); 
       } else { 
         ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("False!"); 
       } 
       ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstas)).setText(questions.get((count[0]) % questions.size()).answer); 

       btnClosePopup.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 

         if (!type.get(count[0])) { 
          points.add(1); // if the answer is correct add +1 to the list. 
          score[0]++; 
          if(questions.size()-1 == count[0]) // if you count[0] is init to 0 
          { 

           AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
           builder.setTitle("WInner") 
             .setMessage("You won, play again?") 
             .setCancelable(false) 
             .setPositiveButton(android.R.string.yes, 
               new DialogInterface.OnClickListener() { 
                public void onClick(DialogInterface dialog, int id) { 
                 // just close dialog 
                 dialog.cancel(); 
                } 
               }) 
             .setNegativeButton(android.R.string.no, 
               new DialogInterface.OnClickListener() { 
                public void onClick(DialogInterface dialog, int id) { 
                 finish(); 
                 //mResult.setText("" + points.size()); 





                } 
               }); 

           // Create dialog from builder 
           AlertDialog alert = builder.create(); 

           // Show dialog 
           alert.show(); 
           count[0]=0; 

           ((TextView)pwindo.getContentView().findViewById(R.id.popupTekstasTiesaArNe)).setText("Klaida!"); 
          } 
          else if(questions.size()-1 < count[0]) 
           try { 
            throw new Exception("Invalid "); 
           } catch (Exception e) { 
            e.printStackTrace(); 
           } 
          else 
           count[0]++; 

          mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore 
          pwindo.dismiss(); 
         } else { 
          count[0]++; 
          mQuestion.setText(questions.get(count[0]).question); // you dont need calculate the module anymore 
          pwindo.dismiss(); 
         } 

        } 
       }); 


      } 
     }); 
    } 

    public PopupWindow pwindo; 

    public void initiatePopupWindow() { 
      try { 
// We need to get the instance of the LayoutInflater 
      LayoutInflater inflater = (LayoutInflater) MainActivity.this 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      View layout = inflater.inflate(R.layout.popup, 
        (ViewGroup) findViewById(R.id.popup_element)); 
      pwindo = new PopupWindow(layout, 500, 570, true); 
      pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0); 

      btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup); 
      btnClosePopup.setOnClickListener(cancel_button_click_listener); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public View.OnClickListener cancel_button_click_listener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      pwindo.dismiss(); 
     } 
    }; 

在該活動中我嘗試獲取列表值,並將其:

public class LevelSelectActivity extends MainActivity { 

    Button mLevel1; 
    public TextView mResult; 

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

     SharedPreferences sharedPref = getSharedPreferences("level1", Context.MODE_PRIVATE); 

     int result = sharedPref.getInt("taskai", 0); 


     mLevel1 = (Button)findViewById(R.id.level1); 
     mResult = (TextView)findViewById(R.id.Resultas); 
     // mResult.setText(players.size()-1 + "/" + 3); 

     mResult.setText("" + result); 

     mLevel1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Intent startGame = new Intent(LevelSelectActivity.this, MainActivity.class); 
       startActivity(startGame); 

      } 
     }); 
    } 
+0

你可以通過像LevelSelectActivity意圖參數像startGame.putExtras(「key」,value);兩者都是字符串,只有當你想獲得MainActivity然後調用getIntent()。getStringExtra(「key」)時,它纔會執行。 – Hanuman 2015-02-07 12:34:37

+0

遊戲結束時保存分數。也真的不需要使用ArrayList。只要使用一個int值並且每當玩家獲得一個點時就增加它。 – Longi 2015-02-07 12:35:06

+0

但是這個分數會保存嗎? – Arina 2015-02-07 12:35:30

回答

0

我不確定您的代碼中發生了什麼,但我確實知道首選項不是傳遞數據的最佳方式。

您最好使用set results/ get results pattern

的第一項活動使用

startActivityForResult(intent, LEVEL_REQUEST); 

它還會創建一個函數來讀回數據它完成之後。這會是這個樣子:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // Check which request we're responding to 
    if (requestCode == LEVEL_REQUEST) { 
     // Make sure the request was successful 
     if (resultCode == RESULT_OK) { 

     } 
    } 
} 

活動將結果發送將做到這一點,以公佈結果:

Intent resultsIntent=new Intent(); 
//Set data in the intent, note this intent is returned to the original function in `onActivityResult` 
setResult(Activity.RESULT_OK,resultsIntent); 

第二活動採用