应用程序未运行,显示NullPointerException

时间:2012-06-26 09:41:15

标签: android logcat

我是新手。现在,这个简单的应用程序将图像作为可绘制的网络下载,然后将其转换为位图(将其存储在缓存中)并在UI中显示。 当我运行它时,它会给出 NullPointerException。

代码: -

public class ImageActivity extends Activity {
    /** Called when the activity is first created. */
    private LruCache<String, Bitmap> mchache;
    ImageView imageview;
    Bitmap image;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


                imageview=(ImageView)findViewById(R.id.img);
        Log.i("shu","HERE @ calling loadimage");
       loadimage();

    }
    public void loadimage()

    {          Log.i("shu","HERE @ inside ");

        image = (Bitmap) mchache.get("img");
        Log.i("shu","HERE @line1passed");

        if (image==null)
        {        Log.i("shu","HERE @ imahe==null");

            downloadimage();
        }
        else if (image != null)
        {        Log.i("shu","HERE @ image!= null");

        imageview.setImageBitmap(image);
        }
    }
    // converts drawable to bitmap
    public static Bitmap drawableToBitmap (Drawable drawable) {
        Log.i("shu","HERE @ drawable to bitmap");

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable)drawable).getBitmap();
        }

        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap); 
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
    public void downloadimage()
    {        Log.i("shu","HERE @ download image");

        String address="http://abd.com/absde.jpg";
        try{ 
           URL url = new URL(address);
         InputStream content = (InputStream)url.getContent();
         Drawable d = Drawable.createFromStream(content , "src"); 
         imageview.setImageDrawable(d);
         Bitmap bmap = drawableToBitmap(d);
         mchache.put("img",bmap);
        }
        catch (IOException e)
        {        Log.i("shu","HERE @ exception");
}
    }

}

现在根据logcat,问题出在这里

            image = (Bitmap) mchache.get("img");

代码b / w两个日志信息,所以任何人都可以指出导致它的原因。 我在支持库的帮助下使用LRUCache,因为它不在api8中。

1 个答案:

答案 0 :(得分:1)

你还没有初始化

private LruCache<String, Bitmap> mchache;

onCreate()

中执行
mchache = LruCache<String, Bitmap>();

之前

loadimage();