4

Can you guys help me with my problem? My program is running with no problems on Android Studio Emulator (Pixel 2 API 28), but after I install it on my phone (Samsung Galaxy S8+ API 28), it just keep on crashing every time i tap the play button :(. I also tried it on some phones and I still have the same problem

Actually it isnt my program but i found it on youtube but the one who make the code in youtube gave me the green light to use it on my term project.

Link of the video on how to make that program in the youtube:

https://www.youtube.com/watch?v=5W3rVBDYFjE

This is the link of the source code you can run it:

https://github.com/heyletscode/2D-Game-In-Android-Studio

All I want is to run this code on a physical device especially on my phone Samsung Galaxy S8+. I can't seem to solve the issue I'm kind of desperate. I am very new to java programming i'm very sorry.

Code for com.heyletscode.ihavetofly.Flight class as requested by @Marc


int toShoot = 0;
boolean isGoingUp = false;
int x, y, width, height, wingCounter = 0, shootCounter = 1;
Bitmap flight1, flight2, shoot1, shoot2, shoot3, shoot4, shoot5, dead;
private GameView gameView;

Flight(GameView gameView, int screenY, Resources res) {

    this.gameView = gameView;

    flight1 = BitmapFactory.decodeResource(res, R.drawable.fly1);
    flight2 = BitmapFactory.decodeResource(res, R.drawable.fly2);

    width = flight1.getWidth();
    height = flight1.getHeight();

    width /= 4;
    height /= 4;

    width *= (int) screenRatioX;
    height *= (int) screenRatioY;

    flight1 = Bitmap.createScaledBitmap(flight1, width, height, false);
    flight2 = Bitmap.createScaledBitmap(flight2, width, height, false);

    shoot1 = BitmapFactory.decodeResource(res, R.drawable.shoot1);
    shoot2 = BitmapFactory.decodeResource(res, R.drawable.shoot2);
    shoot3 = BitmapFactory.decodeResource(res, R.drawable.shoot3);
    shoot4 = BitmapFactory.decodeResource(res, R.drawable.shoot4);
    shoot5 = BitmapFactory.decodeResource(res, R.drawable.shoot5);

    shoot1 = Bitmap.createScaledBitmap(shoot1, width, height, false);
    shoot2 = Bitmap.createScaledBitmap(shoot2, width, height, false);
    shoot3 = Bitmap.createScaledBitmap(shoot3, width, height, false);
    shoot4 = Bitmap.createScaledBitmap(shoot4, width, height, false);
    shoot5 = Bitmap.createScaledBitmap(shoot5, width, height, false);

    dead = BitmapFactory.decodeResource(res, R.drawable.dead);
    dead = Bitmap.createScaledBitmap(dead, width, height, false);

    y = screenY / 2;
    x = (int) (64 * screenRatioX);

}

Bitmap getFlight() {

    if (toShoot != 0) {

        if (shootCounter == 1) {
            shootCounter++;
            return shoot1;
        }

        if (shootCounter == 2) {
            shootCounter++;
            return shoot2;
        }

        if (shootCounter == 3) {
            shootCounter++;
            return shoot3;
        }

        if (shootCounter == 4) {
            shootCounter++;
            return shoot4;
        }

        shootCounter = 1;
        toShoot--;
        gameView.newBullet();

        return shoot5;
    }

    if (wingCounter == 0) {
        wingCounter++;
        return flight1;
    }
    wingCounter--;

    return flight2;
}

Rect getCollisionShape() {
    return new Rect(x, y, x + width, y + height);
}

Bitmap getDead() {
    return dead;
}

}

-----------EDITED------------


CODE FOR GameView.java

private Thread thread;
private boolean isPlaying, isGameOver = false;
private int screenX, screenY, score = 0;
public static float screenRatioX, screenRatioY;
private Paint paint;
private Bird[] birds;
private SharedPreferences prefs;
private Random random;
private SoundPool soundPool;
private List<Bullet> bullets;
private int sound;
private Flight flight;
private GameActivity activity;
private Background background1, background2;

public GameView(GameActivity activity, int screenX, int screenY) {
    super(activity);

    this.activity = activity;

    prefs = activity.getSharedPreferences("game", Context.MODE_PRIVATE);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_GAME)
                .build();

        soundPool = new SoundPool.Builder()
                .setAudioAttributes(audioAttributes)
                .build();

    } else
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

    sound = soundPool.load(activity, R.raw.shoot, 1);

    this.screenX = screenX;
    this.screenY = screenY;
    screenRatioX = 1920f / screenX;
    screenRatioY = 1080f / screenY;

    background1 = new Background(screenX, screenY, getResources());
    background2 = new Background(screenX, screenY, getResources());

    flight = new Flight(this, screenY, getResources());

    bullets = new ArrayList<>();

    background2.x = screenX;

    paint = new Paint();
    paint.setTextSize(128);
    paint.setColor(Color.WHITE);

    birds = new Bird[4];

    for (int i = 0;i < 4;i++) {

        Bird bird = new Bird(getResources());
        birds[i] = bird;

    }

    random = new Random();

}

@Override
public void run() {

    while (isPlaying) {

        update ();
        draw ();
        sleep ();

    }

}

private void update () {

    background1.x -= 10 * screenRatioX;
    background2.x -= 10 * screenRatioX;

    if (background1.x + background1.background.getWidth() < 0) {
        background1.x = screenX;
    }

    if (background2.x + background2.background.getWidth() < 0) {
        background2.x = screenX;
    }

    if (flight.isGoingUp)
        flight.y -= 30 * screenRatioY;
    else
        flight.y += 30 * screenRatioY;

    if (flight.y < 0)
        flight.y = 0;

    if (flight.y >= screenY - flight.height)
        flight.y = screenY - flight.height;

    List<Bullet> trash = new ArrayList<>();

    for (Bullet bullet : bullets) {

        if (bullet.x > screenX)
            trash.add(bullet);

        bullet.x += 50 * screenRatioX;

        for (Bird bird : birds) {

            if (Rect.intersects(bird.getCollisionShape(),
                    bullet.getCollisionShape())) {

                score++;
                bird.x = -500;
                bullet.x = screenX + 500;
                bird.wasShot = true;

            }

        }

    }

    for (Bullet bullet : trash)
        bullets.remove(bullet);

    for (Bird bird : birds) {

        bird.x -= bird.speed;

        if (bird.x + bird.width < 0) {

            if (!bird.wasShot) {
                isGameOver = true;
                return;
            }

            int bound = (int) (30 * screenRatioX);
            bird.speed = random.nextInt(bound);

            if (bird.speed < 10 * screenRatioX)
                bird.speed = (int) (10 * screenRatioX);

            bird.x = screenX;
            bird.y = random.nextInt(screenY - bird.height);

            bird.wasShot = false;
        }

        if (Rect.intersects(bird.getCollisionShape(), flight.getCollisionShape())) {

            isGameOver = true;
            return;
        }

    }

}

private void draw () {

    if (getHolder().getSurface().isValid()) {

        Canvas canvas = getHolder().lockCanvas();
        canvas.drawBitmap(background1.background, background1.x, background1.y, paint);
        canvas.drawBitmap(background2.background, background2.x, background2.y, paint);

        for (Bird bird : birds)
            canvas.drawBitmap(bird.getBird(), bird.x, bird.y, paint);

        canvas.drawText(score + "", screenX / 2f, 164, paint);

        if (isGameOver) {
            isPlaying = false;
            canvas.drawBitmap(flight.getDead(), flight.x, flight.y, paint);
            getHolder().unlockCanvasAndPost(canvas);
            saveIfHighScore();
            waitBeforeExiting ();
            return;
        }

        canvas.drawBitmap(flight.getFlight(), flight.x, flight.y, paint);

        for (Bullet bullet : bullets)
            canvas.drawBitmap(bullet.bullet, bullet.x, bullet.y, paint);

        getHolder().unlockCanvasAndPost(canvas);

    }

}

private void waitBeforeExiting() {

    try {
        Thread.sleep(3000);
        activity.startActivity(new Intent(activity, MainActivity.class));
        activity.finish();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

private void saveIfHighScore() {

    if (prefs.getInt("highscore", 0) < score) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("highscore", score);
        editor.apply();
    }

}

private void sleep () {
    try {
        Thread.sleep(17);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void resume () {

    isPlaying = true;
    thread = new Thread(this);
    thread.start();

}

public void pause () {

    try {
        isPlaying = false;
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

@Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (event.getX() < screenX / 2) {
                flight.isGoingUp = true;
            }
            break;
        case MotionEvent.ACTION_UP:
            flight.isGoingUp = false;
            if (event.getX() > screenX / 2)
                flight.toShoot++;
            break;
    }

    return true;
}

public void newBullet() {

    if (!prefs.getBoolean("isMute", false))
        soundPool.play(sound, 1, 1, 0, 0, 1);

    Bullet bullet = new Bullet(getResources());
    bullet.x = flight.x + flight.width;
    bullet.y = flight.y + (flight.height / 2);
    bullets.add(bullet);

}
}

This is the Logcat on Error tab after installing and tapping the play button on the program on my Samsung Galaxy S8+


2019-10-07 16:59:12.317 11879-11879/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-10-07 16:59:12.322 11879-11879/? E/Zygote: accessInfo : 1
2019-10-07 16:59:21.447 11879-11879/com.heyletscode.ihavetofly E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.heyletscode.ihavetofly, PID: 11879
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.heyletscode.ihavetofly/com.heyletscode.ihavetofly.GameActivity}: java.lang.IllegalArgumentException: width and height must be > 0
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3114)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
     Caused by: java.lang.IllegalArgumentException: width and height must be > 0
        at android.graphics.Bitmap.createBitmap(Bitmap.java:1074)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:1041)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:991)
        at android.graphics.Bitmap.createBitmap(Bitmap.java:912)
        at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:782)
        at com.heyletscode.ihavetofly.Flight.<init>(Flight.java:35)
        at com.heyletscode.ihavetofly.GameView.<init>(GameView.java:70)
        at com.heyletscode.ihavetofly.GameActivity.onCreate(GameActivity.java:22)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3094)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7050) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965) 
Community
  • 1
  • 1
  • post your code you have tried. – Jakir Hossain Oct 07 '19 at 09:06
  • post some code with logcat – Rasel Oct 07 '19 at 09:06
  • Have you tried this solution ? https://stackoverflow.com/questions/17605662/illegalargumentexception-width-and-height-must-be-0-while-loading-bitmap-from If yes then please post your code. – Vikas Oct 07 '19 at 09:13
  • public void dispatchMessage(@NonNull Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } } This is a partial part of a code in Handler.java There is so much "(@NonNull Message msg)" message in this code, all of them saying " 'android.annotation.NonNull' is not public in 'android.annotation'. Cannot be accessed from outside package " – SilverBullet16 Oct 07 '19 at 09:17
  • It is related to bitmap or an ImageView, have you tried this solution ? https://stackoverflow.com/questions/17605662/illegalargumentexception-width-and-height-must-be-0-while-loading-bitmap-from – Vikas Oct 07 '19 at 09:21
  • @Vikas I'll try it, I don't really know what are the exact errors in my program. Well the program is not actually mine but I get it from the youtube but he gave me the green light for me to use his program for my term project in school. https://www.youtube.com/watch?v=5W3rVBDYFjE&t=17s The link above is the program that I am talking about and it is on part 6 already. His code is working no problem in android studio PIXEL 2 API 28 emulator but I cant make it to work on any physical device. You can try the code guys if you can there is source code link in video's link description. – SilverBullet16 Oct 07 '19 at 09:21
  • add the code of at com.heyletscode.ihavetofly.Flight class in the original question. – Logemann Oct 07 '19 at 09:38
  • check if your image resource is okay? – Rasel Oct 07 '19 at 09:48
  • @Marc i just added the code as you say. package com.heyletscode.ihavetofly; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import static com.heyletscode.ihavetofly.GameView.screenRatioX; import static com.heyletscode.ihavetofly.GameView.screenRatioY; public class Flight { ------------------------------------------------------------------- The partial code above are the codes that are included before the first line of code (int toShoot = 0;) that I added in the original question – SilverBullet16 Oct 07 '19 at 09:55

1 Answers1

1

The actual problem is in GameView.java:64, where fixed screen height and width used instead of dynamic. This code runs smoothly on device with screen below or equal 1920x1080 px.

Will Cause problem when screen size goes more than that as the screenRatioX and screenRatioY comes < 1 which turn to o in Flight.java:32 by cast, which caused the exception as

width and height must be > 0

To Use Dynamic screen size, you can use this:

 Display display = getWindowManager().getDefaultDisplay();
 Point size = new Point();
 display.getSize(size);

Use size.x and size.y instead of 1920f and 1080f respectively. Thanks

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • I kinda getting that it is really the problem Mr. Asaduzzaman, where should I find the class/code to replace this? I put the GameView.java for your reference bro. I am just a beginner for java I'm really sorry – SilverBullet16 Oct 07 '19 at 10:51
  • Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); this.screenX = screenX; this.screenY = screenY; screenRatioX = size.x / screenX; screenRatioY = size.y / screenY; I tried putting this on GameView.java but it says "Cannot resolve method 'getWindowManager()' . It is on red font – SilverBullet16 Oct 07 '19 at 10:57
  • Use activity.getWindowManager().getDefaultDisplay(); :) – Md. Asaduzzaman Oct 07 '19 at 10:59
  • Mr. Asaduzzaman I don't really know how I can thank you. I don't know what will I do if not for you. Thank you very much God bless you! You really help me a lot :) Appreciate it. – SilverBullet16 Oct 07 '19 at 11:05
  • Welcome @KennethQuilantang and best of luck. – Md. Asaduzzaman Oct 07 '19 at 11:09