【问题标题】:Saving EditText and retrieve it automatically保存 EditText 并自动检索它
【发布时间】:2018-06-23 13:44:05
【问题描述】:

您好,我正在尝试将 EditText 小部件值保存在手机/平板电脑的内部存储器中,以便应用程序在关闭或活动停止时自动检索它们。所有这些都可以使用保存按钮来工作。(小部件的值由用户输入)。

【问题讨论】:

    标签: java android android-studio android-edittext save


    【解决方案1】:

    您应该使用共享首选项,共享首选项用于将数据存储在本地应用程序中,您可以在需要时访问它。 使用此链接https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

    使用它。 单击按钮后,您可以获得值。它帮助我

    【讨论】:

    • 如果应用被杀了怎么办?
    • 谢谢它,几分钟后我意识到它是多么容易。很好的链接
    【解决方案2】:

    如果您想保存单个值,例如姓名、地址、电话号码等,请使用SharedPreferences,或者想多次保存相同的值,请使用Sqlite

    参考:SqliteSharedPreferences

    【讨论】:

      【解决方案3】:
      public class MainActivity extends AppCompatActivity {
          private Button button;
          private EditText editText;
          private final String KEY = "edittextValue";
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              editText = (EditText) findViewById(R.id.edittext);
              editText.setText(getValue());
      
              button = (Button) findViewById(R.id.button1);
              button.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      saveFromEditText(editText.getText().toString());
                  }
              });
      
          }
      
          private String getValue() {
              SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
              String savedValue = sharedPref.getString(KEY, ""); //the 2 argument return default value
      
              return savedValue;
          }
      
          private void saveFromEditText(String text) {
              SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
              SharedPreferences.Editor editor = sharedPref.edit();
              editor.putString(KEY, text);
              editor.apply();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2014-03-27
        • 1970-01-01
        • 1970-01-01
        • 2021-04-24
        • 2012-01-18
        • 2012-04-27
        • 1970-01-01
        • 2011-10-15
        相关资源
        最近更新 更多