[Android] automatic access to data entities-sharedpreferences

Source: Internet
Author: User

This example uses sharedpreferences as the data access carrier.
To use sharedpreferences to access a data set, follow these steps:

Sharedpreferences sharedpre = getsharedpreferences (name, mode); Save: sharedpreferences. editor editor = sharedpre. edit (); Editor. put (Key, value); Editor. commit (); Take: value = sharedpre. get (Key, defaultvalue );

Observe the above, the key to access is to standardize the <key, value> operation. The key is a pre-defined string. If there are multiple groups of <key, value>, it is quite difficult to think about the key name for each group.

The core of automatic reading in this article is to directly use the attribute name of the data entity as the key value, traverse the attributes of the data instance during access, and use the reflection class to read the attribute name, write or write attribute values.

This article is sodino all, reprint please note the Source: http://blog.csdn.net/sodino/article/details/7979559

First, define the data types that can be processed in advance as follows:

public static final int CLZ_BYTE = 1;public static final int CLZ_SHORT = 2;public static final int CLZ_INTEGER = 3;public static final int CLZ_LONG = 4;public static final int CLZ_STRING = 5;public static final int CLZ_BOOLEAN = 6;public static final int CLZ_FLOAT = 7;public static final int CLZ_DOUBLE = 8;public static final Map<Class<?>, Integer> TYPES;static {TYPES = new HashMap<Class<?>, Integer>();TYPES.put(byte.class, CLZ_BYTE);TYPES.put(short.class, CLZ_SHORT);TYPES.put(int.class, CLZ_INTEGER);TYPES.put(long.class, CLZ_LONG);TYPES.put(String.class, CLZ_STRING);TYPES.put(boolean.class, CLZ_BOOLEAN);TYPES.put(float.class, CLZ_FLOAT);TYPES.put(double.class, CLZ_DOUBLE);}

Write:

private void doSave(GoodsBean bean) {SharedPreferences sharedPre = getSharedPreferences(GoodsBean.class.getName(), Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPre.edit();Class<? extends GoodsBean> clazz = bean.getClass();Field[] arrFiled = clazz.getDeclaredFields();try {for (Field f : arrFiled) {Log.d("ANDROID_LAB", "type[" + f.getType() + "] name[" + f.getName() + "]");int type = TYPES.get(f.getType());switch (type) {case CLZ_BYTE:case CLZ_SHORT:case CLZ_INTEGER:editor.putInt(f.getName(), f.getInt(bean));break;case CLZ_LONG:editor.putLong(f.getName(), f.getLong(bean));break;case CLZ_STRING:editor.putString(f.getName(), (String) f.get(bean));break;case CLZ_BOOLEAN:editor.putBoolean(f.getName(), f.getBoolean(bean));break;case CLZ_FLOAT:editor.putFloat(f.getName(), f.getFloat(bean));break;case CLZ_DOUBLE:editor.putFloat(f.getName(), (float) f.getDouble(bean));break;}}editor.commit();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}

Read:

private GoodsBean doRead() {SharedPreferences sharedPre = getSharedPreferences(GoodsBean.class.getName(), Context.MODE_PRIVATE);GoodsBean bean = new GoodsBean();Class<? extends GoodsBean> clazz = bean.getClass();Field[] arrFiled = clazz.getDeclaredFields();try {for (Field f : arrFiled) {int type = TYPES.get(f.getType());switch (type) {case CLZ_BYTE:byte byteValue = (byte) sharedPre.getInt(f.getName(), 0);f.set(bean, byteValue);break;case CLZ_SHORT:short shortValue = (short) sharedPre.getInt(f.getName(), 0);f.set(bean, shortValue);break;case CLZ_INTEGER:int intValue = sharedPre.getInt(f.getName(), 0);f.set(bean, intValue);break;case CLZ_LONG:long longValue = sharedPre.getLong(f.getName(), 0L);f.set(bean, longValue);break;case CLZ_STRING:String str = sharedPre.getString(f.getName(), null);f.set(bean, str);break;case CLZ_BOOLEAN:boolean bool = sharedPre.getBoolean(f.getName(), false);f.set(bean, bool);break;case CLZ_FLOAT:float floatValue = sharedPre.getFloat(f.getName(), 0.0f);f.set(bean, floatValue);break;case CLZ_DOUBLE:double doubleValue = sharedPre.getFloat(f.getName(), 0.0f);f.set(bean, doubleValue);break;}}} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}return bean;}

Goodsbean. Java

Package lab. sodino. autosave; public class goodsbean {public string name; public long time; Public int price; Public Boolean ispaid;/*** for testing. */Public byte testbyte;/** for testing. */Public short testshort; public float cicle; Public double testdouble; Public String tostring () {stringbuffer strbuffer = new stringbuffer (); strbuffer. append ("name [" + name + "] \ n"); strbuffer. append ("time [" + time + "] \ n"); strbuffer. append ("price [" + Price + "] \ n"); strbuffer. append ("ispaid [" + ispaid + "] \ n"); strbuffer. append ("cicle [" + cicle + "] \ n"); strbuffer. append ("testbyte [" + testbyte + "] \ n"); strbuffer. append ("testshort [" + testshort + "] \ n"); strbuffer. append ("testdouble [" + testdouble + "] \ n"); Return strbuffer. tostring ();} public static goodsbean newinstance () {goodsbean bean = new goodsbean (); bean. name = "autosave"; bean. time = 12345234252342l; bean. price = 1024; bean. ispaid = true; bean. cicle = 2.356f; bean. testbyte = 8; bean. testshort = 128; bean. testdouble = 9856.2145d; return bean ;}}

Note:
1. Because sharedpreferences only supports reading and writing int, long, Boolean, string, and float data types by default, there are some forced conversion operations. From 01.gif, you can see that the double access operation will cause data distortion. Pay attention to some phenomena in actual coding. For example:

2. Handle the initial default values.

Advantages of automatic access:
1. avoid naming a lot of keys and reduce the tangle time.
2. convenient and efficient. You do not need to modify the access process to change the data structure.
3. After a obfuscation packet is generated, all key values are also obfuscated, which protects the program logic to a certain extent. See Figure 01.png

Disadvantages:
1. Automatic access saves or removes all the defined data structures. To add attributes that do not require local storage, you must create a new class to inherit the original data structure.

There are both advantages and disadvantages, but in general the advantages are far greater than the disadvantages.

Next: [Android] automatic access to data entities-SQLite

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.