在主活动中将单击的图像打开到另一个活动

时间:2011-11-15 07:41:52

标签: android android-layout android-widget

我可以在gridview中从SD卡打开我的图像,也可以使用以下代码将图像路径传递给另一个活动:

package com.example.sdcardimage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class Imageshow extends Activity {


    private Cursor cursor;
    private int columnIndex;
     TextView text;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);  
       text = (TextView)findViewById(R.id.text);
        // Set up an array of the Thumbnail Image ID column we want
        String[] projection = {MediaStore.Images.Thumbnails._ID};
        // Create the cursor pointing to the SDCard
        cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                projection, // Which columns to return
                null,       // Return all rows
                null,
                MediaStore.Images.Thumbnails.IMAGE_ID);
        // Get the column index of the Thumbnails Image ID
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);


        GridView sdcardImages = (GridView) findViewById(R.id.sdcard);
        sdcardImages.setAdapter(new ImageAdapter(this));

        // Set up a click listener
      sdcardImages.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                // Get the data location of the image
                String[] projection = {MediaStore.Images.Media.DATA};
                cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        projection, // Which columns to return
                        null,       // Return all rows
                        null,
                        null);
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToPosition(position);
                // Get image filename
                 String imagePath = cursor.getString(columnIndex);
                 text.setText(imagePath);
                 Intent i = new Intent(getBaseContext(), preview.class);
                 i.putExtra("Value1", imagePath);
                         startActivity(i);

                }
        });
    }

    /**
     * Adapter for our image files.
     */
    private class ImageAdapter extends BaseAdapter {

        private Context context;

        public ImageAdapter(Context localContext) {
            context = localContext;
        }

        public int getCount() {
            return cursor.getCount();
        }
        public Object getItem(int position) {
            return position;
        }
        public long getItemId(int position) {
            return position;
        }
        public View getView(final int position, View convertView, ViewGroup parent) 
        {
            ImageView picturesView;
            if (convertView == null) 
            {
                picturesView = new ImageView(context);
                // Move cursor to current position
                cursor.moveToPosition(position);
                // Get the current value for the requested column
                int imageID = cursor.getInt(columnIndex);
                // Set the content of the image based on the provided URI
                picturesView.setImageURI(Uri.withAppendedPath(
                        MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
                picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                picturesView.setPadding(8, 8, 8, 8);
                picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
            }
            else 
            {
                picturesView = (ImageView)convertView;
            }
            return picturesView;
        }
    }
 }

现在当我使用从上面的代码中获得的路径在imageView中打开一个图像时,它给我空指针异常我的代码在另一个活动中使用获得的路径打开图像如下:

package com.example.sdcardimage;

import java.io.BufferedInputStream;
import java.io.FileInputStream;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class preview extends Activity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        ImageView picture = (ImageView)findViewById(R.id.imagepath);
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            return;
        }
        String value1 = extras.getString("Value1");
        if (value1 != null)
        {
        TextView text = (TextView)findViewById(R.id.text);
        text.setText(value1);
        FileInputStream in;
        BufferedInputStream buf;    
    try{ 
        in = new FileInputStream(value1);
        buf = new BufferedInputStream(in);
        Bitmap bMap = BitmapFactory.decodeStream(buf);
        Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 150, 100, true);
        picture.setImageBitmap(bMapScaled);
        if (in != null) 
        {
            in.close();
           }
            if (buf != null) {
            buf.close();
            }
        } catch (Exception e) {
            Log.e("Error reading file", e.toString());
        }
       }
    }
}

为什么我得到空指针异常而无法在imageView中显示图像?

我的日志如下

11-15 13:59:14.764: ERROR/AndroidRuntime(823): Uncaught handler: thread main exiting due to uncaught exception
11-15 13:59:14.814: ERROR/AndroidRuntime(823): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sdcardimage/com.example.sdcardimage.preview}: java.lang.NullPointerException
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.os.Looper.loop(Looper.java:123)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread.main(ActivityThread.java:3948)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at java.lang.reflect.Method.invokeNative(Native Method)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at java.lang.reflect.Method.invoke(Method.java:521)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at dalvik.system.NativeStart.main(Native Method)
11-15 13:59:14.814: ERROR/AndroidRuntime(823): Caused by: java.lang.NullPointerException
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at com.example.sdcardimage.preview.onCreate(preview.java:32)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
11-15 13:59:14.814: ERROR/AndroidRuntime(823):     ... 11 more

更新

我得到了我想要的输出,所以我发布了我修改后的第二个活动代码,如下所示,这样可以帮助其他人寻找同样的东西:

package com.example.sdcardimage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;


public class preview extends Activity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String filename = extras.getString("Value1");
        FileInputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = new FileInputStream(new File(filename));
            bis = new BufferedInputStream(is);
            Bitmap bitmap = BitmapFactory.decodeStream(bis);
            ImageView image = (ImageView)findViewById(R.id.preview);
            image.setImageBitmap(bitmap);    
            } 
        catch (Exception e) {
            //Try to recover
        }
        finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (is != null) {
                    is.close();
                }    
            } catch (Exception e) {
            }
        }   
    }
}

1 个答案:

答案 0 :(得分:0)

使用此代码

Intent intent = getIntent();
Bundle extras = intent.getExtras();
String filename = extras.getString("filename");
Bitmap originalBitmap = BitmapFactory.decodeFile(filename);
ImageView myimage = (ImageView) findViewById(R.id.ImageView01);
myimage.setImageBitmap(originalBitmap);

最终解决方案

Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    String filename = extras.getString("Value1");
    FileInputStream is = null;
    BufferedInputStream bis = null;
    try {
        is = new FileInputStream(new File(filename));
        bis = new BufferedInputStream(is);
        Bitmap bitmap = BitmapFactory.decodeStream(bis);
        ImageView image = (ImageView)findViewById(R.id.preview);
        image.setImageBitmap(bitmap);    
        } 
    catch (Exception e) {
        //Try to recover
    }
    finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (is != null) {
                is.close();
            }    
        } catch (Exception e) {
        }
    }