15、Android数据存储——SharedPreferences及SDCard

Android数据存储——SharedPreferences及SDCard


一、数据存储选项:Data Storage ——Storage Options【重点】
1、Shared Preferences
Store private primitive data in key-value pairs.
保存简单的键值对数据。
2、Internal Storage
Store private data on the device memory.
在手机内存中保存不对外共享的信息。
3、External Storage
Store public data on the shared external storage.
在外部存储设备上保存公共的数据信息。主要指保存在SDCard上。
4、SQLite Databases
Store structured data in a private database.
将结构化的数据保存进数据库。
5、Network Connection
Store data on the web with your own network server.
将数据保存到自己的远程服务器上。
【备注:】
  • 内部存储空间十分有限,因而显得可贵,另外,它也是系统本身和系统应用程序主要的数据存储所在地,一旦内部存储空间耗尽,手机也就无法使用了。 
  • 所以对于内部存储空间,我们要尽量避免使用。Shared Preferences和SQLite数据库都是存储在内部存储空间上的。内部存储一般用Context来获取和操作。 
  • getFilesDir()获取你app的内部存储空间,相当于你的应用在内部存储上的根目录。
  • 最容易混淆的是外部存储,如果说pc上区分出外部存储和内部存储的话,那么自带的硬盘算是内部存储,U盘或者移动硬盘算是外部存储,因此我们很容易带着这样的理解去看待安卓手机,认为机身固有存储是内部存储,而扩展的SDCard卡是外部存储。比如Nexus 4有16G的内部存储,普通消费者可以这样理解,但是安卓的编程中不能,这16GB仍然是外部存储。

二、SharedPreferences:
(一)、概念:
    SharedPreferences是Android系统提供的一个通用的数据持久化框架,用于存储和读取key-value类型的原始基本数据类型对,目前支持string、int、long、float、boolean等基本类型的存储,对于自定义的对象数据类型,无法使用SharedPreferences来存储。
        SharedPreferences主要用于存储系统的配置信息。例如上次登录的用户名,上次最后设置的配置信息(如:是否打开音效、是否使用振动,小游戏的玩家积分等)。当再次启动程序后依然保持原有设置。SharedPreferences用键值对方式存储,方便写入和读取。

(二)、使用SharedPreferences的步骤
1、获取SharedPreferences对象;
        SharedPreferences本身是一个接口,无法直接创建实例,通过Context的getSharedPreferences(String name, int  mode)方法来获取实例。  该方法的第二个参数为 文件读写的操作模式。
2、调用edit()方法获取SharedPreferences.Editor;
3、通过SharedPreferences.Editor接口提供的put()方法对SharedPreferences进行更新;
4、调用SharedPreferences.Editor的commit()方法,将更新提交到SharedPreferences中。


(三)、三种方法来得到SharedPreferences对象:
1、通过Context的getSharedPreferences(String name, int  mode)方法来获取:
        SharedPreferences本身是一个接口,无法直接创建实例,通过Context的getSharedPreferences (String name, int  mode)方法来获取实例。该方法有两个参数,第一个参数用于指定SharedPreferences文件的名称,如果指定的文件不存在则会创建一个,文件的路径在:“/data/data/应用程序包名/shared_prefs/”目录下;
        第二个参数用于指定文件读写的操作模式。

        主要有以下几种模式可以选择:【文件读写的操作模式

  •  Context.MODE_PRIVATE:是默认的操作模式,表示该SharedPreferences文件的数据只能被当前的应用程序读写。当指定同样文件名的时候,新写入的内容会覆盖原文件中的内容; 
  •  Context.MODE_APPEND:表示如果该文件已存在,不会创建新文件,而是往原文件里追加内容; 
  • Context.MODE_MULTI_PROCESS:用于会有多个进程对同一个SharedPreferences文件进行读写; 
  • Context.MODE_WORLD_READABLE:指定 SharedPreferences数据能被其他应用程序读,但是不支持写。该模式已在Android4.2版本中废弃; 
  • Context.MODE_WORLD_WRITEABLE: 指定 SharedPreferences数据能被其他应用程序读、写。会覆盖原数据。该模式已在Android4.2版本中废弃  
  • 可以使用  +  连接这些权限

2、通过Activity类的getPreferences( int  mode)方法来获取:
        这个方法和Context的getSharedPreferences(String name, int  mode)方法很相似,不过该方法只有一个操作模式参数。该方法会自动将当前Activity的类名作为SharedPreferences的文件名。
3、通过PreferenceManager类的getDefaultSharedPreferences( Context context)方法来获取:
        这是一个静态方法,它接收一个Context参数。该方法会将当前应用程序的包名作为前缀来为SharedPreferences文件自动命名。例如包名为“org.mobiletrain.preferenceactivity” 的应用,会在“/data/data/org.mobiletrain.preferenceactivity/shared_prefs/”目录下创建SharedPreferences文件,文件名为org.mobiletrain.preferenceactivity_preferences.xml。

【备注:】
        Android设备上的app都有一个放置在沙盒中的文件目录。将文件保存在沙盒中可以阻止其他APP访问。
每个APP的沙盒目录都是/data/data/包名

        沙盒也叫沙箱,英文sandbox。在计算机领域指一种虚拟技术,且多用于计算机安全技术。其原理是通过重定向技术,把程序生成和修改的文件定向到自身文件夹中。当某个程序试图发挥作用时,安全软件可以先让它在沙盒中运行,如果含有恶意行为,则禁止程序的进一步运行,而这不会对系统造成任何危害。


(四)、核心代码:
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);
                        }
                });


(四)、保存之后的SharedPreferences数据文件:
        SharedPreferences数据总是以xml格式保存在:/data/data/包名/shared_prefs目录下;
例如:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="pwd">123456</string>
    <string name="username">xiangjun</string>
    <int  name="age">20</int>
</map>


(五)、SharedPreferences的设置Settings功能:
1、引入:

        手机中常有这样的设置页面,如果做这样的页面呢?是不是需要写一个复杂的布局文件,再写一堆事件监听来完成呢?

2、PreferenceActivity的简单用法:
    1)、步骤:
  • 将setting.xml文件放到res的xml目录下;
  • 将arrays.xml文件放到values目录下;
  • 写一个页面SettingActivity。
    2)、目录结构:

    3)、核心代码:
    //在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版本以上就已经不推荐使用了。
        }


(六)、借助SharedPreferences实现 黑名单管理

1、示例代码:

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;
}


}


三、内部存储:
(一)、Context类提供的基本文件和目录处理方法
1、getCacheDir()  
获取内部存储缓存目录  /data/data/包名/cache。备注:应及时清理该目录,并节约使用空间

2、getFilesDir()
获取内部存储文件目录  /data/data/包名/ files

跟SharedPreferences目录的区别:/data/data/包名/shared_prefs

3、String[] fileList()   
获取内部存储  /data/data/包名/files 目录下的文件 列表 

4、openFileInput(String name)  
打开内部存储的files目录下的文件

5、openFileOutput(String name , int mode) 
打开内存存储空间上文件进行写入,如果不存在则创建该文件



四、External Storage之SDCard操作:
(一)、引入:Android中提供了特有的两个方法来进行IO操作(openFileInput()和openFileOutput() ),但是毕竟手机内置存储空间很有限,为了更好地存储应用程序的大文件数据,需要读写SD卡上的文件。SD卡大大扩充了手机的存储能力。

(二)、读写SD卡的步骤:
1、先判断手机是否有sd卡;
        调用Environment的getExternalStorageState()方法判断手机是否插上sdcard。
2、获取sdcard的路径;
        调用Environment的getExternalStorageDirectory()方法来获取外部存储器的目录。
3、此外还可以获取SDCard可用磁盘空间的大小(借助StatFs类来实现);
4、清单文件中设置读写sdcard的权限;
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>   在sdcard中创建与删除文件的权限
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>   向sdcard读取权限
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   向sdcard写入权限
5、执行读写操作(基本IO流操作)。

【备注:】
Environment.getExternalStorageDirectory().getPath()来获取sdcard路径,如果您需要往sdcard中保存特定类型的内容,可以考虑使用Environment.getExternalStoragePublicDirectory(String type)方法,该方法可以返回特定类型的目录,目前支持如下类型:
  1. DIRECTORY_ALARMS //警报的铃声 
  2. DIRECTORY_DCIM //相机拍摄的图片和视频保存的位置 
  3. DIRECTORY_DOWNLOADS //下载文件保存的位置 
  4. DIRECTORY_MOVIES //电影保存的位置, 比如 通过google play下载的电影 
  5. DIRECTORY_MUSIC //音乐保存的位置 
  6. DIRECTORY_NOTIFICATIONS //通知音保存的位置 
  7. DIRECTORY_PICTURES //下载的图片保存的位置 
  8. DIRECTORY_PODCASTS //用于保存podcast(博客)的音频文件 
  9. DIRECTORY_RINGTONES //保存铃声的位置

【备注:】
        应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的。 大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中。 这样当该应用被卸载后,这些数据还保留在SDCard中,留下了垃圾数据。 如果你想让你的应用被卸载后,与该应用相关的数据也清除掉,该怎么办呢?

  • 通过Context.getExternalFilesDir()方法可以获取到 SDCard/Android/data/应用的包名/files/ 目录,一般放一些长时间保存的数据  【设置->应用->应用详情里面的”清除数据 Clear Data
  • 通过Context.getExternalCacheDir()方法可以获取到 SDCard/Android/data/应用包名/cache/目录,一般存放临时缓存数据            【设置->应用->应用详情里面的”清除缓存“ Clear Cache
  • 如果使用上面的方法,当你的应用在被用户卸载后,SDCard/Android/data/你的应用的包名/ 这个目录下的所有文件都会被删除,不会留下垃圾信息。
        而且上面二个目录分别对应 设置->应用->应用详情里面的”清除数据“与”清除缓存“选项。当然 如果要保存下载的内容,就不要放在以上目录下。


(三)、SDCard私有文件目录:
1、私有目录的files目录下有分为以下7种(无DIRECTORY_DCIMDIRECTORY_DOWNLOADS
  • DIRECTORY_ALARMS 
  • DIRECTORY_MOVIES
  • DIRECTORY_MUSIC 
  • DIRECTORY_NOTIFICATIONS 
  • DIRECTORY_PICTURES  
  • DIRECTORY_PODCASTS 
  • DIRECTORY_RINGTONES 

2、私有目录的cache目录:



(三)、封装SDCard的工具类:SDCardHelper类
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控件中。
2、示例代码: 、示例代码:

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;

}

}


(五)、案例:SDCard文件浏览器

1、效果如图:

2、原理:利用File对象的listFile()方法获得File[]数组。将数组产生的信息填充在listview中。
核心代码中的重要方法:
  1. listFiles()
  2. isFile()
  3. isDirectory()
  4. getAbsolutePath()
  5. getParentFile()

3、核心示例代码:

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());
}


}



(六)、案例: SDCard图片浏览器












  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值