如何保留第一个活动的值,并在从第二个活动切换回第一个活动时看到它们

时间:2017-12-13 05:35:34

标签: java android sharedpreferences onsaveinstancestate

我在第一项活动的文本框中输入了一些文字。

然后,按下" SAVE"按钮,我被转移到第二个活动。

现在,按下" BACK"按钮,我退回到第一个活动,我无法看到之前输入的值/文本。

我也尝试过使用共享首选项。

Here是我的代码

MainActivity.java

package com.example.madhur.intentclear;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

        final EditText tv1 = findViewById(R.id.editText);
        final EditText tv2 = findViewById(R.id.editText2);
        final EditText tv3 = findViewById(R.id.editText3);
        final Button bt1 = findViewById(R.id.button);
        bt1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                SharedPreferences sharedPreferences1=getSharedPreferences("value1",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences1.edit();
                editor.putString("tv1",tv1.getText().toString());

                SharedPreferences sharedPreferences2=getSharedPreferences("value2",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor2=sharedPreferences2.edit();
                editor2.putString("tv2",tv2.getText().toString());

                SharedPreferences sharedPreferences3=getSharedPreferences("value3",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor3=sharedPreferences3.edit();
                editor3.putString("tv3",tv3.getText().toString());

                editor.apply();
                editor2.apply();
                editor3.apply();
               tv1.setText(String.valueOf(sharedPreferences1.getString("tv1",null)));
               tv2.setText(String.valueOf(sharedPreferences2.getString("tv2",null)));
               tv3.setText(String.valueOf(sharedPreferences3.getString("tv3",null)));

                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                intent.putExtra("tv1",tv1.getText().toString());
                intent.putExtra("tv2",tv2.getText().toString());
                intent.putExtra("tv3",tv3.getText().toString());
                startActivity(intent);
            }
        });
    }
}

Main2Activity.java

package com.example.madhur.intentclear;

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

import java.io.FileOutputStream;
import java.io.IOException;

public class Main2Activity extends AppCompatActivity {

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


        final TextView tv1=findViewById(R.id.textView);
        final TextView tv2=findViewById(R.id.textView2);
        final TextView tv3=findViewById(R.id.textView3);

        Button button=findViewById(R.id.button);
        Button button1=findViewById(R.id.button1);
        Button button2=findViewById(R.id.button2);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle intent=getIntent().getExtras();
                tv1.setText(intent.getString("tv1"));
                tv2.setText(intent.getString("tv2"));
                tv3.setText(intent.getString("tv3"));
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String clear="";

                tv1.setText(clear);
                tv2.setText(clear);
                tv3.setText(clear);
               m1();

            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
Intent intent1=new Intent(Main2Activity.this,MainActivity.class);
startActivity(intent1);
            }
        });
    }
    public void m1()
    {String clear="";
        try {

            FileOutputStream fileOutputStream;
            FileOutputStream fileOutputStream2;
            FileOutputStream fileOutputStream3;
            fileOutputStream = openFileOutput("et1.txt", Context.MODE_PRIVATE);
            fileOutputStream.write(clear.getBytes());

            fileOutputStream2 = openFileOutput("et2.txt", Context.MODE_PRIVATE);
            fileOutputStream2.write(clear.getBytes());

            fileOutputStream3 = openFileOutput("et3.txt", Context.MODE_PRIVATE);
            fileOutputStream3.write(clear.getBytes());

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

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.madhur.intentclear.MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.13" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.87" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.06" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.18" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.29" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.43" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.58" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.73" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.82" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.95" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.24" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.77" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:ems="10"
        android:inputType="textPersonName"
       android:hint="Enter name"
        app:layout_constraintBottom_toTopOf="@+id/guideline4"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="@+id/guideline3" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="0dp"
        android:hint="Enter phone number"
        android:layout_height="0dp"
        android:ems="10"
        android:inputType="textPersonName"

        app:layout_constraintBottom_toTopOf="@+id/guideline6"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="@+id/guideline5" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="0dp"
        android:hint="Enter Email Adress"
        android:layout_height="0dp"
        android:ems="10"
        android:inputType="textPersonName"

        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="@+id/guideline7" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
android:text="SAVE"
        app:layout_constraintBottom_toTopOf="@+id/guideline10"
        app:layout_constraintEnd_toStartOf="@+id/guideline12"
        app:layout_constraintStart_toStartOf="@+id/guideline11"
        app:layout_constraintTop_toTopOf="@+id/guideline9" />
</android.support.constraint.ConstraintLayout>

activity_Main2.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.madhur.intentclear.Main2Activity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"

        app:layout_constraintBottom_toTopOf="@+id/guideline16"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toTopOf="@+id/guideline15" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"

        app:layout_constraintBottom_toTopOf="@+id/guideline19"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toTopOf="@+id/guideline20" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="0dp"

        app:layout_constraintBottom_toTopOf="@+id/guideline17"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toTopOf="@+id/guideline18" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline13"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="249dp" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline14"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.33854166" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline15"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.031311154" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline16"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.13" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline17"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.38" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline18"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.29" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline19"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.26" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline20"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.16" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:text="SHOW TEXT"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toTopOf="@+id/guideline17" />

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="CLEAR TEXT"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="BACK"
        app:layout_constraintEnd_toStartOf="@+id/guideline13"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guideline14"
        app:layout_constraintTop_toBottomOf="@+id/button1" />
</android.support.constraint.ConstraintLayout>

2 个答案:

答案 0 :(得分:2)

在onCreate

中使用 savedInstanceState 捆绑包

savedInstanceState 是对Bundle对象的引用,该对象传递给每个Android Activity的onCreate方法。在特殊情况下,活动可以使用此捆绑包中存储的数据将自身恢复到以前的状态。如果没有可用的实例数据,则savedInstanceState将为null。

  

例如,savedInstanceState在第一次时始终为null   一个Activity已启动,但如果是Activity,则可能为非null   在轮换期间被摧毁。

我何时将内容保存到Bundle?

所有活动都有一个可以覆盖的onSaveInstanceState方法。调用此方法时,任何与状态相关的数据都应放入outState Bundle中。当一个Activity被背景化时(在onPause()或onStop()之后,根据不同的因素调用此方法。)

应该保存什么?

savedInstanceState Bundle应该只保存与当前Activity状态直接相关的信息。例如:

一个典型的例子是用户提交的数据 - 如果用户将其用户名写入文本框,他们会希望在恢复活动时仍然存在用户名。 此数据应保存在onSaveInstanceState中,然后在重新创建活动时恢复

在你的onCreate函数中,这个Bundle会被交还给程序。检查应用程序是否正在重新加载或首次启动的最佳方法是:

if (savedInstanceState != null) {
// Then the application is being reloaded
}

要恢复数据,请使用get *函数,就像put *函数一样。数据存储为名称 - 值对。这就像一个hashmap。你提供了一个键和值,然后当你想要返回值时,你给出键,函数得到值。这是一个简短的例子。

@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putString("message", "This is my message to be reloaded");
   super.onSaveInstanceState(outState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        String message = savedInstanceState.getString("message");
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

//将局部变量提升为字段

public class Main2Activity extends AppCompatActivity {

    private TextView tv1;
    private TextView tv2;
    private TextView tv3;

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

        tv1 = (TextView) findViewById(R.id.textView);
        tv2 = (TextView) findViewById(R.id.textView2);
        tv3 = (TextView) findViewById(R.id.textView3);

        ...
    }
}

答案 1 :(得分:0)

使用共享首选项暂时/永久存储值

<强> EDITED 对不起,我看到代码后没有看到代码。

您再次在onlCick内设置值。您已将值设置在onClick

之外

解决方案

使用SharedPreferences创建一个全局MODE_PRIVATE,设置值onClick并读取onCreate上的值(onClick之外)。