当前位置: 首页 > 知识库问答 >
问题:

Android Studio:我正在尝试更改共享首选项,并希望将数据存储在SQLite数据库中

安建木
2023-03-14

我是Java编程的新手。

现在,我面临的问题是,我想要更改共享的首选项,并且想要使用SQLite数据库来存储这些数据。我已经创建了一个表来存储这些数据,名称为Register table,但我不知道如何更改。

我该怎么办?有人能帮我吗????

这是我的代码:

public class Login extends AppCompatActivity {
    InputStream inputStream;
    ACDatabase db;
    SharedPreferences prefs;

    ActivityLoginBinding binding;
    AC_Class.Connection connection;
    AC_Class.Register reg;
    String versionNo;
    String url;
    String urlStr;
    String id;
    String pwd;
    private static String uniqueID = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        getSupportActionBar().hide();

        // Placeholder
        versionNo = "3.1.6";

        reg = new AC_Class.Register();

        connection = new AC_Class.Connection();
        binding.setConSettings(connection);
        db = new ACDatabase(this);

        
        // Check preferences/create if nonexistent
        prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);

        uniqueID = prefs.getString("UUID", null);
        if (uniqueID == null)
        {
            uniqueID = UUID.randomUUID().toString();
            //uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
            prefs.edit().putString("UUID", uniqueID).commit();
        }

        binding.lblUUID.setText(uniqueID);
        binding.lblVersion.setText(versionNo);

        if (prefs.getString("ID", id) != null) {
            binding.rmbCheckBox.setChecked(true);
            url = prefs.getString("URL", url);
            binding.txtURL.setText(prefs.getString("URLstr", urlStr));
            binding.txtID.setText(prefs.getString("ID", id));
            binding.txtpw.setText(prefs.getString("pwd", pwd));
        }
        if (prefs.getString("Default_curr", null) == null) {
            prefs.edit().putString("Default_curr", "RM").apply();
        }
        if (prefs.getString("Default_loc", null) == null) {
            Cursor tempCursor = db.getLocation();
            if (tempCursor.moveToNext()) {
                prefs.edit().putString("Default_loc", tempCursor
                        .getString(tempCursor.getColumnIndex("Location"))).apply();
            }
        }
        // Version number
        if (prefs.getString("Version ", null) == null) {
            prefs.edit().putString("Version", versionNo).apply();
        }
        // Tax Inclusive
        if (!prefs.getBoolean("taxInclusive", false)) {
            prefs.edit().putBoolean("taxInclusive", false).apply();
        }
        if (Build.MODEL.equals("HC720"))
        {
            Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    //On return of intent
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 7) {
            url = data.getStringExtra("URLKey");
            urlStr = data.getStringExtra("URLStr");
            Log.i("custDebug", url + ", " + urlStr);
            binding.txtURL.setText(urlStr);
            if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
                new GetModules(Login.this).execute(url);
                new GetLoginList(Login.this).execute(url);
                new SetDevice(Login.this).execute(url);
            }
        }
    }

    //Open connection settings
    public void btnSetClicked(View view) {
        Intent intent = new Intent(Login.this, ConnectionSettings.class);
        startActivityForResult(intent, 7);
    }

    //Reset Database
    public void btnResetDbClicked(final View view) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Reset DB");
        builder.setMessage("Are you sure you want to reset the Database?");
        final EditText input = new EditText(this);

        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (input.getText().toString().equals("presoftmobile")) {
                    db.close();
                    deleteDatabase("AutoCountDatabase");
                } else {
//                    Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
                }
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();

    }

    //Login button
    public void btnLoginBtnClicked(View view) {
        if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
            binding.txtURL.setError("This field can't be blank.");
            //return;
        }
        if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
            binding.txtID.setError("This field can't be blank.");
            //return;
        }
        if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
            binding.txtpw.setError("This field can't be blank.");
            //return;
        }

        //Non-empty fields
        else {
            Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
                    binding.txtpw.getText().toString().toUpperCase());

            if (checkData.getCount() > 0) {
                checkData.moveToNext();

                //Shared Preferences

                prefs.edit().putString("URL", url).apply();
                prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();

                if (binding.rmbCheckBox.isChecked()) {
                    prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
                    prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
                }

                prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
                prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
                prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
                prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
                prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();

                if (url != null) {
                    try {
                        // Check Connection

                        new SetDevice(Login.this).execute(url);

                        // Go to main
                        Intent intent = new Intent(Login.this, Dashboard.class);
                        intent.putExtra("URLKey", url);
                        intent.putExtra("URLStr", binding.txtURL.getText().toString());
                        startActivity(intent);
                        finish();
                    } catch (Exception e) {
                        Log.i("custDebug", e.getMessage());
                        Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
                binding.txtpw.setText(null);
            }

            checkData.close();
        }
    }

共有1个答案

陆浩博
2023-03-14

下面是一个工作示例,它的操作与共享偏好非常相似,但将偏好存储在SQLite数据库中。

该表非常简单,有2列。键(存储值的名称)和值本身。可以是String、boolean、int、long或float。

它包括以下方法;插入(添加)键/值对,更新键/值对,根据键获取值,并返回传递的默认值(使其易于检测是否检索到值)。

DatabaseHelper(SQLiteOpenHelper的子类)拥有大部分代码,它是:-

class DBHelper extends SQLiteOpenHelper {

    private static volatile DBHelper instance = null;
    private SQLiteDatabase db = null;

    public static final String DBNAME = "sharedpreferences.db";
    public static final int DBVERSION = 1;

    public static final String TBLNAME_SP = "_shared_preferences";
    public static final String COLNAME_SP_KEY = "_key";
    public static final String COLNAME_SP_VALUE = "_value";

    private DBHelper(@Nullable Context context) {
        super(context, DBNAME, null, DBVERSION);
        db = this.getWritableDatabase();
    }

    public static DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
                "(" +
                COLNAME_SP_KEY + " PRIMARY KEY," +
                COLNAME_SP_VALUE + " TEXT" +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    private long insertPrefsRow(ContentValues cv, String key) {
        cv.put(COLNAME_SP_KEY,key);
        return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
    }

    public long insertPrefsValue (String key, int value) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,value);
        return insertPrefsRow(cv,key);
    }

    public long insertPrefsValue (String key, String value) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,value);
        return insertPrefsRow(cv,key);
    }

    public long insertPrefsValue (String key, long value) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,value);
        return insertPrefsRow(cv,key);
    }
    public long insertPrefsValue (String key, boolean value) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,value);
        return insertPrefsRow(cv,key);
    }

    public long insertPrefsValue (String key, float value) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,value);
        return insertPrefsRow(cv,key);
    }

    private long updatePrefs(String key, ContentValues cv) {
        return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
    }

    public long updatePrefsStringValue(String key, String newValue) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,newValue);
        return updatePrefs(key,cv);
    }

    public long updatePrefsStringValue(String key, boolean newValue) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,newValue);
        return updatePrefs(key,cv);
    }

    public long updatePrefsStringValue(String key, int newValue) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,newValue);
        return updatePrefs(key,cv);
    }

    public long updatePrefsStringValue(String key, long newValue) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,newValue);
        return updatePrefs(key,cv);
    }

    public long updatePrefsStringValue(String key, Float newValue) {
        ContentValues cv = new ContentValues();
        cv.put(COLNAME_SP_VALUE,newValue);
        return updatePrefs(key,cv);
    }

    private Cursor getPrefsValue(String key) {
        return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
    }

    public String getPrefsStringValue(String key, String default_value) {
        String rv = default_value;
        Cursor csr;
        if ((csr = getPrefsValue(key)).moveToFirst()) {
            rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
            csr.close();
        }
        return rv;
    }
    public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
        Boolean rv = default_value;
        Cursor csr;
        if ((csr = getPrefsValue(key)).moveToFirst()) {
            rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
            csr.close();
        }
        return rv;
    }
    public int getPrefsIntValue(String key, int default_value) {
        int rv = default_value;
        Cursor csr;
        if ((csr = getPrefsValue(key)).moveToFirst()) {
            rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
            csr.close();
        }
        return rv;
    }

    public long getPrefsLongValue(String key, long default_value) {
        long rv = default_value;
        Cursor csr;
        if ((csr = getPrefsValue(key)).moveToFirst()) {
            rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
            csr.close();
        }
        return rv;
    }

    public Float getPrefsFLoatValue(String key, Float default_value) {
        Float rv = default_value;
        Cursor csr;
        if ((csr = getPrefsValue(key)).moveToFirst()) {
            rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
            csr.close();
        }
        return rv;
    }

}

下面是演示用法的活动:-

public class MainActivity extends AppCompatActivity {

    DBHelper db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = DBHelper.getInstance(this);
        db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
        db.insertPrefsValue("taxInclusive",false);
        db.insertPrefsValue("myprefs_int",100);
        db.insertPrefsValue("myprefs_long",100L);
        db.insertPrefsValue("myprefs_float",10.567F);

        Log.d("PREFSINFO",
                "Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
                        " Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
                        " Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
                        " Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
                        " Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
                        " NOT STORED is " + db.getPrefsFLoatValue("NOT A SET  KEY",-3333.3333F)
        );

        db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");

        Log.d("PREFSINFO",
                "Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
                        " Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
                        " Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
                        " Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
                        " Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
                        " NOT STORED is " + db.getPrefsFLoatValue("NOT A SET  KEY",-3333.3333F)
        );
    }
}

运行时(或重新运行,但重新运行时检索的是更新的UUID,而不是原始的UUID),日志包含:-

D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
    null
 类似资料:
  • 我正在创建一个番茄工作计时器应用程序。它有2项活动: 主要活动是设置时间 我已经创建了一个对象,它保存了设置的时间,我希望这些时间显示在Recents活动中的按钮中。但是,似乎没有保存数据,而是显示了包名称。

  • 我是编程新手。我正在制作一个在线有奖债券钱包系统,我使用选择选项选择债券,然后在数据库中搜索。 我得到这个错误: 注意:未定义的变量:第37行C:\xampp\htdocs\PBWS\searchi.php中的sql 警告:mysqli_query():第37行C:\xampp\htdocs\PBWS\searchi.php中的空查询 警告:mysqli_fetch_array()希望参数1是my

  • 我正在向SharedPreference添加一个集合。这是来自另一个类的静态集,该类处理一些数据并将其存储在该集中。 然后我转到另一个活动(订单活动),在那里我显示了这组信息。第一次访问共享偏好时,我能够获得正确的详细信息。例如name1、name2、name3。 然后,我离开此活动,返回到另一个活动,添加另一个名称,然后再次返回到此 Order 活动。我希望这次得到名称1,名称2,名称3,名称4

  • 日志: 2021-05-09 14:04:19.356错误22211---[nio-8080-exec-2]O.A.C.C.C.[.[.[/].[dispatcherServlet]:servlet.Service()对于路径[]上下文中的servlet[dispatcherServlet]抛出异常[请求处理失败;嵌套异常为java.lang.NullPointerException:无法调用“c

  • 我想在我的共享首选项中保存一些数据,但在保存时,例外情况如下。在第SharedReferences行。编辑器存储=默认数据。编辑(); 05-29 20:20:53.234:E/AndroidRuntime(27650):致命异常:main 05-29 20:20:53.234:E/AndroidRuntime(27650):java。lang.NullPointerException 05-29

  • 我创建了一个TextView,它以多行显示值 ,我希望将该值保留在SQLite数据库中。这是我使用的代码: 问题是当我保存值时,整个值被插入到一个单元格中。我希望每行的值分开,然后插入到每行的单个单元格中,尽管我使用扫描器方法插入数据,但它不起作用。那有什么办法吗?