使用ContentProvider管理照片

本文介绍了一个Android应用中实现照片的添加、查询及展示的功能。通过ContentProvider实现了照片的存储与检索,并使用ListView展示所有照片信息。解决在查看照片时遇到的错误,最终成功实现了照片的查看功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里的例程是参考Android讲义,可以添加一张照片、查看所有照片

刚开始查看照片不成功,找到bug并修改终于可以查看



MediaProviderTest.java

public class MediaProviderTest extends Activity {

	Button addButton;
	Button viewButton;
	ListView showList;
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> descs = new ArrayList<String>();
	ArrayList<String> fileNames = new ArrayList<String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		addButton = (Button)findViewById(R.id.add);
		viewButton = (Button)findViewById(R.id.view);
		showList = (ListView)findViewById(R.id.show);
		
		addButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 创建ContentValues对象,准备插入数据
				ContentValues values = new ContentValues();
				values.put(Media.DISPLAY_NAME, "jinta");
				values.put(Media.DESCRIPTION, "金塔");
				values.put(Media.MIME_TYPE, "image/jpeg");
				// 插入数据,返回所插入数据对应的Uri
				Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
				// 加载应用程序下的jinta图片
				Bitmap bitmap = BitmapFactory.decodeResource(MediaProviderTest.this.getResources(), R.drawable.jinta);
				OutputStream os = null;
				try{
					// 获取刚插入的数据的Uri对应的输出流
					os = getContentResolver().openOutputStream(uri);
					// 将bitmap图片保存到Uri对应的数据节点中
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
					os.close();
				}catch(Exception e){
					e.printStackTrace();					
				}
			}
		});
		
		viewButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				names.clear();
				descs.clear();
				fileNames.clear();
				
				// 通过ContentResolver查询所有图片信息
				Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, null, null, null, null);
				while (cursor.moveToNext()){
					// 获取图片的显示名
					String name = cursor.getString(cursor.getColumnIndex(Media.DISPLAY_NAME));
					
					// 获取图片的详细描述
					String desc = cursor.getString(cursor.getColumnIndex(Media.DESCRIPTION));
					
					// 获取图片的保存位置的数据
					byte[] data = cursor.getBlob(cursor.getColumnIndex(Media.DATA));
					
					// 将图片名添加到names集合中
					names.add(name);
					
					// 将图片描述添加到descs集合中
					descs.add(desc);
					// 将图片保存路径添加到fileNames集合中
					fileNames.add(new String(data, 0, data.length - 1));
				}
				// 创建一个List集合,List集合的元素是Map
				List<Map<String, Object>> listItems = new ArrayList<Map<String,Object>>();
				// 将names、descs两个集合对象的数据转换到Map集合中
				for(int i = 0; i < names.size(); i++){
					Map<String, Object> listItem = new HashMap<String, Object>();
					listItem.put("name", names.get(i));
					listItem.put("desc", descs.get(i));
					listItems.add(listItem);
				}
				
				// 创建一个SimpleAdapter
				SimpleAdapter simpleAdapter = new SimpleAdapter(
						MediaProviderTest.this,
						listItems,
						R.layout.line,
						new String[]{"name","desc"}, 
						new int[]{R.id.name,R.id.desc});
				// 为show ListView组件设置Adapter
				showList.setAdapter(simpleAdapter);
			}
		});
		
		// 为show ListView的列表项单击事件添加监听器
		showList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View source, int position,
					long id) {
				// 加载view.xml界面布局代表的视图
				View viewDialog = getLayoutInflater().inflate(R.layout.view, null);
				// 获取viewDialog中ID为image的组件
				ImageView image = (ImageView) viewDialog.findViewById(R.id.image);
				// 设置image显示指定图片
				image.setImageBitmap(BitmapFactory.decodeFile(fileNames.get(position)));
				// 使用对话框显示用户单击的图片
				new AlertDialog.Builder(MediaProviderTest.this).
				setView(viewDialog).setPositiveButton("确定", null).show();
			}
		});
	}
}
各个layout文件:

main.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"
    tools:context=".MediaProviderTest" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <LinearLayout 
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
        <Button 
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add"/>
        <Button 
            android:id="@+id/view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/view"/>
    </LinearLayout>
    <ListView 
        android:id="@+id/show"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

line.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<TextView 
	android:id="@+id/name"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:textSize="20dip"
	/>
<TextView 
	android:id="@+id/desc"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:lines="2"
	/>
</LinearLayout>

view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<ImageView 
	android:id="@+id/image"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:scaleType="fitCenter"
	/>		
</LinearLayout>

在ListView上查看一张照片,发现总是打不开,查看LogCat报错是:bitmap加载图片报错

Unable to decode stream: java.io.FileNotFoundException..... open failed: ENOENT (No such file or directory)



百思不得其解,后来去看模拟器sdcard存放的文件,发现没有Camera文件夹,然后添加这个文件夹,查看图片成功



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值