android sharedpreference保存boolean,int,float,long,String和图片的使用方法及实例(附快速使用类文件)

  hello,大家好,今天上传一下本人对于android 中sharedpreference的理解,以及自己使用的一个Demo的讲解。

   

SharedPreferences是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。实现SharedPreferences存储的步骤如下:

  一、根据Context获取SharedPreferences对象

  二、利用edit()方法获取Editor对象。

  三、通过Editor对象存储key-value键值对数据。

  四、通过commit()方法提交数据。

SharedPreferences相对于sqllite使用起来相当方便,但是SharedPreferences也只能存储boolean,int,float,long和String五种简单的数据类型,本文在上述五种类型的基础上增加了图片的保存,并将其封装成了一个可以快速使用的java类,下面进行代码的展示跟演示:

PreferencesUtils.java文件:

其中将SharedPreferences的五种类型以及图片的读取和存储都写好了,使用时可直接引入到项目中进行快速开发。

package com.example.sharedpreferencedtestdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;


public class PreferencesUtils {

    public static String PREFERENCE_NAME = "TrineaAndroidCommon";

    /**
     * put string preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putString(Context context, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    /**
     * get string preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this
     *         name that is not a string
     * @see #getString(Context, String, String)
     */
    public static String getString(Context context, String key) {
        return getString(context, key, null);
    }

    /**
     * get string preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a string
     */
    public static String getString(Context context, String key, String defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getString(key, defaultValue);
    }

    /**
     * put int preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putInt(Context context, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        return editor.commit();
    }

    /**
     * get int preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a int
     * @see #getInt(Context, String, int)
     */
    public static int getInt(Context context, String key) {
        return getInt(context, key, -1);
    }

    /**
     * get int preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a int
     */
    public static int getInt(Context context, String key, int defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);
    }

    /**
     * put long preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putLong(Context context, String key, long value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(key, value);
        return editor.commit();
    }

    /**
     * get long preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a long
     * @see #getLong(Context, String, long)
     */
    public static long getLong(Context context, String key) {
        return getLong(context, key, -1);
    }

    /**
     * get long preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a long
     */
    public static long getLong(Context context, String key, long defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getLong(key, defaultValue);
    }

    /**
     * put float preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putFloat(Context context, String key, float value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putFloat(key, value);
        return editor.commit();
    }

    /**
     * get float preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
     *         name that is not a float
     * @see #getFloat(Context, String, float)
     */
    public static float getFloat(Context context, String key) {
        return getFloat(context, key, -1);
    }

    /**
     * get float preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a float
     */
    public static float getFloat(Context context, String key, float defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getFloat(key, defaultValue);
    }

    /**
     * put boolean preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static boolean putBoolean(Context context, String key, boolean value) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }

    /**
     * get boolean preferences, default is false
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
     *         name that is not a boolean
     * @see #getBoolean(Context, String, boolean)
     */
    public static boolean getBoolean(Context context, String key) {
        return getBoolean(context, key, false);
    }

    /**
     * get boolean preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
     *         this name that is not a boolean
     */
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getBoolean(key, defaultValue);
    }
    
    /**
     * get picture preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
     *         name that is not a picture
     */
    public static Drawable getPicture(Context context,String key){
    	return getPicture(context, key,"");
    }
    
    /**
     * get picture preferences
     * 
     * @param context
     * @param key The name of the preference to retrieve
     * @param defaultValue Value to return if this preference does not exist
     * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
     *         name that is not a picture
     */
    public static Drawable getPicture(Context context,String key,String defaultValue){
    	SharedPreferences settings=context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
    	String srcName=settings.getString(key, defaultValue);
    	byte[] base64Bytes = Base64.decode(srcName, 1);
		ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
		return Drawable.createFromStream(bais, srcName);
    }
    
    /**
     * put picture preferences
     * 
     * @param context
     * @param key The name of the preference to modify
     * @param value The new value for the preference
     * @return True if the new values were successfully written to persistent storage.
     */
    public static Boolean putPicture(Context context,String key,Drawable value){
    	SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((BitmapDrawable) value).getBitmap().compress(CompressFormat.JPEG, 100, baos);
        String srcName = new String(Base64.encodeToString(
				baos.toByteArray(), 1));
        editor.putString(key, srcName);
        return editor.commit();
    	
    }
}


在Demo中我选择进行了String,Boolean(个人理解用来保存开关之类的比较方便),图片三种比较常用的保存。

下面是Demo的XML文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edt_string"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:hint="请输入要保存的内容" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/txt_boolen"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:text="现在是True" />

        <Button
            android:id="@+id/changeBool"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:onClick="changeBool"
            android:text="chanageBool"
            android:textSize="12sp" />
    </LinearLayout>

    <ImageView
        android:id="@+id/customer_img_shop"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:clickable="true"
        android:onClick="changepicture"
        android:src="@drawable/nopicture" />

    <Button
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="save"
        android:text="采用SharedPreference保存上述类容" />
    
    <Button 
        android:id="@+id/read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="read"
        android:text="采用SharedPreference读出上述类容"/>

</LinearLayout>


以及Demo的MainActivity文件,其中由于要保存图片,于是加了一个拍照和读取本地文件的功能,有需要的朋友也可以看看,没需要的朋友就可以直接略过了。

MainActivity.java:

package com.example.sharedpreferencedtestdemo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private Boolean nowBoolean=true;
	private EditText edt_string;
	private TextView txt_boolen;
	private TextView take_picture_tv;
	private TextView gallery_tv;
	private String ImageName;
	private static final int REQUESTCODE_TAKEPICTURE = 1;
	private static final int REQUESTCODE_PICTUREROOM = 2;
	private static final int REQUESTCODE_TAKEPICTURE_CUT = 3;
	private String imagepath = "image/*";
	private Bitmap tmpBitmap;
	private ImageView customer_img_shop;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		txt_boolen=(TextView) findViewById(R.id.txt_boolen);
		edt_string=(EditText) findViewById(R.id.edt_string);
		customer_img_shop=(ImageView) findViewById(R.id.customer_img_shop);
	}
	
	//将当前Bool值置反
	public void changeBool(View view){
		if (nowBoolean==true){
			nowBoolean=false;
			txt_boolen.setText("现在是false");
		}else if (nowBoolean==false) {
			nowBoolean=true;
			txt_boolen.setText("现在是true");
		}else {
			Toast.makeText(this, "Rrror!", Toast.LENGTH_SHORT).show();
			return;
		}

	}
	
	//点击图片的地方选择图片
	public void changepicture(View view){
		takepicture();
	}
	
	//点击保存SharedPreference数据
	public void save(View view){
		PreferencesUtils.putBoolean(this, "Boolen", nowBoolean);
		PreferencesUtils.putString(this, "String", edt_string.getText().toString());
		PreferencesUtils.putPicture(this, "picture", customer_img_shop.getDrawable());
	}
	
	//点击读取已保存的SharedPreference数据
	public void read(View view){
		nowBoolean=PreferencesUtils.getBoolean(this, "Boolen", true);
		if (nowBoolean==true){
			txt_boolen.setText("现在是true");
		}else if (nowBoolean==false) {
			txt_boolen.setText("现在是false");
		}else {
			Toast.makeText(this, "Rrror!", Toast.LENGTH_SHORT).show();
			return;
		}
		edt_string.setText(PreferencesUtils.getString(this, "String", ""));
		customer_img_shop.setImageDrawable(PreferencesUtils.getPicture(this, "picture"));
	}
	
	// 选择本地照片/拍摄新的照片
		private void takepicture() {

			final AlertDialog imgdialog = new AlertDialog.Builder(
					this).show();
			imgdialog.setContentView(R.layout.settings_photo);
			take_picture_tv = (TextView) imgdialog
					.findViewById(R.id.take_picture_tv);
			gallery_tv = (TextView) imgdialog.findViewById(R.id.gallery_tv);

			// 调用相机
			take_picture_tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					try {
						ImageName = "/picture.jpg";
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(Environment
										.getExternalStorageDirectory(), ImageName)));

						if (CommonTools.isIntentAvailable(
								MainActivity.this, intent)) {
							startActivityForResult(intent, REQUESTCODE_TAKEPICTURE);
						} else {
							Toast.makeText(MainActivity.this,
									R.string.persional_information_camera_notexist,
									Toast.LENGTH_SHORT).show();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					imgdialog.dismiss();
				}
			});

			// 从相册选择
			gallery_tv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_PICK, null);
					intent.setDataAndType(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imagepath);
					startActivityForResult(intent, REQUESTCODE_PICTUREROOM);
					imgdialog.dismiss();
				}
			});

		}

		// 处理图片--------------------------------------------------------------------------------

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (resultCode != Activity.RESULT_OK) {
				return;
			}
			// 拍照
			if (requestCode == REQUESTCODE_TAKEPICTURE) {
				// 设置文件保存路径这里放在根目录下
				File picture = new File(Environment.getExternalStorageDirectory()
						+ ImageName);
				startPhotoZoom(Uri.fromFile(picture));
			}
			if (data == null) {
				return;
			}
			// 相册
			if (requestCode == REQUESTCODE_PICTUREROOM) {
				startPhotoZoom(data.getData());
			}

			if (requestCode == REQUESTCODE_TAKEPICTURE_CUT) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					Bitmap photo = extras.getParcelable("data");
					tmpBitmap = photo;
						customer_img_shop.setImageBitmap(tmpBitmap);	
					FileOutputStream stream = null;
					try {
						stream = new FileOutputStream(this.getApplicationContext()
								.getFilesDir().getAbsolutePath()
								+ "/shop.jpg");

					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (photo != null && stream != null) {
						photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
						// face.setImageBitmap(photo);
					}
				}
				super.onActivityResult(requestCode, resultCode, data);
			}
		}

		// 处理图片的大小
		public void startPhotoZoom(Uri uri) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, imagepath);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", MyTools.dip2px(this, 150));
			intent.putExtra("outputY", MyTools.dip2px(this, 150));
			intent.putExtra("return-data", true);

			intent.putExtra("scale", true);
			intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
			intent.putExtra("noFaceDetection", false);

			startActivityForResult(intent, REQUESTCODE_TAKEPICTURE_CUT);
		}
}


Demo下载地址: http://download.csdn.net/detail/a332802774/8472467
希望能够帮到大家,谢谢观看!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值