0

我在我的代码中添加了一个 onRestoreInstanceState 和 onSaveInstanceState 来保存一个要保存的变量,但是该变量在旋转后没有得到保留

我试着用谷歌搜索,我看到 Logcat 和 android 确实调用了这两个函数这里是 Logcat 的重要部分

I/SimpleActivity: PlayTheGame #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: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on an null object reference

然后我将 onCreate 中的代码更新为此

if(savedInstanceState!=null)
    sc = savedInstanceState.getInt("sc",0);
    else
        sc = 0;

这没有返回任何错误,但旋转后 sc 仍然再次设置为零

4

1 回答 1

0

不是说它不起作用,而是onRestoreInstanceState()在之后调用之后onStart()调用onCreate()

您在其中进行所有处理,onCreate()并且只将sc存储在OnRestoreInstanceState()while onCreate()hassc = 0;

这将导致您正在进行的所有处理都onCreate()使用 0 值而不是您保存的sc值。因为它还没有到达活动生命周期中获取你的sc值的步骤。

在你的方法中使用sc = savedInstanceState.getInt("sc", 0);而不是。您可以摆脱该方法。sc = 0onCreate()onRestoreInstanceState()

这样,如果您之前通过保存sconSaveInstanceState(),您将能够在您的onCreate(). 如果您没有保存它,它将使用默认值 0。

编辑:

检查savedInstanceState是否为 null,因为如果没有传入任何内容onSaveInstanceState(),通常在第一次运行时会发生这种情况,它将为 null。

arr = new ArrayList<String>(dictionary.keySet());
sc = savedInstanceState==null ? 0 : savedInstanceState.getInt("sc", 0);
readFileData();//read file data into the dictionary
于 2019-01-25T11:47:00.390 回答