user1270217
user1270217

Reputation: 131

Cannot convert Bitmap to Drawable, why do i get this error?

I have spend about 3 hours trying to figure this out and it seems so simple but i cant seem to work it out! Could someone please help me! All i want it to do it display an image from the drawable resources folder. It says that "cannot convert from Bitmap to Drawable".

package com.CS3040.Places;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.CS3040.*;
import com.CS3040.Coursework.R;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class PlaceOverlayItem extends OverlayItem {
    private final GeoPoint point;
    private final Place place;
    private final Drawable marker;
    //private final Context context;

    public PlaceOverlayItem(Context context, Place p, String type) {
        super(p.getGeoPoint(), p.getName(), p.getFormatted_address());

        if(type.equals("restaurant"))
        { 
            //this.marker =
            Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.restaurant);
            this.marker = bmp;

        } 

        //super.setMarker(this.marker);
        this.point = p.getGeoPoint();
        this.place = p;
    }

    /**
     * @return the point
     */
    public GeoPoint getPoint() {
        return point;
    }

    /**
     * @return the place
     */
    public Place getPlace() {
        return place;
    }

    }

Upvotes: 1

Views: 3342

Answers (3)

zapl
zapl

Reputation: 63955

You need to get your resource as a Drawable:

if(type.equals("restaurant"))
{ 
    this.marker = context.getResources().getDrawable(R.drawable.restaurant);
} else {
    // marker would get no value without that else case - not allowed if you declare it final
    this.marker = null;
}

Upvotes: 0

waqaslam
waqaslam

Reputation: 68177

change this:

Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.restaurant);
this.marker = bmp;

to this:

Drawable d = context.getResources().getDrawable(R.drawable.restaurant);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
this.marker = d;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500485

Well it's right - Bitmap doesn't extend Drawable. I haven't done any Android development, but it sounds like you want a BitmapDrawable:

Resources resources = context.getResources();
Bitmap bmp = BitmapFactory.decodeResource(resources, R.drawable.restaurant);
this.marker = new BitmapDrawable(resources, bmp);

Upvotes: 1

Related Questions