首页 > 解决方案 > Android studio:我正在尝试更改共享首选项并希望将数据存储在 SQLite 数据库中

问题描述

我是Java编程新手。

现在,我面临的问题是我想更改共享首选项并想使用 SQLite 数据库来存储这些数据。我已经创建了存储这些数据的表,我正在尝试将这些数据保存在 SQLite 中。

我能怎么做?任何人都可以帮助我吗????

我的数据库表

这是我使用共享首选项的代码:

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();
        }
    }

这是将数据保存在 SQLite 数据库中的代码(但出现错误):</p>

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";

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

        uniqueID = db.getReg("8");
        uniqueID = prefs.getString("UUID", null);
        if (uniqueID == null)
        {
            uniqueID = UUID.randomUUID().toString();
            //uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
            db.updateREG("8", uniqueID);
        }

        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();
        }
    }

我的数据库助手

 //GET value by id 
    public Cursor getReg(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
        return data;
    }

//update value
public boolean updateREG(String ID, String Value) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("Value", Value);
        String[] args = new String[]{ID};
        database.update("Reg", cv, "ID = ?", args);
        return true;
    }

标签: javaandroid-studioandroid-sqlite

解决方案


以下是一个工作示例,其行为与共享首选项非常相似,但将首选项存储在 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
  • NOT STORED 演示了未存储 Key/Name 时返回的默认值。
  • 如您所见,UUID 已在第二行中更新(如果重新运行这两行将显示更新后的值)

推荐阅读