简体   繁体   English

重新启动应用程序时,如何在 EditText 中保留字符串/整数值?

[英]How can I persist the string/int value in EditText when i relaunch my application?

In my Android activity, I have one EditText , a ' + ' button, a ' - ' button, ' Save ' button and ' Load ' button.在我的 Android 活动中,我有一个EditText 、一个“ + ”按钮、一个“ - ”按钮、“ Save ”按钮和“ Load ”按钮。 When I press ' + ', the value in EditText increases by 1, similarly on pressing ' - ' value decreases by 1. I used SharedPreferences to save the data when I click on ' Save '.当我按下“ + ”时, EditText 中的值增加 1,类似地按下“ - ”时值减少 1。当我点击“保存”时,我使用SharedPreferences来保存数据。 When I click ' Load ', I want to reload this data onto the EditText field.当我单击“加载”时,我想将此数据重新加载到EditText字段中。

Now the problem is, when I completely exit the application (even from recently used apps), and click ' Load ' on relaunching it, the saved number doesn't appear.现在的问题是,当我完全退出应用程序(即使是从最近使用的应用程序中),并在重新启动时单击“加载”,保存的号码不会出现。 I included the onClick() action for the 'Load' method in onRestart() method.我在onRestart()方法中包含了“Load”方法的onClick()操作。 It still doesn't work.它仍然不起作用。 What am I missing here?我在这里缺少什么? I even tried out all other suggestions for the similar questions asked previously here.对于之前在这里提出的类似问题,我什至尝试了所有其他建议。 Also, is it really onRestart() or onRestoreInstanceState() ?另外,它真的是onRestart()还是onRestoreInstanceState()

public class MainActivity extends Activity {
    Button btn1;
    Button btn2;
    Button btn3;
    Button btn4;
    EditText scoreText;
    int counter = 0;
    TextView textTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button)findViewById(R.id.add);
        btn2 = (Button)findViewById(R.id.subtract);
        btn3 = (Button)findViewById(R.id.save);
        btn4 = (Button)findViewById(R.id.load);
        scoreText = (EditText)findViewById(R.id.total);
        textTitle = (TextView)findViewById(R.id.title);

        btn1.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View v) {
                counter++;
                scoreText.setText(Integer.toString(counter));
                scoreText.setBackgroundColor(Color.GREEN);
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View v) {
                counter=counter-1;
                scoreText.setText(Integer.toString(counter));
                scoreText.setBackgroundColor(Color.RED);
            }
        });
        btn3.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View v) {
                //store data using sharedprefernces
                SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                //Edit method allow to write the data in sharedpreferences
                editor.putString("count",scoreText.getText().toString());
                //For commit changes commit() method is used
                editor.commit();
                Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
            }
        });
        btn4.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
                String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
               // scoreText.setText(strcount);
                scoreText.setBackgroundColor(Color.YELLOW);
            }
        });

    }

    @Override
    protected void onRestart(Bundle savedInstanceState){
        super.onRestart(savedInstanceState);
        btn4.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View v) {
                SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
                String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
                if (strcount.equals(""))
                {
                    Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    scoreText.setText(strcount);


                }
                scoreText.setBackgroundColor(Color.YELLOW);
            }
        });

    }

You using using count as key to save the value您使用使用count作为键来保存值

editor.putString("count",scoreText.getText().toString());

but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use但是使用name作为键来检索值,因此您需要在获取先前存储的数据时使用count键,因此请使用

sharedPreferences.getString("count",scoreText.getText().toString());

instead of代替

sharedPreferences.getString("name",scoreText.getText().toString());

You are using different keys to save and retrieve the data from SharedPrefernces.您正在使用不同的键来保存和检索 SharedPrefernces 中的数据。

editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());

You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.您应该在这两种情况下使用相同的键,否则它会返回默认值,即 TextView 中的文本,并且在应用程序开始时为空,您只需要更改键即可为您解决问题.

Just change the below line like it is mentioned只需像提到的那样更改下面的行

String strcount=sharedPreferences.getString("count",scoreText.getText().toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何从EditText获取值并将其转换为int类型 - How can i get value from EditText and convert it to int type Android:为什么在旋转Android设备时我的String值不会持续存在? 但倒计时部分确实如此 - Android: Why does my String value not persist when I rotate Android device? However the countdown portion does 我该如何比较EditText值和textview Int - How do i compare EditText Value to textview Int 如何在片段中使用我的edittext? - How I can use my edittext in a fragment? 如何更改 int 变量的值? - How can I change the value of my int variable? 如何将字符串转换为const类的int值? - How can I convert string to const class int value? 在将字符串搜索到我的EditText之后,如何在我的Recycler View中开始搜索匹配项 - How can I start searching for matches in my Recycler View after intenting string for search to my EditText 当我更改int值时,字符串中的int不变 - Int in string does not change when i change the int value 我有一个连续包含超过1个值的列表视图,当我在Edittext中键入内容时,如何用名称值过滤列表? - I have a listview which contains more that 1 value in a row, how can i filter the list with a name value when i type in Edittext? 如何将2d字符串数组保存到sql数据库中? - How can I persist 2d string arrays into a sql database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM