【问题标题】:SharedPreferences with a Save Button带有保存按钮的 SharedPreferences
【发布时间】:2019-12-02 16:47:43
【问题描述】:

我是 Android/Java 开发的新手,请放轻松。

该应用程序比较简单,它只是连接到一个 MSQL 数据库 对于每个用户,连接设置都会有所不同,因此我为设置创建了一个新 Activity。 我想我正确地存储了 Activity_Settings.xml 中的值并将它们存储到 SharedPreferences 中。 但我不明白如何创建一个列表器来提交更改。

最终目标是进入 Settings 活动,将显示由 SharedPreferences 中的值填充的 EditText。保存和退出会将它们写回 SharedPreferences。

这是我的活动,如果有人能指出我正确的方向,我已经检查了https://developer.android.com/training/data-storage/shared-preferences,这让我更加困惑

设置.Java

public class Settings extends AppCompatActivity {

    // Declaring layout button, edit texts
    EditText ServerName,ServerPort,DatabaseName,ServerPath;
    // End Declaring layout button, edit texts

    @Override
    protected void onCreate(Bundle savedInstanceState)     //Creating Instance for storing data
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);    // Fetch from Activity_Settings

        // Getting values from any button or text fields
        ServerName = (EditText) findViewById(R.id.ServerName);
        ServerPort = (EditText) findViewById(R.id.ServerPort);
        DatabaseName = (EditText) findViewById(R.id.DBName);
        ServerPath = (EditText) findViewById(R.id.ServerPath);
        // End Getting values from any button or text fields


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
    //    editor.putString("ServerName","192.168.1.75");
    //    editor.putInt("ServerPort",1433);
    //    editor.putString("DBName","OpenXpos");
    //    editor.putString("ServerPath","\\\\/Server01\\/OpenXpos\\/");

        editor.putString("ServerName", String.valueOf(ServerName));
        editor.putString("ServerPort", String.valueOf(ServerPort));
        editor.putString("DBName", String.valueOf(DatabaseName));
        editor.putString("ServerPath", String.valueOf(ServerPath));


        editor.apply();
    }
}

Activity_Settings.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.android.openretail.stocktake.Settings">

    <Button
        android:id="@+id/save"
        android:layout_width="91dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="52dp"
        android:text="Save Exit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginTop="88dp"
        android:text="Server Name"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginTop="20dp"
        android:text="Server Port"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginTop="23dp"
        android:text="Database Name"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="39dp"
        android:layout_marginLeft="39dp"
        android:layout_marginTop="22dp"
        android:text="Server Path"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView4" />

    <EditText
        android:id="@+id/ServerName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:layout_marginEnd="73dp"
        android:layout_marginRight="40dp"
        android:ems="10"
        android:hint="192.168.X.X"
        android:inputType="textPersonName"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/ServerPort"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:layout_marginEnd="73dp"
        android:layout_marginRight="40dp"
        android:ems="10"
        android:hint="Default:1433"
        android:inputType="number"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ServerName" />

    <EditText
        android:id="@+id/DBName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:layout_marginEnd="73dp"
        android:layout_marginRight="40dp"
        android:ems="10"
        android:hint="OpenXpos"
        android:inputType="textPersonName"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ServerPort" />

    <EditText
        android:id="@+id/ServerPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:layout_marginEnd="73dp"
        android:layout_marginRight="40dp"
        android:ems="10"
        android:hint="\\\\Server01\\OpenXpos\\"
        android:inputType="textPersonName"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/DBName" />

</android.support.constraint.ConstraintLayout>

【问题讨论】:

    标签: android


    【解决方案1】:

    这应该如下,首先您使用按钮对象上的setOnClickListener() 分配一个点击侦听器,然后在onCreate() 中加载来自共享首选项的数据。如果用户单击按钮,那么他将在按钮单击侦听器回调中收到通知,数据将保存在该回调中。下面的代码给出了如何做到这一点的大致思路。

     public class Settings extends AppCompatActivity {
    
            // Declaring layout button, edit texts
            EditText serverName,serverPort,databaseName,serverPath;
            // End Declaring layout button, edit texts
            Button saveButton;
    
            @Override
            protected void onCreate(Bundle savedInstanceState)     //Creating Instance for storing data
            {
    
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_settings);    // Fetch from Activity_Settings
    
                // Getting values from any button or text fields
                serverName = (EditText) findViewById(R.id.ServerName);
                serverPort = (EditText) findViewById(R.id.ServerPort);
                databaseName = (EditText) findViewById(R.id.DBName);
                serverPath = (EditText) findViewById(R.id.ServerPath);
    
                //get the shared preference instance
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    
                saveButton = (Button) findViewById(R.id. save);
                // End Getting values from any button or text fields
                saveButton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                //here save the data
                SharedPreferences.Editor editor = preferences.edit();
             editor.putString("server_name",serverName.getText().toString());
             editor.putString("server_port",serverPort.getText().toString());
          editor.putString("database_name",databaseName.getText().toString());
             editor.putString("server_path",serverPath.getText().toString());
             editor.commit();
                   }
                });
    
             //set the default values saved on load
            serverName.setText(preferences.getString("server_name",""));
            serverPort.setText(preferences.getString("server_port",""));
            databaseName.setText(preferences.getString("database_name",""));
            serverPath.setText(preferences.getString("server_path",""));
            }
        }
    

    注意:也不要将 cap 命名分配给实例变量。始终使用 camelCase

    【讨论】:

    • 这现在更有意义了谢谢。对两件事感到好奇。为什么使用camelCase? (我来自 PHP,所以学习曲线陡峭)如果我想要主要活动来获取这些变量,我是否必须做一些特别的事情,比如让它们成为公共/全球?还是我也只是在主要活动中加载 SharedPref ?还是使用 Intent?
    • 我得到了这个工作,虽然我怀疑它不是正确的方式也不是干净的方式,我回电:final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);在主活动中:将每个变量定义为: String serverName = preferences.getString("server_name", "");并将其捆绑在一起,如下所示: db = String.format("jdbc:jtds:sqlserver://%s:%s/%s", serverName, serverPort, databaseName) ;
    【解决方案2】:

    您需要从编辑文本中获取文本值并提交到

    editor.putString("server_name",serverName.getText().toString());
            editor.putString("server_port",serverPort.getText().toString());
            editor.putString("database_name",databaseName.getText().toString());
            editor.putString("server_path",serverPath.getText().toString());
            editor.commit();
    

    【讨论】:

    • 谢谢,这就解释了为什么它没有正确保存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多