`
sillycat
  • 浏览: 2551028 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Android UI(3)Getting Started - Saving Data

 
阅读更多
Android UI(3)Getting Started - Saving Data

1. Saving Data
Saving Key-Value Sets
SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.

Get a Handle to a SharedPreferences
getSharedPreferences(key_name,mode) - Multiple shared preference files identified by names, and this is called by Context.

In activity:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);

getPreferences() - Only one shared preference file for the activity.

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

If we create preferences file with MODE_WORLD_READABLE or MODE_WORLD_WRITEABLE, then other apps can access the data.

Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore); // getString()
editor.commit();

Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);

long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

2. Saving Files
Deal with the android file system with the File API. It is good the store the image files or anything exchanged over a network.

Choose Internal or External Storage
“internal” and "external" storage are coming from the old days, when most devices offered built-in non-volatile  memory(internal storage), removable storage medium such as a micro SD card(external storage).

The apps are installed onto the internal storage by default, you can specify the android:installLocation in manifest file.

Obtain Permissions for External Storage
<manifest …>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>

Right now, apps have the read permission by default to external storage.

And for internal storage, by default, apps have that permissions.

Save a File on Internal Storage
File handler methods:
getFileDir()

getCacheDir()

File file = new File(context.getFilesDir(), filename);

Examples to write a file>
String filename = "myfile";
String hello = "Hello";
FileOutputStream outputStream;
try{
     outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
     outputStream.write(hello.getBytes());
}catch(Exception e){
     e.printStackTrace();
}finally{
     outputStream.close();
}

Save a File on External Storage
public boolean isExternalStorageWritable(){
     String state = Environment.getExternalStorageState();
     if(Evironment.MEDIA_MOUNTED.equals(state)){
          return true;
     }
     return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable(){
     String state = Environment.getExternalStorageState();
     if(Environment.MEDIA_MOUNTED.equals(state) ||
          Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
          return true;
     }
     return false;
}

Even all the files stored on external storage can be accessed by other apps. But there are still 2 parts in external, private and public.

public File getAlbumStorageDir(String albumName){
     File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES),albumName);
     if(!file.mkdirs()){
          Log.e(LOG_TAG, "Directory not there");
     }
     return file;
}

public File getAlbumStorageDir(Context context, String albumName){
     File file = new File(context.getExternalFilesDir(
               Environment.DIRECTORY_PICTURES), albumName);
     if(!file.mkdirs()){
          Log.e(LOG_TAG, "Directory not there!");
     }
     return file;
}

Query Free Space
getFreeSpace()
getTotalSpace()

Delete a File
myFile.delete()

myContext.deleteFile(fileName);

3. Saving Data in SQL Databases
android.database.sqlite

Define a Schema and Contract
//===========database
public static final String TABLE_NAME = "product";
public static final String COLUMN_NAME_PRODUCT_ID = "product_id";
public static final String COLUMN_NAME_PRODUCT_NAME = "product_name";
public static final String COLUMN_NAME_PRODUCT_PRICE = "product_price";
public static final String COLUMN_NAME_PRODUCT_DESN = "product_desn";
public static final String COLUMN_NAME_PRODUCT_IMAGE_URL = "product_imageurl";

publicstaticfinalStringSQL_CREATE = "CREATE TABLE " + TABLE_NAME + " ( " +
     COLUMN_NAME_PRODUCT_ID + " INTEGER PRIMARY KEY," +
     COLUMN_NAME_PRODUCT_NAME + " TEXT," +
     COLUMN_NAME_PRODUCT_PRICE + " TEXT," +
     COLUMN_NAME_PRODUCT_DESN + " TEXT," +
     COLUMN_NAME_PRODUCT_IMAGE_URL + " TEXT" +
     ");";
public static final String SQL_DROP = "DROP TABLE IF EXISTS " + TABLE_NAME;
//===========database

I defined all these things in my model object.

Create a Database Using a SQL Helper
package com.sillycat.easyrestclientandroid.dao.db;

import com.sillycat.easyrestclientandroid.model.Product;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class BasicDBHelper extends SQLiteOpenHelper {

     public static final int DATABASE_VERSION = 1;

     public static final String DATABASE_NAME = "sillycat.db";

     public BasicDBHelper(Context context) {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
     }

     public void onCreate(SQLiteDatabase db) {
          db.execSQL(Product.SQL_CREATE);
     }

     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          db.execSQL(Product.SQL_DROP);
          onCreate(db);
     }
   
}

Put Information into a Database
public class ProductDBDAOImpl implements ProductDAO {
     private BasicDBHelper helper;
     public ProductDBDAOImpl(BasicDBHelper helper) {
          this.helper = helper;
     }
…snip…
public Product insert(Product product) {
     synchronized (DBGuard.class) {
          SQLiteDatabase db = null;
          try {
               db = helper.getWritableDatabase();
               Long id = db.insert(Product.TABLE_NAME,
               Product.COLUMN_NAME_PRODUCT_NAME, getValues(product));
               product.setProductId(id);
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               if (db != null) {
                    db.close();
               }
          }
          return product;
     }
}


private ContentValues getValues(Product item) {
     ContentValues values = new ContentValues();
     values.put(Product.COLUMN_NAME_PRODUCT_DESN, item.getProductDesn());
     values.put(Product.COLUMN_NAME_PRODUCT_ID, item.getProductId());
     values.put(Product.COLUMN_NAME_PRODUCT_IMAGE_URL,item.getProductImageURL());
     values.put(Product.COLUMN_NAME_PRODUCT_NAME, item.getProductName());
     values.put(Product.COLUMN_NAME_PRODUCT_PRICE, item.getProductPrice());
     return values;
}


…snip…
}

Read Information from a Database
public List<Product> all() {
     List<Product> items = new ArrayList<Product>();
     synchronized (DBGuard.class) {
          SQLiteDatabase db = null;
          Cursor cursor = null;
          try {
               db = helper.getReadableDatabase();
               cursor = db.query(Product.TABLE_NAME, new String[] {
                    Product.COLUMN_NAME_PRODUCT_DESN,
                    Product.COLUMN_NAME_PRODUCT_ID,
                    Product.COLUMN_NAME_PRODUCT_IMAGE_URL,
                    Product.COLUMN_NAME_PRODUCT_NAME,
                    Product.COLUMN_NAME_PRODUCT_PRICE }, null, null, null, null, null);
               if (cursor != null && cursor.getColumnCount() > 0) {
                    cursor.moveToFirst();
                    while (cursor.getPosition() != cursor.getCount()) {
                         items.add(getItem(cursor));
                         cursor.moveToNext();
                    }
               }
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               if (cursor != null) {
                    cursor.close();
               }
               if (db != null) {
                    db.close();
               }
          }
     }
     return items;
}


private Product getItem(Cursor cursor) {
     Product item = new Product();
     item.setProductDesn(cursor.getString(0));
     item.setProductId(cursor.getLong(1));
     item.setProductImageURL(cursor.getString(2));
     item.setProductName(cursor.getString(3));
     item.setProductPrice(cursor.getString(4));
     return item;
}



Delete Information from a Database
publicboolean deleteById(Long productId) {
     synchronized (DBGuard.class) {
          SQLiteDatabase db = null;
          try {
               db = helper.getReadableDatabase();
               db.delete(Product.TABLE_NAME, "id = ?",
               new String[] { productId + "" });
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               if (db != null) {
                    db.close();
               }
          }
     }
     return false;
}


Update a Database
public Product update(Product product) {
     Product item = null;
     synchronized (DBGuard.class) {
          SQLiteDatabase db = null;
          try {
               db = helper.getWritableDatabase();
               db.update(Product.TABLE_NAME, getValues(product), "id=?",
               new String[] { "" + product.getProductId() });
          } catch (Exception e) {
               e.printStackTrace();
          } finally {
               if (db != null) {
                    db.close();
               }
          }
     }
     return item;
}



DBGuard is just an empty class that used to lock the synchronized things. I am not sure it is necessary. How can the customer type his mobile devices in that fast? Haha.


References:
http://developer.android.com/training/basics/data-storage/index.html


分享到:
评论

相关推荐

    Android-android-ui-animation-components-and-libraries.zip

    Android-android-ui-animation-components-and-libraries.zip,android ui库、组件和动画作者@ramotion-https://github.com/ramotion/swift-ui-animation-components-libraries,安卓系统是谷歌在2008年设计和制造的。...

    Android---UI篇

    •Android---UI篇---Tab Layout(选项卡布局) • •Andorid---UI篇---TableLayout(表格布局) ...•Android---UI篇---ListView之SimpleCursorAdapter(列表)---3 • •Android---UI篇---Menu(菜单)

    android-ui-test-runner-master.rar

    3. 配置Test Runner,确保测试运行时使用的是`android-ui-test-runner`。 4. 运行测试,观察测试结果和报告。 六、最佳实践与注意事项 - 测试用例应尽可能独立,避免相互影响。 - 使用`@UiThreadTest`注解来标识...

    Android-awesome-android-ui.zip

    Android-awesome-android-ui.zip,一份精选的android ui/ux库列表,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核之上构建的,具有安全性优势。

    android-support-core-ui-26.0.0-alpha1.jar

    android-support-core-ui-26.0.0-alpha1.jar

    Android源码查看ui-闹钟-导航-pdf等.rar

    Android源码查看ui-闹钟-导航-pdf等.rar

    Android代码-android-ui-toolkit-demos

    This project includes sample applications that demonstrate different features of the Android Framework and Support Library. It is actively managed by the Android Framework Team. Disclaimers This is ...

    restclient-ui-3.2.2-jar-with-dependencies

    "restclient-ui-3.2.2-jar-with-dependencies" 是这个工具的一个特定版本,该版本包含了所有必要的依赖项,使得用户可以直接运行而无需额外安装其他库。这个版本号表明它是RESTClient的3.2.2迭代,且“jar-with-...

    ui-fabric-android,Office UI Fabric for Android-为Office和Office 365构建体验的前端框架.zip

    "ui-fabric-android"是一个专为Office和Office 365设计的前端框架,它针对Android平台进行了优化,旨在提供一致、高效的用户界面组件和设计系统。这个开源项目旨在帮助开发者构建与Office品牌相符的高质量应用程序,...

    android-support-v4.jar android-support-v13.jar android-support-v7-gridlayout.jar

    3. **android-support-v7-gridlayout.jar** 这个库专门引入了GridLayout布局管理器,它是Android SDK API Level 14(Ice Cream Sandwich)引入的一个新特性,但在早期版本中无法使用。GridLayout允许开发者创建网格...

    新版Android开发教程&笔记--基础入门

    新版Android开发教程+笔记九--基础UI编程3 新版Android开发教程+笔记十--基础UI编程4 新版Android开发教程+笔记十一--可视化UI设计DroidDraw 新版Android开发教程+笔记十二--文件存取、数据库编程

    android-整体UI设计-滑动导航栏+滚动页面

    很多朋友对RollNavigationBar+SlidePageView如何设计业务界面感到疑惑,今天我专门写...了解详情可以看我的博客《android-整体UI设计-(滑动导航栏+滚动页面)》http://blog.csdn.net/swadair/article/details/7551609

    android-async-http-1.4.8.jar

    强大的网络请求库,主要特征如下: 处理异步Http请求,并通过匿名内部类...Http请求均位于非UI线程,不会阻塞UI操作 通过线程池处理并发请求 处理文件上传、下载 响应结果自动打包JSON格式 自动处理连接断开时请求重连

    android ui patterns

    开源项目推荐:Android UI Patterns 实现各种UI效果,含动画

    Android-react-native-ui-lib.zip

    Android-react-native-ui-lib.zip,用于react native的ui组件库,安卓系统是谷歌在2008年设计和制造的。操作系统主要写在爪哇,C和C 的核心组件。它是在linux内核之上构建的,具有安全性优势。

    新版Android开发教程及笔记-完整版.pdf

    新版Android开发教程+笔记九--基础UI编程3.pdf 新版Android开发教程+笔记十--基础UI编程4.pdf 新版Android开发教程+笔记十一--可视化UI设计DroidDraw.pdf 新版Android开发教程+笔记十二--文件存取、数据库编程.pdf ...

    Saving Data on Android - v1.zip

    《Saving Data on Android》是针对Android开发人员的一份宝贵资源,特别关注于在Android平台上保存数据的方法。这个压缩包包含了三种格式的文档——PDF、ePub以及源代码,旨在帮助开发者深入理解如何在Swift服务器端...

    Android--开发--奇艺高清UI界面源代码.rar

    Android--开发--奇艺高清UI界面源代码

    android-support-v7-appcompat.jar android-support-v4.jar

    在Android开发中,`android-support-v7-appcompat.jar` 和 `android-support-v4.jar` 是两个非常重要的库文件,它们提供了对旧版本Android系统的重要支持和功能扩展。 首先,`android-support-v7-appcompat.jar` 是...

    Android系统定制-SystemUI-下拉状态栏快捷设置新增选项(自动亮度&amp;静音)_Patch

    Android系统定制-SystemUI-下拉状态栏快捷设置新增选项(自动亮度&静音)_Patch 文章链接:https://blog.csdn.net/qq_33750826/article/details/122829104

Global site tag (gtag.js) - Google Analytics