调用onSaveInstanceState但在onCreate中savedInstanceState为null

时间:2015-05-15 15:24:36

标签: android

已经提出过类似的问题,但我没有找到任何令人满意的解决方案或解释。这个似乎是最接近的,但没有给出解决方案:question

简而言之,我有三个活动,MainActivity,DisplayMessageActivity和EditMessageActivity。在MainActivity中,我有一个EditText视图,我可以在其中输入文本,然后按“发送”按钮,文本将发送到DisplayMessageActivity并显示。

然后我有一个“编辑”按钮,如果按下则启动EditMessageActivity。在EditMessageActivity中,我有另一个EditText视图,我可以在其中输入新文本,当我按“编辑”时,我返回到DisplayMessageActivity并显示新消息。到目前为止一切都很好。

问题是如果我在DisplayMessageActivity中按“编辑”,然后只是从EditMessageActivity返回而没有做任何事情,原始文本就消失了,TextView只是空白。

我已经实施了

   @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        // Store UI to the savedInstanceState
        // This bundle will be passed to onCreate on next call.
       super.onSaveInstanceState(savedInstanceState);

       TextView textView = (TextView) findViewById(R.id.display_text);
        String text = textView.getText().toString();

       savedInstanceState.putString("savedText", text);
       System.out.println("onSaveInstanceState triggered");
    }

我在DisplayMessageActivity中的onCreate方法看起来像

    protected void onCreate(Bundle savedInstanceState){
        // This probably calls the onCreate method in AppCompatActivity?
        super.onCreate(savedInstanceState);
            System.out.println("onCreate triggered");
            if (savedInstanceState != null){
                System.out.println("savedInstanceState is NOT null!");
            }
            Intent intent = getIntent();
            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

            setContentView(R.layout.fragment_display_message);

            TextView textView = (TextView) findViewById(R.id.display_text);
            textView.setTextSize(40);
            textView.setText(message);

    }

按“编辑”时,会显示“onSaveInstanceState triggered”。当我按回EditMessageActivity时,它会显示“onCreate triggered”,但savedInstanceState始终为null。

自程序进入

以来,我不明白这一点
onSaveInstanceState(Bundle savedInstanceState).

我之前曾经问过类似的问题,但在大多数情况下,似乎问题是onSaveInstanceState不是调用,现在似乎就是这样吗?

我还想保存当前会话的数据,而不是将其存储在数据库中,当重新启动整个应用程序时,该数据库将恢复文本。否则可以在onPause()中使用SharedPreferences。

提前致谢

按照kasunbdn的建议进行编辑:

覆盖onBackPressed

@Override
public void onBackPressed(){
    Intent intent = new Intent(EditMessageActivity.this, DisplayMessageActivity.class);
    // Add your extras here ?
    EditText editText = (EditText) findViewById(R.id.edit_text);
    String text = editText.getText().toString();
    System.out.println("Text in onBackPressed: " + text);
    intent.putExtra(EDITMESSAGE, text);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

我的新onCreate方法:

    protected void onCreate(Bundle savedInstanceState){
        // This probably calls the onCreate method in AppCompatActivity?
        super.onCreate(savedInstanceState);
            System.out.println("onCreate triggered");
            if (savedInstanceState != null){
                System.out.println("savedInstanceState is NOT null!");
            }
            Intent intent = getIntent();
            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
            String text = intent.getStringExtra(EditMessageActivity.EDITMESSAGE);
            System.out.println("message: " + message);
            System.out.println("text: " + text);
            setContentView(R.layout.fragment_display_message);

            TextView textView = (TextView) findViewById(R.id.display_text);
            textView.setTextSize(40);
        if (message != null) {
                textView.setText(message);
            } else if (text != null){
                textView.setText(text);
        }
    }

然而,

System.out.println("Text in onBackPressed: " + text);

从不打印,所以我想当我回去时不会调用onBackPressed。

我仍然不明白为什么savedInstanceState为null。

这是DisplayMessageActivity:

package com.example.erikbylow.myclayapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;

import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

/**
 * Created by erikbylow on 5/14/15.
 */
public class DisplayMessageActivity extends AppCompatActivity{
    public final static String EXTRA_MESSAGE = "com.example.erikbylow.myclayapplication.MESSAGEEDIT";

    // onCreate is where an activity receives an intent. All subclasses of Activity must implement this
    @Override
    protected void onCreate(Bundle savedInstanceState){
        // This probably calls the onCreate method in AppCompatActivity?
        super.onCreate(savedInstanceState);
            System.out.println("onCreate triggered");
            if (savedInstanceState != null){
                System.out.println("savedInstanceState is NOT null!");
            }
            Intent intent = getIntent();
            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
            String text = intent.getStringExtra(EditMessageActivity.EDITMESSAGE);
            System.out.println("message: " + message);
            System.out.println("text: " + text);
            setContentView(R.layout.fragment_display_message);

            TextView textView = (TextView) findViewById(R.id.display_text);
            textView.setTextSize(40);
        if (message != null) {
                textView.setText(message);
            } else if (text != null){
                textView.setText(text);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        // Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button,
        // so long as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void editText(View view){
        Intent intent = new Intent(this, EditMessageActivity.class);
        final int result = 3;
        TextView textView = (TextView) findViewById(R.id.display_text);
        String currentText = textView.getText().toString();
        intent.putExtra("currentText", currentText);
        startActivityForResult(intent, result);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("resultCode: " + resultCode);
        if (resultCode == 3) {
            String message = data.getStringExtra("Edited");
            TextView textView = (TextView) findViewById(R.id.display_text);
            textView.setText(message);
        }
    }
   @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        // Store UI to the savedInstanceState
        // This bundle will be passed to onCreate on next call.
       TextView textView = (TextView) findViewById(R.id.display_text);
        String text = textView.getText().toString();

       savedInstanceState.putString("savedText", text);
       System.out.println("onSaveInstanceState triggered");
       super.onSaveInstanceState(savedInstanceState);
    }

   /* protected void onPause() {
        super.onPause();
        System.out.println("onPause triggered");
        // Store values between instances here
        SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        TextView textView = (TextView) findViewById(R.id.display_text);
        String savedText = textView.getText().toString();
        editor.putString("savedText", savedText);
        editor.commit();
    }*/
}

这里是EditMessageActivity:

package com.example.erikbylow.myclayapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


/**
* Created by erikbylow on 5/14/15.
*/
public class EditMessageActivity extends AppCompatActivity {
   final static  String EDITMESSAGE =   "com.example.erikbylow.myclayapplication.EDITMESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_display_message);
    EditText editText = (EditText) findViewById(R.id.edit_text);
    editText.setText(getIntent().getStringExtra("currentText"));
 }
@Override
public boolean onOptionsItemSelected(MenuItem item){
    // Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button,
    // so long as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void submitEdit(View view){
    EditText editText = (EditText) findViewById(R.id.edit_text);
    String edit = editText.getText().toString();
    Intent intent = new Intent();
    intent.putExtra("Edited",edit);
    setResult(3,intent);
    finish();
}

@Override
public void onBackPressed(){
    Intent intent = new Intent(EditMessageActivity.this, DisplayMessageActivity.class);
    // Add your extras here ?
    EditText editText = (EditText) findViewById(R.id.edit_text);
    String text = editText.getText().toString();
    System.out.println("Text in onBackPressed: " + text);
    intent.putExtra(EDITMESSAGE, text);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

}

2 个答案:

答案 0 :(得分:0)

你可以在这里做一点小动作。只需覆盖EditMessageActivity中的onBackPressed(),然后使用新的附加内容(编辑后的文本)启动新的DisplayMessageActivity。它会像按下后退键一样。

@Override
public void onBackPressed() {
            Intent intent = new Intent(EditMessageActivity.this, DisplayMessageActivity.class); 
            //add your extras here
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
            startActivity( intent );
}

编辑您的submitEdit()方法

public void submitEdit(View view){
  EditText editText = (EditText) findViewById(R.id.edit_text);
  String edit = editText.getText().toString();
  Intent intent = new Intent(EditMessageActivity.this, DisplayMessageActivity.class);
  intent.putExtra("Edited",edit);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
  startActivity( intent );
}

如果你想要的话,这是我试过的代码

DisplayMessage.java

public class DisplayMessage extends ActionBarActivity {

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

    Intent intent = getIntent();
    String message = intent.getStringExtra("testing");

    Button edit=(Button)findViewById(R.id.edit_button); //this button is for go next activity 
    EditText edit_message=(EditText)findViewById(R.id.edit_message);
    if(message!=null)
        edit_message.setText(message);

    edit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(DisplayMessage.this, EditActivity.class);
            final int result = 3;
            EditText edit_message=(EditText)findViewById(R.id.edit_message);
            String currentText = edit_message.getText().toString();
            intent.putExtra("currentText", currentText);
            startActivityForResult(intent, result);

        }
    });


}

}

EditActivity.java

public class EditActivity extends ActionBarActivity {

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

    Intent intent = getIntent();
    String message = intent.getStringExtra("currentText");
    Button edit=(Button)findViewById(R.id.edit_button);
    EditText edit_message=(EditText)findViewById(R.id.edit_message);
    if(message!=null)
        edit_message.setText(message);

    edit.setOnClickListener(new OnClickListener() {         //to submit edits

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(EditActivity.this, DisplayMessage.class);
            EditText edit_message=(EditText)findViewById(R.id.edit_message);
            String text = edit_message.getText().toString();
            intent.putExtra("testing", text);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }


    });

}

}

答案 1 :(得分:0)

您应该覆盖onRestoreInstanceState()方法。当您的DisplayActivity恢复时(在您从编辑活动中按显示后),此方法将获得回调

参考下面的图片,这是自我解释的: enter image description here

代码:

@Override

protected void onRestoreInstanceState(Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        editText.setText(savedInstanceState.getString("savedText"));
    }
}