【问题标题】:Store Integer in SQL Database & Retrieve it in Fragment在 SQL 数据库中存储整数并在片段中检索它
【发布时间】:2015-01-08 21:13:40
【问题描述】:

我正在设置一个 Android 应用程序,并且刚刚浏览了 Android 开发人员文档来设置一个 SQL 数据库 http://developer.android.com/training/basics/data-storage/databases.html#WriteDbRow

我有一个 MainActivity,它设置了导航抽屉:http://pastebin.com/9nyejZdV,以及该 Activity 中的一个开关,用于在导航抽屉中单击项目时替换片段。

切换的两个片段是:

StartingFragment,首次打开应用时显示:http://pastebin.com/740LepNV


TeaCounterFragment,在我的导航抽屉中点击第二个项目时显示:http://pastebin.com/edfEe1Gd


在 StartingFragment 中,在 onClick 方法中,每当按下名为“Oolong”的按钮时,它都会更新我的 TeaCounterFragment 中的 TextView,显示按下“Oolong”按钮的次数(通过使用 String.valueOf(an_integer ) 和一个 Bundle)。

问题是每当应用程序完全关闭时,TextView 会重置为默认值,不会显示计数。所以,我想我会使用 SQL 数据库来存储整数,这样当应用程序完全关闭时,整数仍然会被存储。然后,当应用程序重新打开时,我可以点击我的 NavDrawer 并转到我的 TeaCounterFragment,数字仍然存在。

我怎样才能做到这一点?

数据库活动:

public final class Database {

    // To prevent someone from accidentally instantiating the database class,
    // give it an empty constructor.
    public Database() {
    }

    /* Inner class that defines the table contents */
    public static abstract class DBEntry implements BaseColumns {

        public static final String TABLE_NAME = "Number of Cups of Tea";
        public static final String COLUMN_NAME_ENTRY_ID = "entryid";
        public static final String COLUMN_NAME_TITLE = "Tea Counter Table";
        public static final String COLUMN_NAME_SUBTITLE_OOLONG = "Oolong";
    }

    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + DBEntry.TABLE_NAME + " (" +
                    DBEntry._ID + " INTEGER PRIMARY KEY," +
                    DBEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
                    DBEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                    DBEntry.COLUMN_NAME_SUBTITLE_OOLONG + TEXT_TYPE + COMMA_SEP +
                    " )";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS" + DBEntry.TABLE_NAME;

    public class DatabaseHelper extends SQLiteOpenHelper {

        public static final String DATABASE_NAME = "TeaCounter.db";
        public static final int DATABASE_VERSION = 1;

        Context context;
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(SQL_CREATE_ENTRIES); //creates Database
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // This database is only a cache for online data, so its upgrade policy is
            // to simply to discard the data and start over
            db.execSQL(SQL_DELETE_ENTRIES);
            onCreate(db);
        }

        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            onUpgrade(db, oldVersion, newVersion);
        }

        public void storeCounts() {
            DatabaseHelper mDbHelper = new DatabaseHelper(context);
            SQLiteDatabase db = mDbHelper.getWritableDatabase();

            // Create a new map of values, where column names are the keys
            ContentValues values = new ContentValues();
            values.put(DBEntry.COLUMN_NAME_ENTRY_ID, 1);
            values.put(DBEntry.COLUMN_NAME_TITLE, "Tea Counter Table");
            values.put(DBEntry.COLUMN_NAME_SUBTITLE_OOLONG, "Oolong Tea");
        }
    }
}

我想使用 SQL 数据库,因为我希望能够为多个按钮执行此操作。 不过,我也愿意接受任何其他方式的建议。

【问题讨论】:

标签: java android android-fragments sqliteopenhelper


【解决方案1】:

如果你只是想存储一个整数,也许你可以看看 DefaultSharedPreferences 类。见此链接:http://developer.android.com/reference/android/content/SharedPreferences.html

如果您从片段中执行此操作:

SharedPreferences pref = getActivity().getSharedPreferences("keyname", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("counter", integer);
editor.commit();

然后当你想检索它时,假设你已经有了 SharedPreferences 实例

Integer counter = pref.getInt("counter", 0);

希望对你有所帮助。

【讨论】:

  • 在第一个代码块中,我将把该代码放在哪个 Fragment 中? StartingFragment 还是 TeaCounterFragment?然后我假设我应该在 TeaCounterFragment 中检索它?
  • 是的。起始片段中的编辑代码和 TeaCounterFragment 中的检索代码
  • @Simar 好的。不过现在还有另一个问题。我收到此错误:java.lang.NumberFormatException: Invalid int: "null" 来自写入 pref.getInt("counter", null)。实际上,它甚至不允许我写“null”。我必须用 Integer.parseInt() 包装它,当我这样做时,我得到了错误
  • 第二个参数是默认值,以防共享首选项中不存在该项目。因为它是一个整数,所以你应该写 0 或 -1 或任何你想要的。
  • @Simar 知道了。虽然有一个错误。如果我单击“乌龙”按钮 3 次,它将显示计数器的数字 3。如果应用程序完全关闭,然后重新打开,它仍然存在。好的。这就是应该发生的事情。问题是,如果我再次单击该按钮,它不会添加到已经存在的号码。相反,它将从 1 开始。
【解决方案2】:

由于您只想存储一个整数,因此您应该使用共享首选项而不是数据库。

【讨论】:

  • 即使我想为多个按钮点击计数存储整数?因为每个按钮都会有不同的整数,具体取决于每个按钮被点击的次数。
  • 是的。共享首选项只是名称值对的集合。 Button1 5,Button2 8 以此类推。
  • 好的。在我废弃数据库之前......如果我想稍后在电子表格/表格中的另一个片段上显示这些整数怎么办?并且拆分按钮计数为每天、每周、每月、每年的点击次数?如果我使用 SharedPreferences,我还能这样做吗?或者数据库会更有用吗?
  • 好的。因此,SharedPreferences 是执行此操作的最佳方式。然后再问一个问题:我什么时候应该真正使用数据库?比如......在什么情况下使用数据库而不是 sharedpreferences 更合适?
  • 当你有一个大数据集时。或同一事物的不同属性。在这种情况下,对于一个按钮,您只知道它被单击的次数。但如果让我们说一辆车,你有型号、颜色等......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2017-08-23
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多