赞
踩
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版本以上就已经不推荐使用了。 }
- public class MainActivity extends Activity {
- <span style="font-family:Arial;"> </span>private ListView listView_main_blockList;
- <span style="font-family:Arial;"> </span>private EditText editText_main_number;
- <span style="font-family:Arial;"> </span>private TextView textView_main_emptyinfo;
- <span style="font-family:Arial;"> </span>private SharedPreferences prefs = null;
- <span style="font-family:Arial;"> </span>private Editor editor = null; private ArrayAdapter<String> adapter = null;
-
- <span style="font-family:Arial;"> </span> @Override protected void onCreate(Bundle savedInstanceState) {
- <span style="font-family:Arial;"> </span> super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
- <span style="font-family:Arial;"> </span>editText_main_number = (EditText) findViewById(R.id.editText_main_number);
- <span style="font-family:Arial;"> </span>listView_main_blockList = (ListView) findViewById(R.id.listView_main_blocklist);
- <span style="font-family:Arial;"> </span>textView_main_emptyinfo = (TextView) findViewById(R.id.text_main_emptyinfo);
- <span style="font-family:Arial;"> </span>prefs = getSharedPreferences("blocklist", Context.MODE_PRIVATE); editor = prefs.edit();
- <span style="font-family:Arial;"> </span> List<String> list = getBlocklist(); adapter = new ArrayAdapter<String>(this,
- <span style="font-family:Arial;"> </span>android.R.layout.simple_list_item_1, list); // 注意setEmptyView()的用法。当适配器为空的时候,设置ListView中的展示内容。
- <span style="font-family:Arial;"> </span>listView_main_blockList.setEmptyView(textView_main_emptyinfo);
- <span style="font-family:Arial;"> </span>listView_main_blockList.setAdapter(adapter); }
-
- <span style="font-family:Arial;"> </span>public void clickButton(View view) {
- <span style="font-family:Arial;"> </span>switch (view.getId()) {
- <span style="font-family:Arial;"> </span>case R.id.button_main_add:
- <span style="font-family:Arial;"> </span>String mpnumber = editText_main_number.getText().toString();
- <span style="font-family:Arial;"> </span>editor.putString(mpnumber, mpnumber);
- <span style="font-family:Arial;"> </span>editor.commit(); fillListView();
- <span style="font-family:Arial;"> </span>break;
- <span style="font-family:Arial;"> </span>case R.id.button_main_clear:
- <span style="font-family:Arial;"> </span>editor.clear();
- <span style="font-family:Arial;"> </span>editor.commit();
- <span style="font-family:Arial;"> </span> fillListView();
- <span style="font-family:Arial;"> </span>break;
- <span style="font-family:Arial;"> </span>default:
- <span style="font-family:Arial;"> </span> break; }
- <span style="font-family:Arial;"> </span> }
- <span style="font-family:Arial;"> </span>/* * 获取SharedPreferences中的全部数据,放到List集合中。形成适配器的数据源 */
- <span style="font-family:Arial;"> </span>private List<String> getBlocklist() { List<String> list = new ArrayList<String>();
- <span style="font-family:Arial;"> </span>try { Map<String, ?> map = prefs.getAll();
- <span style="font-family:Arial;"> </span> // 增强for循环,实现对Map集合的遍历
- <span style="font-family:Arial;"> </span>for (Map.Entry<String, ?> entry : map.entrySet()) {
- <span style="font-family:Arial;"> </span> list.add(entry.getKey());
- <span style="font-family:Arial;"> </span> }
- <span style="font-family:Arial;"> </span>return list;
- <span style="font-family:Arial;"> </span> } catch (Exception e) {
- <span style="font-family:Arial;"> </span>return null;
- <span style="font-family:Arial;"> </span>}
- <span style="font-family:Arial;"> </span>}
- <span style="font-family:Arial;"> </span> /* * 填充ListView控件,实现刷新显示数据的效果 */
- <span style="font-family:Arial;"> </span>private void fillListView() {
- <span style="font-family:Arial;"> </span>adapter.clear();
- <span style="font-family:Arial;"> </span>adapter.addAll(getBlocklist());
- <span style="font-family:Arial;"> </span> }
- <span style="font-family:Arial;"> </span> @Override
- <span style="font-family:Arial;"> </span>public boolean onCreateOptionsMenu(Menu menu) {
- <span style="font-family:Arial;"> </span>getMenuInflater().inflate(R.menu.main, menu);
- <span style="font-family:Arial;"> </span>return true;
- <span style="font-family:Arial;"> </span>}
- }
public class SDCardHelper { private static String TAG = "SDCardHelper"; /* * 判断sdcard是否挂载 */ public static boolean isSDCardMounted() { return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } /* * 获取sdcard绝对物理路径 */ public static String getSDCardPath() { if (isSDCardMounted()) { return Environment.getExternalStorageDirectory() .getAbsolutePath(); } else { return null; } } /* * 获取sdcard的全部的空间大小。返回MB字节 */ public static long 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字节 */ public static long 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指定的路径下 */ public static boolean 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(); return true; } catch (Exception e) { e.printStackTrace(); } finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } /* * 已知文件的路径,从sdcard中获取到该文件,返回byte[] */ public static byte[] 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 = new byte[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(); } } } } return null; } }
(四)、案例:
1、功能:点击按钮,实现从网络上访问图片,将图片保存进SDCard中。点击另外一按钮,可以获取到刚才保存进SDCard中的图片,将其加载的页面中的ImageView控件中。
public class 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 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView_main_img = (ImageView) findViewById(R.id.imageView_main_img); } public void 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 protected void onPreExecute() { super.onPreExecute(); pDialog.show(); } @Override protected byte[] 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 = new byte[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(); } return null; } @Override protected void 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 public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } } } }
public class MainActivity extends Activity { private TextView textView_main_currentpath; private ListView listView_main_fileList; private File currentFile = null; private File[] arrCurrentFiles = null; @Override protected void 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 public void 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(); } } }); } public void clickButton(View view) { switch (view.getId()) { case R.id.imageView_main_back: if (!currentFile.getAbsolutePath().equals( SDCardHelper.getSDCardPath())) { fillListView(currentFile.getParentFile()); } break; default: break; } } public void 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" }, new int[] { R.id.imageView_item_listview_type, R.id.text_item_listview_filename }); listView_main_fileList.setAdapter(adapter); textView_main_currentpath.setText(currentFile.getAbsolutePath()); } }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。