1

I am currently making a game which expands off of the tutorial found here: http://www.edu4java.com/en/androidgame/androidgame.html

I currently have a screen layout that looks like the following: http://postimg.org/image/ghib8fb87/

As you can see, the directional keypad and the difficulty radio buttons are outside of my custom view.

EDIT: Attempted to use SharedPreferences:

In my MainActivity I have functions for the onClick of the RadioButtons and Directional keypad (not yet created):

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    private AppPreferences _appPrefs;
    int hour = 0;
    int minute = 0;
    int second = 0;
    TextView TimeAliveCounter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        timer();
    }

    public void runEasy(View view){
        _appPrefs.saveSmsBody("1");

    }

    public void runMedium(View view){
        _appPrefs.saveSmsBody("2");
    }

    public void runHard(View view){
        _appPrefs.saveSmsBody("3");

    }

    private void timer() {

        int locMilSec = 0;
        int locSec = 0;
        int locMin = 0;
        int locHr = 0;
        DecimalFormat format = new DecimalFormat("00");
        String formatMilliSecond = format.format(locMilSec);
        String formatSecond = format.format(locSec);
        String formatMinute = format.format(locMin);
        String formatHour = format.format(locHr);

        millisecond = Integer.parseInt(formatMilliSecond);
        second = Integer.parseInt(formatSecond);
        minute = Integer.parseInt(formatMinute);
        hour = Integer.parseInt(formatHour);

        Timer T = new Timer();
        TimeAliveCounter = (TextView) findViewById(R.id.TimeAlive);
        T.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TimeAliveCounter.setText(hour + ":"+ minute + ":"+ second + ":" + millisecond);
                        second++;
                        if(second > 59){
                            second = 0;
                            minute = minute + 1;                          
                        }
                    }
                });
            }
        }, 1000, 1000);
    }
}

My AppPreferences Class:

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppPreferences {
    public static final String KEY_DIFFICULTY = "difficulty";
    private static final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); 
    private SharedPreferences _sharedPrefs;
    private Editor _prefsEditor;

    public AppPreferences(Context context) {
        this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
        this._prefsEditor = _sharedPrefs.edit();
    }

    public String getDifficulty() {
        return _sharedPrefs.getString(KEY_DIFFICULTY, "");
    }

    public void saveSmsBody(String text) {
        _prefsEditor.putString(KEY_DIFFICULTY, text);
        _prefsEditor.commit();
    }
}

My GameView class:

    import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GameView extends SurfaceView {
       private GameLoopThread gameLoopThread;
       private List<Sprite> sprites = new ArrayList<Sprite>();
       private List<tempSprite> temps = new ArrayList<tempSprite>();
       private long lastClick;
       private Bitmap bmpBlood;
       private AppPreferences _appPrefs;

       public GameView(Context context, AttributeSet attributeSet) {

             super(context);
             _appPrefs = new AppPreferences(context);
             final String difficulty = _appPrefs.getDifficulty();
             gameLoopThread = new GameLoopThread(this);
             getHolder().addCallback(new SurfaceHolder.Callback() {

                    @Override
                    public void surfaceDestroyed(SurfaceHolder holder) {
                           boolean retry = true;
                           gameLoopThread.setRunning(false);
                           while (retry) {
                                  try {
                                        gameLoopThread.join();
                                        retry = false;
                                  } catch (InterruptedException e) {}
                           }
                    }



                    @Override
                    public void surfaceCreated(SurfaceHolder holder) {
                        createSprites(difficulty);    
                        gameLoopThread.setRunning(true);
                        gameLoopThread.start();
                    }

                    @Override
                    public void surfaceChanged(SurfaceHolder holder, int format,
                                  int width, int height) {
                    }
             });
             bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.image);
       }

       private void createSprites(final String difficulty) {

           if ("1".equals(difficulty))  // easy
           {
               new Thread(new Runnable() {
                public void run() {
                    for (int z =0; z<20; z++ )
                    try
                        {
                        Thread.sleep(5000); 
                        sprites.add(createSprite(R.drawable.image));
                        z++;

                        }
                    catch(InterruptedException e)
                        {
                        e.printStackTrace();
                        }
                }
            }).start();
           }

           else if ("2".equals(difficulty)) // medium
           {
               new Thread(new Runnable() {
                public void run() {
                    for (int z =0; z<40; z++ )
                    try
                        {
                        Thread.sleep(3000); 
                        sprites.add(createSprite(R.drawable.image));
                        z++;

                        }
                    catch(InterruptedException e)
                        {
                        e.printStackTrace();
                        }
                }
            }).start();
           }

           else if ("3".equals(difficulty)) // hard" +

           {
               new Thread(new Runnable() {
                public void run() {
                    for (int z =0; z<60; z++ )
                    try
                        {
                        Thread.sleep(1000); 
                        sprites.add(createSprite(R.drawable.zombie_sprite1));
                        z++;

                        }
                    catch(InterruptedException e)
                        {
                        e.printStackTrace();
                        }
                }
            }).start();
           } 

           else {
                sprites.add(createSprite(R.drawable.zombie_sprite1));
                sprites.add(createSprite(R.drawable.zombie_sprite2));
                sprites.add(createSprite(R.drawable.zombie_sprite3));
                sprites.add(createSprite(R.drawable.zombie_sprite4));
                sprites.add(createSprite(R.drawable.zombie_sprite1));
                sprites.add(createSprite(R.drawable.zombie_sprite2));
                sprites.add(createSprite(R.drawable.zombie_sprite3));
                sprites.add(createSprite(R.drawable.zombie_sprite4));
                sprites.add(createSprite(R.drawable.zombie_sprite1));
                sprites.add(createSprite(R.drawable.zombie_sprite2));
                sprites.add(createSprite(R.drawable.zombie_sprite3));
                sprites.add(createSprite(R.drawable.zombie_sprite4));
           }
        }


       private Sprite createSprite(int resouce) {
             Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
             return new Sprite(this, bmp);
       }

       @Override
       protected void onDraw(Canvas canvas) {


           Resources res = getResources();
           Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.graveyard_background);


            canvas.drawBitmap(background, 0, 0, null);

             for (int i = temps.size() - 1; i >= 0; i--) {
                    temps.get(i).onDraw(canvas);
             }
             for (Sprite sprite : sprites) {
                    sprite.onDraw(canvas);
             }
       }



       @Override
       public boolean onTouchEvent(MotionEvent event) {
             /**if (System.currentTimeMillis() - lastClick > 300) {
                    lastClick = System.currentTimeMillis();
                    float x = event.getX();
                    float y = event.getY();
                    synchronized (getHolder()) {
                           for (int i = sprites.size() - 1; i >= 0; i--) {
                                  Sprite sprite = sprites.get(i);
                                  if (sprite.isCollision(x, y)) {
                                        sprites.remove(sprite);
                                        temps.add(new tempSprite(temps, this, x, y, bmpBlood));
                                        break;
                                  }
                           }
                    }
             }*/
             return true;
       }          
}

My GameLoopThread class:

    import android.graphics.Canvas;

public class GameLoopThread extends Thread {
       static final long FPS = 10;
       private GameView view;
       private boolean running = false;

       public GameLoopThread(GameView view) {
             this.view = view;
       }

       public void setRunning(boolean run) {
             running = run;
       }

       @Override
       public void run() {
             long ticksPS = 1000 / FPS;
             long startTime;
             long sleepTime;
             while (running) {
                    Canvas c = null;
                    startTime = System.currentTimeMillis();
                    try {
                           c = view.getHolder().lockCanvas();
                           synchronized (view.getHolder()) {
                                  view.onDraw(c);
                           }
                    } finally {
                           if (c != null) {
                                  view.getHolder().unlockCanvasAndPost(c);
                           }
                    }
                    sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
                    try {
                           if (sleepTime > 0)
                                  sleep(sleepTime);
                           else
                                  sleep(10);
                    } catch (Exception e) {}
             }
       }
}

I am currently trying to be able to get the radio buttons to change the difficulty of the game but currently on clicking the radio buttons it is crashing.

Bedimindtricks
  • 113
  • 1
  • 7

2 Answers2

1

(the code is dump from this question Android Shared Preferences)

create a class AppPreferences

public class AppPreferences {
     public static final String KEY_DIFFICULTY = "difficulty";
     private static final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); //  Name of the file -.xml
     private SharedPreferences _sharedPrefs;
     private Editor _prefsEditor;

     public AppPreferences(Context context) {
         this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
         this._prefsEditor = _sharedPrefs.edit();
     }

     public String getDifficulty() {
         return _sharedPrefs.getString(KEY_DIFFICULTY, "");
     }

     public void saveDifficulty(String text) {
         _prefsEditor.putString(KEY_DIFFICULTY, text);
         _prefsEditor.commit();
     }
}

define a member in your class

private AppPreferences _appPrefs;

to get it in your onCreate do so

public GameView(Context context, AttributeSet attributeSet) {
    super(context);
    _appPrefs = new AppPreferences(getApplicationContext());
    String difficulty = _appPrefs.getDifficulty();

and to set it when you choose it do

_appPrefs.saveDifficulty("1"); //or "2" or "3"
Community
  • 1
  • 1
mihail
  • 2,173
  • 19
  • 31
  • Thanks so much for your quick response. Seems like I still have not got it - can you have a quick look at my new code? – Bedimindtricks Nov 14 '13 at 09:41
  • _appPrefs = new AppPreferences(getApplicationContext()); is not being recognized - my new code is edited from first post. If you have a minute to take a look it would be much appreciated! – Bedimindtricks Nov 14 '13 at 09:55
  • define _appPrefs as class member - inside the class and outside the onCreate method – mihail Nov 14 '13 at 10:05
  • like you have defined it in your main activity – mihail Nov 14 '13 at 10:06
  • I believe I have done that already have I not? Updated code can be seen in initial post. – Bedimindtricks Nov 14 '13 at 10:09
  • I don't see where you have defined tha _appPrefs variable in your GameView class - you can define it in the GameView class as member, or if you don't need it, you can create new instance - `AppPreferences _appPrefs = new AppPreferences(getApplicationContext());` – mihail Nov 14 '13 at 10:12
  • In my GameView I have defined it using: private AppPreferences _appPrefs; but this does not seem to remedy the issue. The getApplicationContext() is undefined for type GameView – Bedimindtricks Nov 14 '13 at 10:15
  • instead of `getApplicationContext()` use `context` – mihail Nov 14 '13 at 10:20
  • Check the last block of code in first post. So sorry to keep bothering you but now it does not recognize the variable difficulty within my Sprites Creation method – Bedimindtricks Nov 14 '13 at 10:25
  • can you post the whole classes, it's hard to guess where and how variables are defined – mihail Nov 14 '13 at 10:26
  • first thing - you don't need the static `difficulty` variable, you can remove it (also from the runEasy/medium/hard methods) **side note**: you don't see it because you are trying to access static variable from a non-static method. Next, in the GameView, you are comparing strings with the `==` operator which is plain wrong. Use `if("1".equals(difficulty))` and so on instead. – mihail Nov 14 '13 at 10:40
  • Sorry about that, had actually removed that when I changed it initially but I removed edits back too far and copy/pasted the wrong edit. The comparator for strings I had completely forgot about - I am really new to program so please excuse my mistake with this. After changing those values it is still crashing with no error on console output upon click of radio buttons – Bedimindtricks Nov 14 '13 at 10:47
  • GameView failed to instantiate. java.lang.NullPointerException at killthemall.AppPreferences.(AppPreferences.java:16) at killthemall.GameView.(GameView.java:29) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) – Bedimindtricks Nov 14 '13 at 11:08
  • in your `GameView` replace `_appPrefs = new AppPreferences(getContext());` with `_appPrefs = new AppPreferences(context);`. – mihail Nov 14 '13 at 11:25
  • also, don't create new instance in the `createSprites`, it is already created in the `onCreate` – mihail Nov 14 '13 at 11:27
  • Without the new instance in createSprites it does not recognize the difficulty variable – Bedimindtricks Nov 14 '13 at 11:35
  • how it does not recognize it?? Is it empty when you debug it? – mihail Nov 14 '13 at 11:45
  • else if ("2".equals(difficulty)) - difficulty cannot be resolved to a variable. – Bedimindtricks Nov 14 '13 at 11:47
  • and what about if ("1".equals(difficulty)) ?? is it Ok? – mihail Nov 14 '13 at 11:52
  • No, all three of them are the same, I only copy/pasted one as an example. – Bedimindtricks Nov 14 '13 at 11:53
  • can you edit your post with the current state of the GameView. I don't understand what are you doing... – mihail Nov 14 '13 at 11:58
  • ok, in onCreate make it like this `final String difficulty = _appPrefs.getDifficulty();` , add a parameter to the createSprites function - `private void createSprites(final String difficulty)` and call it like this `createSprites(difficulty)` – mihail Nov 14 '13 at 12:08
  • Updated. On compile it runs with the else statement for difficulty level. On click of radio button it crashes with no error message in console. on main.xml -> Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse java.lang.NullPointerException at killthemall.AppPreferences.(AppPreferences.java:18) at killthemall.GameView.(GameView.java:28) – Bedimindtricks Nov 14 '13 at 12:15
  • this is some other error, I really don't have the time to be with you through the whole tutorial. You are still learning so be prepared to research what these error messages mean. I think I answered to the question of this topic, so I wish you good luck and have a nice day – mihail Nov 14 '13 at 12:17
  • yes it is an unrelated issue, but it does not affect that when I click the radio buttons now with sharedpreferences it still is just crashing and there is no error output.. sorry not sure what to do. Thanks for all your help, ill try reading around. – Bedimindtricks Nov 14 '13 at 12:36
  • Have not been able to figure this out as of yet. If you see anything obvious in my code I would be much appreciated. Thanks. – Bedimindtricks Nov 15 '13 at 07:17
  • I assume that the problem is you are trying to use OnClickListener on RadioButton. Better try with OnCheckedChangeListener. Make sure your RadioButtons are in a RadioGroup - Follow this link http://stackoverflow.com/questions/8323778/how-to-set-on-click-listener-on-the-radio-button-in-android – mihail Nov 15 '13 at 07:23
  • It isn't that because I have tried it with buttons somehow: The following classes could not be instantiated: - jordan.bedi.killthemall.GameView (Open Class, Show Error Log) See the Error Log (Window > Show View) for more details. Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse java.lang.NullPointerException at killthemall.AppPreferences.(AppPreferences.java:16) at killthemall.GameView.(GameView.java:27) at sun.reflect.NativeConstructorAccessorImpl.newInstance0( at – Bedimindtricks Nov 15 '13 at 10:07
  • This is shown when I simply open my main_activity.xml file. On clicking the buttons (or radio buttons) it crashes. – Bedimindtricks Nov 15 '13 at 10:10
  • Was not able to get this working. Anyone have any other ideas? Thanks in advanced! – Bedimindtricks Nov 17 '13 at 08:45
0

Solved this issue using simple static setter and getter methods which I would call and modify.

Bedimindtricks
  • 113
  • 1
  • 7