我在代码中添加了onRestoreInstanceState和onSaveInstanceState来保存要保存的变量,但是该变量在旋转后并没有得到保留
我尝试谷歌搜索,我已经看到Logcat和android确实调用了这两个函数,这是Logcat的重要部分
I / SimpleActivity:PlayPalm游戏#9469915 onPause()
I / SimpleActivity:PlayTheGame#9469915 onSaveInstanceState()
I / SimpleActivity:PlayTheGame#9469915 onStop()
I / SimpleActivity:PlayTheGame#9469915 onDestroy()
I / SimpleActivity:PlayTheGame#245612069 onStart()
I / SimpleActivity:PlayTheGame#245612069
onRestoreInstanceState(bundle = Bundle [{points = -4,android:viewHierarchyState = Bundle [{android:views = {/ 一些奇怪的数字 /} I / SimpleActivity: PlayTheGame#245612069 onResume()
因此,似乎我已完成的功能被调用但未实现
package com.example.rishabhjain.myapplication;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import stanford.androidlib.AutoSaveFields;
import stanford.androidlib.SimpleActivity;
//SimpleActivity is standford library I have downloaded,It only makes
//Syntax easy. Not used uch in this code although
public class PlayTheGame extends SimpleActivity {
private static Map<String, String> dictionary = null;//keeps words and
//defns
private static ArrayList<String> arr = null;//keeps only words
TextView score = null;
private MediaPlayer mp;//for starting music when playing the game
private int sc;//this variable saves score
//the next two functions read files containing words and their meanings
private void readFileData() {
Scanner scan = new Scanner(
getResources().openRawResource(R.raw.text)//scans from raw file
);
readIt(scan);//readIt and store it in dictionary
try {//in try in case user didn't added a word and file was not created
Scanner scan2 = new Scanner(
openFileInput("dictionary.txt")//reads the user saved words
);
readIt(scan2);
} catch (Exception e) {
//do noting
}
}
private void readIt(Scanner scan) {
/*splits appart the words of each file from their definitions*/
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] parts = line.split("\t");//stores the splitted parts
if (parts.length < 2)
continue;//in case encountered an emply line
dictionary.put(parts[0], parts[1]);//words and correspondind defns
//added to the dictionary
arr.add(parts[0]);//stores words
}
}
//to reset word after each click or onCreate
private void resetWord() {
Random randy = new Random();
int nextInt = randy.nextInt(arr.size());
String nextWord = arr.get(nextInt);
TextView word = (TextView) findViewById(R.id.word);
for (; nextWord.equals(word.getText()); ) {
nextInt = randy.nextInt(arr.size());
nextWord = arr.get(nextInt);
}
String realdefn = dictionary.get(nextWord);
List<String> options = new ArrayList<>(dictionary.values());
options.remove(realdefn);
Collections.shuffle(options);
options = options.subList(0, 3);
options.add(realdefn);
Collections.shuffle(options);
word = (TextView) findViewById(R.id.word);
word.setText(nextWord);
//the listview, onClick of it is on onCreate
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
options
);
list.setAdapter(adapter);
}
//checks if the user clicked correct answer or not it too works file
private void checkCorrect(String defn) {
TextView word = (TextView) findViewById(R.id.word);
score = (TextView) findViewById(R.id.score);
if (defn.equals(dictionary.get(word.getText()))) {
sc++;
score.setText("Score: " + sc);
toast("Nice One");
} else {
sc--;
score.setText("Score: " + sc);
toast("booooo!");
}
resetWord();
}
//To save the variable sc when performing rotation but not working,sc
//getting
//set to zero after rotation
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("sc", sc);
}
//this may be the reason of the problem to the world either
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
sc = savedInstanceState.getInt("sc");
}
//onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_the_game);
setTraceLifecycle(true);//library function that generates Log
//nothing to do with app, just displays the activity life cycle
dictionary = new TreeMap<>();
arr = new ArrayList<String>(dictionary.keySet());
sc = 0;
readFileData();//read file data into the dictionary
resetWord();//reset word
//setting the onClick for the List works fine
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String defn = parent.getItemAtPosition(position).toString();
checkCorrect(defn);
}
});
//plays the song Makhana, nice song must listen :)
//works fine
mp = MediaPlayer.create(this, R.raw.recordings);
mp.start();
}
//the layout of this activity has a button to other activity called AddWord
//onResume when you return from that activity, works fine
@Override
protected void onResume() {
super.onResume();
mp.start();
}
//onPause when goning from this activity to AddWord, this too works fine
@Override
protected void onPause() {
super.onPause();
mp.pause();
}
//this directs to AddWord, attached with a button, works fine
public void addAWordClick(View view) {
Intent intent = new Intent(this, AddWord.class);
startActivity(intent);
}
}
游戏就像程序从文件中读取两件事:单词及其含义,然后显示单词和4个选项,如果选择正确,则得分会增加,否则得分会降低。该分数保存在变量sc中。我希望在屏幕旋转时保留此变量。但这似乎没有发生
我也尝试过:
我尝试删除onRestoreInstanceState并更改了代码
arr = new ArrayList<String>(dictionary.keySet());
sc = savedInstanceState.getInt("sc",0);// previosly sc=0
readFileData();
但是会产生错误
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'int android.os.Bundle.getInt(java.lang.String,int)'
然后我将onCreate中的代码更新为此
if(savedInstanceState!=null)
sc = savedInstanceState.getInt("sc",0);
else
sc = 0;
这没有返回任何错误,但是仍然在旋转sc重新设置为零之后
答案 0 :(得分:0)
不是不起作用,而是在onRestoreInstanceState()
之后调用onStart()
,在onCreate()
之后调用。
您在onCreate()
中进行所有处理,并且仅将{strong> sc 存储在OnRestoreInstanceState()
中,而onCreate()
具有sc = 0;
这将导致您在onCreate()
中执行的所有处理都使用0值而不是您保存的 sc 值。因为它尚未到达“活动生命周期”中获取其 sc 值的步骤。
在您的sc = savedInstanceState.getInt("sc", 0);
方法中使用sc = 0
代替onCreate()
。您可以摆脱onRestoreInstanceState()
方法。
这样,如果您以前通过onSaveInstanceState()
保存了 sc ,则可以在onCreate()
中获得该值。如果不保存,它将使用默认值0。
编辑:
检查 savedInstanceState 是否为空,因为如果没有从onSaveInstanceState()
传入任何内容(通常在首次运行时传入),则该值为null。
arr = new ArrayList<String>(dictionary.keySet());
sc = savedInstanceState==null ? 0 : savedInstanceState.getInt("sc", 0);
readFileData();//read file data into the dictionary