赞
踩
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 ArrayAdapter<String> adapter = 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();
List<String> list = getBlocklist();
adapter = new ArrayAdapter<String>(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:
String mpnumber = editText_main_number.getText().toString();
editor.putString(mpnumber, mpnumber);
editor.commit();
fillListView();
break;
case R.id.button_main_clear:
editor.clear();
editor.commit();
fillListView();
break;
default:
break;
}
}
/*
* 获取SharedPreferences中的全部数据,放到List集合中。形成适配器的数据源
*/
private List<String> getBlocklist() {
List<String> list = new ArrayList<String>();
try {
Map<String, ?> map = prefs.getAll();
// 增强for循环,实现对Map集合的遍历
for (Map.Entry<String, ?> entry : 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;
}
}
publicclass SDCardHelper {
privatestatic String TAG = "SDCardHelper";
/*
* 判断sdcard是否挂载
*/
publicstaticboolean isSDCardMounted() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/*
* 获取sdcard绝对物理路径
*/
publicstatic String getSDCardPath() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
returnnull;
}
}
/*
* 获取sdcard的全部的空间大小。返回MB字节
*/
publicstaticlong getSDCardSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardPath());
long size = fs.getBlockSize();
long count = fs.getBlockCount();
return size * count / 1024 / 1024;
}
return 0;
}
/*
* 获取sdcard的剩余的可用空间的大小。返回MB字节
*/
publicstaticlong getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardPath());
long size = fs.getBlockSize();
long count = fs.getAvailableBlocks();
return size * count / 1024 / 1024;
}
return 0;
}
/*
* 将文件(byte[])保存进sdcard指定的路径下
*/
publicstaticboolean saveFileToSDCard(byte[] data, String dir,
String filename) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
Log.i(TAG, "==isSDCardMounted==TRUE");
File file = new File(getSDCardPath() + File.separator + dir);
Log.i(TAG, "==file:" + file.toString() + file.exists());
if (!file.exists()) {
boolean flags = file.mkdirs();
Log.i(TAG, "==创建文件夹:" + flags);
}
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, filename)));
bos.write(data, 0, data.length);
bos.flush();
returntrue;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
returnfalse;
}
/*
* 已知文件的路径,从sdcard中获取到该文件,返回byte[]
*/
publicstaticbyte[] loadFileFromSDCard(String filepath) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
if (isSDCardMounted()) {
File file = new File(filepath);
if (file.exists()) {
try {
baos = new ByteArrayOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
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();
} finally {
try {
if (bis != null) {
bis.close();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
returnnull;
}
}
(四)、案例:
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 AsyncTask<String, Void, byte[]> {
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<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < arrCurrentFiles.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
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());
}
}
良心的公众号,更多精品文章,不要忘记关注哈
《Android和Java技术栈》
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。