Android数据存储——SharedPreferences及SDCard
button_main_savedata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("age", 38);
editor.putString("username", "wangxiangjun");
editor.putString("pwd", "123456");
editor.putString("username", "xiangjun");
editor.putString("age", "I'm 40 years old!");
editor.commit();
}
});
button_main_readdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
String name = prefs.getString("username", "wxj");
String pwd = prefs.getString("pwd", "000");
int age = prefs.getInt("age", 20);
System.out.println("====>" + name + ":" + pwd + ":" + age);
}
});
//在SettingActivity中。不再需要setContentView(R.layout.activity_main)方法来加载布局了。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.setting);
//备注:This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.这个方法在11版本以上就已经不推荐使用了。
}
publicclass MainActivity extends Activity {
private ListView listView_main_blockList;
private EditText editText_main_number;
private TextView textView_main_emptyinfo;
private SharedPreferences prefs = null;
private Editor editor = null;
private ArrayAdapteradapter = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_main_number = (EditText) findViewById(R.id.editText_main_number);
listView_main_blockList = (ListView) findViewById(R.id.listView_main_blocklist);
textView_main_emptyinfo = (TextView) findViewById(R.id.text_main_emptyinfo);
prefs = getSharedPreferences("blocklist", Context.MODE_PRIVATE);
editor = prefs.edit();
Listlist = getBlocklist();
adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
// 注意setEmptyView()的用法。当适配器为空的时候,设置ListView中的展示内容。
listView_main_blockList.setEmptyView(textView_main_emptyinfo);
listView_main_blockList.setAdapter(adapter);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_add:
break;
case R.id.button_main_clear:
editor.clear();
editor.commit();
fillListView();
break;
default:
break;
}
}
/*
* 获取SharedPreferences中的全部数据,放到List集合中。形成适配器的数据源
*/
private ListgetBlocklist() {
Listlist = new ArrayList ();
try {
Mapmap = prefs.getAll();
// 增强for循环,实现对Map集合的遍历
for (Map.Entryentry : map.entrySet()) {
list.add(entry.getKey());
}
return list;
} catch (Exception e) {
returnnull;
}
}
/*
* 填充ListView控件,实现刷新显示数据的效果
*/
privatevoid fillListView() {
adapter.clear();
adapter.addAll(getBlocklist());
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}
package com.steven.sdcardhelper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
public class SDCardHelper {
// 判断SD卡是否被挂载
public static boolean isSDCardMounted() {
// return Environment.getExternalStorageState().equals("mounted");
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
// 获取SD卡的根目录
public static String getSDCardBaseDir() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
// 获取SD卡的完整空间大小,返回MB
public static long getSDCardSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getBlockCount();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 获取SD卡的剩余空间大小
public static long getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getFreeBlocks();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 获取SD卡的可用空间大小
public static long getSDCardAvailableSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
int count = fs.getAvailableBlocks();
int size = fs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}
// 往SD卡的公有目录下保存文件
public static boolean saveFileToSDCardPublicDir(byte[] data, String type,
String fileName) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = Environment.getExternalStoragePublicDirectory(type);
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的自定义目录下保存文件
public static boolean saveFileToSDCardCustomDir(byte[] data, String dir,
String fileName) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = new File(getSDCardBaseDir() + File.separator + dir);
if (!file.exists()) {
file.mkdirs();// 递归创建自定义目录
}
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的私有Files目录下保存文件
public static boolean saveFileToSDCardPrivateFilesDir(byte[] data,
String type, String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalFilesDir(type);
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 往SD卡的私有Cache目录下保存文件
public static boolean saveFileToSDCardPrivateCacheDir(byte[] data,
String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalCacheDir();
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 从SD卡获取文件
public static byte[] loadFileFromSDCard(String fileDir) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(
new FileInputStream(new File(fileDir)));
byte[] buffer = new byte[8 * 1024];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// 获取SD卡公有目录的路径
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}
// 获取SD卡私有Cache目录的路径
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}
// 获取SD卡私有Files目录的路径
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
}
(四)、案例:
1、功能:点击按钮,实现从网络上访问图片,将图片保存进SDCard中。点击另外一按钮,可以获取到刚才保存进SDCard中的图片,将其加载的页面中的ImageView控件中。
publicclass MainActivity extends Activity {
private ImageView imageView_main_img;
private String urlString = "http://t2.baidu.com/it/u=2,1891512358&fm=19&gp=0.jpg";
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main_img = (ImageView) findViewById(R.id.imageView_main_img);
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_save:
new MyTask(this).execute(urlString);
break;
case R.id.button_main_show:
String filepath = SDCardHelper.getSDCardPath() + File.separator
+ "mydir" + File.separator + "firstimg.jpg";
byte[] data = SDCardHelper.loadFileFromSDCard(filepath);
if (data != null) {
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView_main_img.setImageBitmap(bm);
} else {
Toast.makeText(this, "没有该图片!", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
class MyTask extends AsyncTaskbyte []> {
private Context context;
private ProgressDialog pDialog;
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setMessage("图片加载中...");
}
@Override
protectedvoid onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protectedbyte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
httpConn.setDoInput(true);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = newbyte[1024 * 8];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
returnnull;
}
@Override
protectedvoid onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result == null) {
Toast.makeText(context, "图片加载失败!", Toast.LENGTH_LONG).show();
} else {
// 将字节数组转成Bitmap,然后将bitmap加载的imageview控件中
// Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0,
// result.length);
// imageView_main_img.setImageBitmap(bitmap);
if (SDCardHelper.saveFileToSDCard(result, "mydir",
"firstimg.jpg")) {
Toast.makeText(context, "图片保存OK!", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(context, "图片保存失败!", Toast.LENGTH_LONG)
.show();
}
}
pDialog.dismiss();
}
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}
publicclass MainActivity extends Activity {
private TextView textView_main_currentpath;
private ListView listView_main_fileList;
private File currentFile = null;
private File[] arrCurrentFiles = null;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_main_currentpath = (TextView) findViewById(R.id.text_main_currentpath);
listView_main_fileList = (ListView) findViewById(R.id.listView_main_filelist);
if (SDCardHelper.isSDCardMounted()) {
currentFile = new File(SDCardHelper.getSDCardPath());
fillListView(currentFile);
} else {
Toast.makeText(MainActivity.this, "SDCARD不存在!", Toast.LENGTH_LONG)
.show();
}
listView_main_fileList
.setOnItemClickListener(new OnItemClickListener() {
@Override
publicvoid onItemClick(AdapterView> parent, View view,
int position, long id) {
if (arrCurrentFiles[position].isDirectory()) {
File[] arrSubFiles = arrCurrentFiles[position]
.listFiles();
if (arrSubFiles.length == 0) {
Toast.makeText(MainActivity.this, "您点击的是空目录!",
2000).show();
} else {
fillListView(arrCurrentFiles[position]);
}
} else {
Toast.makeText(MainActivity.this, "您点击的不是目录!",
Toast.LENGTH_LONG).show();
}
}
});
}
publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.imageView_main_back:
if (!currentFile.getAbsolutePath().equals(
SDCardHelper.getSDCardPath())) {
fillListView(currentFile.getParentFile());
}
break;
default:
break;
}
}
publicvoid fillListView(File file) {
currentFile = file;
arrCurrentFiles = currentFile.listFiles();
List
for (int i = 0; i < arrCurrentFiles.length; i++) {
Mapmap = new HashMap ();
if (arrCurrentFiles[i].isDirectory()) {
map.put("imgId", R.drawable.folder);
} else {
map.put("imgId", R.drawable.file);
}
map.put("filename", arrCurrentFiles[i].getName());
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.item_listview_main,
new String[] { "imgId", "filename" }, newint[] {
R.id.imageView_item_listview_type,
R.id.text_item_listview_filename });
listView_main_fileList.setAdapter(adapter);
textView_main_currentpath.setText(currentFile.getAbsolutePath());
}
}