简体   繁体   English

在Android中存储数据

[英]Storing data in Android

I am currently working on my first app and I have decided to do it on android. 我目前正在开发我的第一个应用程序,因此决定在android上进行操作。 I have the main activity layout the way I wish and the Time/Date displaying dynamically. 我有自己想要的主要活动布局,并且动态显示了时间/日期。

What I am needing help with is I need the app to save the date and time whenever a button is pressed. 我需要帮助的是每当按下按钮时,我都需要该应用程序来保存日期和时间。 This data will need to be available for 1 week (7 Days) and then it may be overwritten the following week to save space on the device. 此数据将需要在1周(7天)内可用,然后在下周可能会被覆盖以节省设备空间。

Ideally there would be two button presses a day, one to clock in/clock out (App to keep track of my hours at work and calculate pay). 理想情况下,每天要按两次按钮,一次可以按时/按时(应用程序可以跟踪我的工作时间并计算工资)。 What is the best way to go about this? 最好的方法是什么? Can you guys point me in the right direction to storing this data? 你们能指出我正确的方向来存储这些数据吗?

I thought about using Parse but then an online connection would be needed, correct? 我曾考虑过使用Parse,但随后需要在线连接,对吗? Is there anyway to do this locally and then maybe I can implement online storage later? 无论如何,是否可以在本地进行此操作,然后以后再实现在线存储?

If the data you want to save isn't very complex I'd use SharedPreferences. 如果您要保存的数据不是很复杂,我将使用SharedPreferences。 Here's an example: 这是一个例子:

To write data: 写入数据:

SharedPreferences sharedPref = getSharedPreferences("com.example.myapp.PREFERENCE_FILE_KEY",
    Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong("clockIn", clockIn.getTime());
editor.commit();

To read data: 读取数据:

SharedPreferences sharedPref = getSharedPreferences("com.example.myapp.PREFERENCE_FILE_KEY",
    Context.MODE_PRIVATE);
Date clockIn = new Date(getResources().getLong("clockIn"));

Take a look at this for more info: https://developer.android.com/training/basics/data-storage/shared-preferences.html 看看它以获得更多信息: https : //developer.android.com/training/basics/data-storage/shared-preferences.html

The simplest way would be to use SharedPreferences, but a more comprehensive, dynamic storage would be using Sqlite. 最简单的方法是使用SharedPreferences,但更全面的动态存储将使用Sqlite。

Shared Preferences 共享首选项

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

prefs.putLong(FIRST_TIME,nix timestamp).commit();

prefs.putLong(SECOND_TIME, nix timestamp).commit();

And retrieve the same way: 并以相同的方式检索:

long firstTime = prefs.getLong(FIRST_TIME);

long secondTime = prefs.getLong(SECOND_TIME);

最好的方法是存储在本地db(Sqlite)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM