Home  >  Article  >  Java  >  What data types can sharedpreferences store?

What data types can sharedpreferences store?

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-03 14:51:485567browse

SharedPreferences can only save simple types of data, and can only store string, int, float, long and boolean data types. If you need to access more complex data types such as classes or images, you need to encode the data.

What data types can sharedpreferences store?

The operating environment of this tutorial: windows7 system, java10 version, Dell G3 computer.

We often need to save data in daily development. Commonly used storage methods in Android include SQLite, sharedPreferences, etc. Of course, they also have their own application scenarios. The former is suitable for saving more data, and the latter is more responsible for the tendency. To save user preferences, such as the selection status of a certain checkbox, user login status, configuration information, realize password remembering function, etc., files are read in the form of key-value pairs.

But each time a piece of data is stored, a key must be provided. If you want to store multiple data, don't you have to write multiple keys? For example, we want to save a user's login information, such as user nickname, personalized signature, login time... Nima, if I write one piece of data, I can play a game of Luo. Anyway, I can't stand it. So, can we How about encapsulating user information and storing it with one key? The answer is yes~
The byte input and output streams provided in the Java class library can easily help us complete the reversible conversion of any type to String, and then we can save it to Share~

SharedPreferences Only simple types of data can be saved, such as the four basic types (int, float, long, boolean) String. If you need to access more complex data types such as classes or images, you need to encode the data, usually convert it to Base64 encoding, and then save the converted data in the form of a string in an XML file.

What data types can sharedpreferences store?

Easy to use:

Savable types:

string, int, float, long, boolean

		//获取sharedPreferences对象
        SharedPreferences sharedPreferences = getSharedPreferences("zjl", Context.MODE_PRIVATE);
        //获取editor对象
        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
        //存储键值对
        editor.putString("name", "周杰伦");

        editor.putInt("age", 24);
        editor.putBoolean("isMarried", false);
        editor.putLong("height", 175L);
        editor.putFloat("weight", 60f);

        editor.putStringSet("where", set);
        //提交
        editor.commit();//提交修改





        SharedPreferences sharedPreferences = getSharedPreferences("zjl", Context.MODE_PRIVATE);
        //getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
        String name = sharedPreferences.getString("name", "");
        int age = sharedPreferences.getInt("age", 1);

Storage object:

Method 1: fastJson/Gson/Jackson converts the object into a string and then saves it.

Method 2: ObjectOutputStream converts the object into a stream, base64 converts the stream into a string, and then saves it.

package com.example.draggridview;

/**
 * Created by Administrator on 2017/6/19.
 */

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * SharedPreferences工具类,可以保存object对象
 */
public class SharedPreferenceUtil {

    /**
     * 存放实体类以及任意类型
     *
     * @param context 上下文对象
     * @param key
     * @param obj
     */
    public static void putBean(Context context, String key, Object obj) {
        if (obj instanceof Serializable) {// obj必须实现Serializable接口,否则会出问题
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                String string64 = new String(Base64.encode(baos.toByteArray(), 0));
                SharedPreferences.Editor editor = getSharedPreferences(context).edit();
                editor.putString(key, string64).commit();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            throw new IllegalArgumentException("the obj must implement Serializble");
        }

    }

    public static Object getBean(Context context, String key) {
        Object obj = null;
        try {
            String base64 = getSharedPreferences(context).getString(key, "");
            if (base64.equals("")) {
                return null;
            }
            byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
            ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
    
}

Reference:

Use SharedPreference to save list data. In fact, you can save Object objects

Android development notes - SharedPreferences stores entity classes and any type

Android data persistence SharedPreference

AIDL supported data types

  1. All basic types (byte/short/int/long/float/double/boolean/char, etc.)

  2. String, List, Map, CharSequence and other classes

  3. Other AIDL interface types

  4. All Parcelable class

bundle can pass data types:

1, eight basic types such as byte/short/int/long/float/double/boolean/char or Their corresponding arrays

2, String, charsequence or corresponding arrays can also be objects () or object arrays.

3. Bundle.putSerializable(Key, Object); //Object that implements the Serializable interface

4. Bundle.putParcelable(Key, Object); //Object that implements the Parcelable interface

What data types can sharedpreferences store?

What data types can sharedpreferences store?

What data types can sharedpreferences store?

What data types can sharedpreferences store?

##intent passable data type:

intent delivery type (abcd)

A, Serializable B. charsequence C. Parcelable D. Bundle

1, Eight basic data types and their corresponding arrays

2, String/Charsequence and their corresponding arrays

3, Parcelable and their corresponding arrays/Serializable

4, bundle/intent

What data types can sharedpreferences store?

What data types can sharedpreferences store?

What data types can sharedpreferences store?

## related free learning Recommended:

java basic tutorial

The above is the detailed content of What data types can sharedpreferences store?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn