2016-12-14 64 views
0

我正在製作文本遊戲。我在我的代碼開頭聲明瞭一個「public int x = 0」。 x的值正在控制用戶進度和故事的正文以及單選按鈕的文本。我需要保存x的值,並且能夠加載它以便使用下面的代碼保存用戶進度。我之前通過複製代碼進行了保存工作,但它只是將x的值與加載故事的主要文本一起打印出來。在內部存儲器中保存txt文件中的整數值

   /* 
       Saves the game data 
       */ 

       String text = t.getText().toString(); 
       try { 
        FileOutputStream fos = openFileOutput(TEXTFILE, Context.MODE_PRIVATE); 
        fos.write(text.getBytes()); 
        fos.close(); 
        t.setText(""); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 


    /* 
    loads the game data 
    */ 
    try { 
     FileInputStream fis = openFileInput(TEXTFILE); 



     TextView t = (TextView) findViewById(R.id.mainText); 


     t.setText(null); 


     BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis))); 

     String line; 


     while ((line = reader.readLine()) != null){ 
      t.append(line); 
      t.append("\n"); 
     } 
     fis.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

//story logic 

      }else if (rb1.isChecked() && (x==2)){ 
       t.setText("You put the key in your pocket"); 
      } else if (rb2.isChecked()&& (x==2)) { 
       t.setText("You took the file"); 
+0

請不要存儲在一個文本文件中。改爲使用[SharedPreferences](http://stackoverflow.com/a/40979079/6615718)。有了這個,你可以在谷歌應用程序商店雲 –

+0

存儲故事的進展如何保存一個TextView的價值 – KingBuzzo

+0

像字符串myValue = sharedPref.getInt(getString(R.string.textView),defaultValue); –

回答

1

爲了存儲這樣的事情你會得到更好的使用SharedPreferences

節省:

​​

負載:

int value = PreferenceManager.getDefaultSharedPreferences(context).getInt("KEY", defaultValue);

+0

你能解釋一下嗎?我是一個noob。當我把這個代碼在它沒有工作。 im使用的值被稱爲x,並在代碼的開頭聲明。另外,我需要知道如何保存在我的代碼中稱爲t的TextView的值。 – KingBuzzo

+0

另外我還需要保存一個名爲rb1的單選按鈕文本的值以及文本的可見性。 – KingBuzzo

相關問題