drawBitmap nullpointerexception - android

I'm experiencing a nullpointerexception in my android java code in the following code. This is inside AndroidGraphics.java.
public void drawPixmap(Pixmap pixmap, int x, int y) {
canvas.drawBitmap(((AndroidPixmap)pixmap).bitmap, x, y, null);
}
AndroidPixmap.java is here:
package com.badlogic.androidgames.framework.impl;
import android.graphics.Bitmap;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.framework.Pixmap;
public class AndroidPixmap implements Pixmap{
Bitmap bitmap;
PixmapFormat format;
public AndroidPixmap(Bitmap bitmap, PixmapFormat format){
this.bitmap = bitmap;
this.format = format;
}
#Override
public int getWidth(){
return bitmap.getWidth();
}
#Override
public int getHeight(){
return bitmap.getHeight();
}
#Override
public PixmapFormat getFormat(){
return format;
}
#Override
public void dispose(){
bitmap.recycle();
}
}
Is there something wrong with the casting? Any help would be great!
EDIT: This is the pixmap class:
package com.badlogic.androidgames.framework;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
public interface Pixmap {
public int getWidth();
public int getHeight();
public PixmapFormat getFormat();
public void dispose();
}

Your AndroidPixmap implements Pixmap, it is not inherited/extended from Pixmap. If you cast to Pixmap, you get the Implementation only, which I assume has bitmap=null.
As you didn't add the Pixmap class to the question, it's quite hard to answer in more detail.

Try this:
public void drawPixmap(AndroidPixmap pixmap, int x, int y) {
canvas.drawBitmap(pixmap.bitmap, x, y, null);
}
Alternatively if you want to keep Pixmap in the signature you can make it an abstract class and extend it instead of an interface.

Related

Why am I getting "cannot resolve symbol urlDrawable" in this class

I'm trying to display <img> tags in json string and I using the accepted answer in this question but Android Studio is complaining "cannot resolve symbol urlDrawable
Please can anybody tell me why this is happening and how to fix it?
UILImageGetter
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.View;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
public UILImageGetter(View textView, Context context) {
this.c = context;
this.conatiner = (TextView) textView;
}
#Override
public Drawable getDrawable(String source) {
urlDrawable = new UrlImageDownloader(c.getResources(), source);
urlDrawable.drawable = c.getResources().getDrawable(R.drawable.default_thumb);
ImageLoader.getInstance().loadImage(source, new SimpleListener(urlDrawable));
return urlDrawable;
}
private class SimpleListener extends SimpleImageLoadingListener {
UrlImageDownloader mUrlImageDownloader;
public SimpleListener(UrlImageDownloader downloader) {
super();
mUrlImageDownloader= downloader;
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
int width = loadedImage.getWidth();
int height = loadedImage.getHeight();
int newWidth = width;
int newHeight = height;
if (width > conatiner.getWidth()) {
newWidth = conatiner.getWidth();
newHeight = (newWidth * height) / width;
}
if (view != null) {
view.getLayoutParams().width = newWidth;
view.getLayoutParams().height = newHeight;
}
Drawable result = new BitmapDrawable(c.getResources(), loadedImage);
result.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.setBounds(0, 0, newWidth, newHeight);
mUrlImageDownloader.mDrawable = result;
conatiner.setHeight((conatiner.getHeight() + result.getIntrinsicHeight()));
conatiner.invalidate();
}
}
private class UrlImageDownloader extends BitmapDrawable {
public Drawable mDrawable;
public UrlImageDownloader(Resources resources, String filepath) {
super(resources, filepath);
mDrawable = new BitmapDrawable(resources, filepath);
}
#Override
public void draw(Canvas canvas) {
if (mDrawable != null) {
mDrawable.draw(canvas);
}
}
}
}
You haven't assigned a type to urlDrawable;
This portion of code contains the error:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
urlDrawable;
Try this:
public class UILImageGetter implements Html.ImageGetter{
Context c;
TextView conatiner;
UrlImageDownloader urlDrawable;
Java is a strongly typed language, which means that all variables must be declared as being of some type.
Since you don't specify a type for urlDrawable, the compiler doesn't understand that you're declaring a variable.
Simply replace
urlDrawable;
with
UrlImageDownloader urlDrawable;

Constructor is undefined in Android

I have this code but they show errors in
myelement=new Element(getResources(),(int)event.getX(),(int)event.getY());
(Error: The constructor is undefined.
and
myelement.mX=(int)event.getX()-myelement.bitmap.getWidth()/2;
Error: mX cannot be resolved or is not a field
and
myelement.doDraw(canvas);
Error: The method doDraw(Canvas) is undefined for the type Element
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback{
Element myelement;
private MainThread thread;
public GamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread =new MainThread(getHolder(),this);
setFocusable(true);
}
public boolean onTouchEvent(MotionEvent event) {
if(myelement==null)
{
myelement=new Element(getResources(),(int)event.getX(),(int)event.getY());
return true;
}
else
{
myelement.mX=(int)event.getX()-myelement.bitmap.getWidth()/2;
myelement.mY=(int)event.getY()-myelement.bitmap.getHeight()/2;
}
if(event.getAction()==MotionEvent.ACTION_DOWN)
{
myelement.mX=(int)event.getX()-myelement.bitmap.getWidth()/2;
myelement.mY=(int)event.getY()-myelement.bitmap.getHeight()/2;
}
if(event.getAction()==MotionEvent.ACTION_UP)
{
myelement.mX=(int)event.getX()-myelement.bitmap.getWidth()/2;
myelement.mY=(int)event.getY()-myelement.bitmap.getHeight()/2;
}
if(event.getAction()==MotionEvent.ACTION_MOVE)
{
myelement.mX=(int)event.getX()-myelement.bitmap.getWidth()/2;
myelement.mY=(int)event.getY()-myelement.bitmap.getHeight()/2;
}
return true;
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(myelement!=null)
myelement.doDraw(canvas);
}
And:
public class Element {
Bitmap bitmap;
int mX;
int mY;
public Element(Resources res, int x,int y)
{
bitmap=BitmapFactory.decodeResource(res,R.drawable.ic_launcher);
mX=x-bitmap.getWidth()/2;
mY=y-bitmap.getHeight()/2;
}
public Element(Resources res, int x, int y, int idHinh)
{
bitmap=BitmapFactory.decodeResource(res,idHinh);
mX=x-bitmap.getWidth()/2;
mY=y-bitmap.getHeight()/2;
}
public void doDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, mX,mY, null);
}
}
Edit: First, double-check your import declarations. There are several Element classes present in the Android API, i.e. android.renderscript.Element, which you may be inadvertently accessing rather than your custom Element class.
Your Element constructor requires a Resources object for its first argument. However, you call getResources() inside a class that extends SurfaceView, whereas getResources() is a method associated with Context.
SurfaceView is a subclass of View, that has the getContext() method. So, instead of:
myelement=new Element(getResources(),(int)event.getX(),(int)event.getY());
try
myelement=new Element(this.getContext().getResources(),(int)event.getX(),(int)event.getY());

SetTexture and Sprites not working as intended! (LibGDX)

I searched for and wide on the internet and I have yet to find an answer. I have an object called GameIcon which extends Sprite. Everything about it is okay except for the texture. Here is my code for the GameIcon class.
package com.xx4everPixelatedxx.gaterunner.sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.xx4everPixelatedxx.gaterunner.GateRunner;
import javax.xml.soap.Text;
/**
* Created by Michael Jan on 8/17/2015.
*/
public class GameIcon extends Sprite {
private int vX = 3;
private int vY = 3;
private int r = 9;
private int rotation;
private Vector3 position;
private Texture texture;
public GameIcon(int x, int y) {
position = new Vector3(x, y, 0);
texture = new Texture(Gdx.files.internal("icon_players/icon1.png"));
setTexture(texture);
}
public void update() {
position.add(vX, vY, 0);
rotation = rotation + r;
rotation = rotation % 360;
setRotation(rotation);
setOriginCenter();
}
public void addPosition(int x, int y) {
position.add(x, y, 0);
setOriginCenter();
}
public void negateVelocityX() {
vX = -vX;
}
public void negateRotation() {
r = -r;
}
public Vector3 getPosition() {
return position;
}
public int getvY() {
return vY;
}
public void setvY(int vY) {
this.vY = vY;
}
public int getvX() {
return vX;
}
public void setvX(int vX) {
this.vX = vX;
}
}
Here is the icon1.png:
https://i.gyazo.com/1d52f5e58b227f08809f6c14ae4c94a4.png
Here is what I am getting:
https://i.gyazo.com/1881a9392955af34de5c55b9b8fac391.png
Note that the rotation of the image and the particles are intended. The problem is that the big square should be the texture (icon1.png), and I do not know how to fix this.
(Not enough reputation to post pictures)
I'm not familiar with LibGDX, but this may have something to do with the fact that you are maybe overwriting TextureRegion.texture. Could you try to user your parent class Sprite(Texture) constructor like this:
...
public class GameIcon extends Sprite {
private int vX = 3;
private int vY = 3;
private int r = 9;
private int rotation;
private Vector3 position;
//private Texture texture;
public GameIcon(int x, int y) {
super(new Texture(Gdx.files.internal("icon_players/icon1.png")))
position = new Vector3(x, y, 0);
}
...
As stated by Tenfour04 in comments, this method works because the parent's constructor applies the width and height of the texture, while setTexture() does not.

How to appear and disappear an object on screen using game loop for every five second

I am trying to learn game development in android. First I am trying to appear and disappear an object on screen using game loop for every five second. But I did not get succeed. I have read different tutorials and forums. I applied all things as in tutorials but still object is drawing continuously. It is not disappearing. I a not getting what I am missing? Please guide me.
The complete code is here:
MainGameActivity.java
package com.example.showandhideobject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class MainGameActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new MainGamePanel(this));
}
}
MainGamePanel .java
package com.example.showandhideobject;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback {
private MainGameThread thread;
private ImageObject image;
// private long gameStartTime;
public MainGamePanel(Context context) {
super(context);
// adding the callback (this) to the surface holder to intercept events
getHolder().addCallback(this);
// create the game loop thread
thread = new MainGameThread(getHolder(), this);
Bitmap imageBitMap = BitmapFactory.decodeResource(getResources(),
R.drawable.rose);
image = new ImageObject(imageBitMap, 100, 150);
image.setAppeared(false);
image.setDisappearTime(System.currentTimeMillis());
// make the GamePanel focusable so it can handle events
setFocusable(true);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// at this point the surface is created and
// we can safely start the game loop
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void update() {
Log.i("Image Status::::::::::::: ",
Boolean.valueOf(image.isAppeared()).toString());
if (!image.isAppeared()
&& System.currentTimeMillis() - image.getDisappearTime() >= 5000) {
Log.i("Image Object::::::: ", "Showing");
image.setAppeared(true);
image.setAppearTime(System.currentTimeMillis());
}
if (image.isAppeared()
&& (System.currentTimeMillis() - image.getAppearTime() >= 5000)) {
Log.i("Image Object::::::: ", "Not Showing");
image.setAppeared(false);
image.setDisappearTime(System.currentTimeMillis());
}
}
public void render(Canvas canvas) {
if (image.isAppeared()) {
image.draw(canvas);
}
}
}
MainGameThread.java
package com.example.showandhideobject;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
public class MainGameThread extends Thread {
// Surface holder that can access the physical surface
private SurfaceHolder surfaceHolder;
// The actual view that handles inputs
// and draws to the surface
private MainGamePanel gamePanel;
// flag to hold game state
private boolean running;
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public MainGameThread(SurfaceHolder surfaceHolder, MainGamePanel gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
#Override
public void run() {
Canvas canvas;
while (isRunning()) {
canvas = null;
// try locking the canvas for exclusive pixel editing
// in the surface
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
Log.i("With in :::::::::", "Game Loop");
// update game state
gamePanel.update();
// render state to the screen and draw the canvas on the
// panel
gamePanel.render(canvas);
// gamePanel.onDraw(canvas);
}
} finally {
// in case of an exception the surface is not left in an
// inconsistent state
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
} // end finally
}
}
}
ImageObject.java
package com.example.showandhideobject;
import android.graphics.Bitmap;
import android.graphics.Canvas;
public class ImageObject {
private Bitmap bitmap; // the actual bitmap
private int x; // the X coordinate
private int y; // the Y coordinate
private boolean isAppeared;
private long appearTime;
private long disappearTime;
// Constructor for this class
public ImageObject(Bitmap bitmap, int x, int y) {
this.bitmap = bitmap;
this.x = x;
this.y = y;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public boolean isAppeared() {
return isAppeared;
}
public void setAppeared(boolean isAppeared) {
this.isAppeared = isAppeared;
}
public long getAppearTime() {
return appearTime;
}
public void setAppearTime(long appearTime) {
this.appearTime = appearTime;
}
public long getDisappearTime() {
return disappearTime;
}
public void setDisappearTime(long disappearTime) {
this.disappearTime = disappearTime;
}
/* Method to draw images on Canvas */
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2),
y - (bitmap.getHeight() / 2), null);
}
}
in this part
if (image.isAppeared()) {
image.draw(canvas);
}
you never clear your canvas. What you are doing is actually drawing your image over and over on the same spot.
You probably need to redraw a background in cas isAppeared() is false
Edit
you can also use canvas.save() before drawing the image, and canvas.restore() when you don't want the image anymore.
Don't try to optimise too early, game rendering is usually inefficient as almost always most of the screen is expected to change.
Loop should be:
always draw the background to canvas
always draw all game objects to the canvas, let them decide if they are visible or not which will simplify the MainGamePanel class
finally always display canvas (by copying to the image as you are doing)
To expand on point 2:
/* Method to draw images on Canvas */
public void draw(Canvas canvas) {
if(!isAppeared) return; //let the object decide when it should be drawn
canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2),
y - (bitmap.getHeight() / 2), null);
}
Change the method render in MainGamePanel.java to
if (image.isAppeared() && canvas != null) {
image.draw(canvas);
}

how to serialize an object of android.graphics.Path

I'm trying to store objects of Android.graphics.Path in internal device memory. Does anyone know how to serialize a android.graphics.Path object? And also, is there any other way of storing a Path object? Thanks.
The way I did it is to identify the methods that I needed from the original Path class and then simply override those methods as follows:
public class CustomPath extends Path implements Serializable {
private static final long serialVersionUID = -5974912367682897467L;
private ArrayList<PathAction> actions = new ArrayList<CustomPath.PathAction>();
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
in.defaultReadObject();
drawThisPath();
}
#Override
public void moveTo(float x, float y) {
actions.add(new ActionMove(x, y));
super.moveTo(x, y);
}
#Override
public void lineTo(float x, float y){
actions.add(new ActionLine(x, y));
super.lineTo(x, y);
}
private void drawThisPath(){
for(PathAction p : actions){
if(p.getType().equals(PathActionType.MOVE_TO)){
super.moveTo(p.getX(), p.getY());
} else if(p.getType().equals(PathActionType.LINE_TO)){
super.lineTo(p.getX(), p.getY());
}
}
}
public interface PathAction {
public enum PathActionType {LINE_TO,MOVE_TO};
public PathActionType getType();
public float getX();
public float getY();
}
public class ActionMove implements PathAction, Serializable{
private static final long serialVersionUID = -7198142191254133295L;
private float x,y;
public ActionMove(float x, float y){
this.x = x;
this.y = y;
}
#Override
public PathActionType getType() {
return PathActionType.MOVE_TO;
}
#Override
public float getX() {
return x;
}
#Override
public float getY() {
return y;
}
}
public class ActionLine implements PathAction, Serializable{
private static final long serialVersionUID = 8307137961494172589L;
private float x,y;
public ActionLine(float x, float y){
this.x = x;
this.y = y;
}
#Override
public PathActionType getType() {
return PathActionType.LINE_TO;
}
#Override
public float getX() {
return x;
}
#Override
public float getY() {
return y;
}
}
}
In my example I need "moveTo" and "lineTo", so in this case I simply hold the drawing information in a list. This list contains the drawing information (what I call "action") needed by Path in order to restore the drawing as it looked like before the object was serialized. Then when I deserialize my objects of type CustomPath i make sure to let the default serialization protocol call "drawThisPath", so the path is redrawn.
I've just managed to solve this. My application is based off the FingerPaintDemo, so makes use of just moveTo and quadTo, but I think you can apply this approach to any Path functions.
First, extend Path as follows:
import android.graphics.Path;
import java.util.ArrayList;
import java.io.Serializable;
public class SerializablePath extends Path implements Serializable {
private ArrayList<float[]> pathPoints;
public SerializablePath() {
super();
pathPoints = new ArrayList<float[]>();
}
public SerializablePath(SerializablePath p) {
super(p);
pathPoints = p.pathPoints;
}
public void addPathPoints(float[] points) {
this.pathPoints.add(points);
}
public void loadPathPointsAsQuadTo() {
float[] initPoints = pathPoints.remove(0);
this.moveTo(initPoints[0], initPoints[1]);
for (float[] pointSet : pathPoints) {
this.quadTo(pointSet[0], pointSet[1], pointSet[2], pointSet[3]);
}
}
}
I don't think I need to paste the implementation code, but if you want to see it let me know. Basically just as you call something like myPath.quadTo(x1, y1, x2, y2), also call myPath.addPathPoints(new float[]{x1, y1, x2, y2}).
Serialize the object to disk as normal, and when you read it back in, just be sure to call myPath.loadPathPointsAsQuadTo().
There is nothing so special for Path Class. Use can serialize any class that implements the Serializable interface..
Serializable interface is a Marker interface. i.e it dont have any method to implement. It just signify that the object can be deflatted to files/Memroies and later can be inflatted to be a live object again
What you do just make a class that extends your android.graphics.Path class and implements the Serializable interface. Then use this class instead of your android.graphics.Path. Then you will be able to apply serialization over it.
And check the following link for a detailed information
http://java.sun.com/developer/technicalArticles/Programming/serialization/
Hope this helps :)

Categories

Resources