【问题标题】:NullPointerException when setting bitmap in imageview在 imageview 中设置位图时出现 NullPointerException
【发布时间】:2011-03-14 23:29:48
【问题描述】:

大家好,我在设置 ImageView 位图时遇到了 NPE。位图已从 bytearray 解码,并且不为 null 或为空。有任何想法吗?谢谢

public class LoadPic extends Activity{

    private static final String TAG = "Loadpic";
    private ImageView imageview;
    private File tempFile;
    private byte[] imageArray;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        Log.e(TAG, " loadpic onCreate");
        setContentView(R.layout.load);

        imageview = (ImageView)findViewById(R.id.imageView1);

        tempFile = new File(Environment.getExternalStorageDirectory().
             getAbsolutePath() + "/"+"image.jpg");

        imageArray = new byte[(int)tempFile.length()];

  try{

        InputStream is = new FileInputStream(tempFile);
        BufferedInputStream bis = new BufferedInputStream(is);
        DataInputStream dis = new DataInputStream(bis);


        int i = 0;

        while (dis.available() > 0) {
        imageArray[i] = dis.readByte();
        i++;
        }

        dis.close();

  } catch (Exception e) {

           e.printStackTrace();
        }

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inSampleSize = 5;
        Bitmap bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
        Log.e(TAG, bm.toString());
        imageview.setImageBitmap(bm);

    }// end of onCreate


}//end of Activity








<?xml version="1.0" encoding="UTF-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:orientation="vertical" android:layout_width="match_parent" 
                    android:layout_height="wrap_content" android:gravity="fill">


        <ImageView android:id="@+id/imageView1" 
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></ImageView>


     </RelativeLayout>               

【问题讨论】:

  • 请说明是什么特定行导致了 npe。
  • 一个想法是你的 imageView 是空的
  • @Vladimir lvanov imageview.setImageBitmap(bm);是哪里坏了

标签: android imageview


【解决方案1】:

确保ImageViewandroid:id="@+id/imageView1" 确实出现在res/layout/load.xml 中。

【讨论】:

  • @Mathew Willis 当我在添加代码设置图像之前运行它时,屏幕弹出正常。我怎么知道图像视图在那里。它在设计时就在图形布局中
  • 尝试将您的布局粘贴到问题中
  • 我在代码后面粘贴了xml布局文件,只需要向下滚动即可。对不起,如果这不是你的意思。
  • 那个文件是 res/layout/load.xml 吗?还是另一个xml文件?
  • :) 非常感谢。当我创建另一个活动时,我需要另一个 xml 布局文件,但是当您创建一个时,它没有图形布局选项卡。我不得不复制 main.xml 并重命名它。第一次尝试是 load.xml,第二次尝试是 load2.xml。我的应用程序仍在引用 load.xml 而不是 load2.xml .....再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-10
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多