Get score value from serializable class to activity - android

I am developing a game in which I've a serializable class that has a score parameter and it is set to 0 initially.
Now what I want that when the score is greater than 1 then the score value is passed to my main activity and some toast is shown in the main activity
This is my code for serializable class:
public class Game implements Serializable{
private static final long serialVersionUID = 8326065952389292265L;
private int score = 0;
Here is my score increase and when it is greater than 1 then the score value should be passed to main activity
if(bird.GetX()+bW > px1 && bird.GetX() < px2)
{
if(birdY1>=minY && birdY2<=maxY)
{
}
else
{
if(!boom)
SoundManager.playSound(5, 1);
boom = true;
bird.SetState(0);
}
score = (i+1);
if (score>1)
{
}
}
I am confused how to send this score value to my main activity and then how to get it in main activity. Can anyone help me some little code that how it is done? Any help will be appreciated
Here is my MainActivity code:
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private SurfaceView mainGameView;
static Bitmap bitmap;
static Canvas canvas;
private GameLogic gameLogic;
private Game gamescore;
private ArrayList<String> wordsDictionary;
private Context context;
private MyTask mt;
private boolean dictionaryLoaded;
private ImageView image;
private Activity activity;
Intent playbackServiceIntent;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
SoundManager.getInstance();
SoundManager.initSounds(this);
SoundManager.loadSounds();
SoundManager.playSound(1, 1);
if(true)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
else
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
context = this;
gameLogic = new GameLogic(context, getResources());
dictionaryLoaded = false;
SharedPreferences sPref = getPreferences(MODE_PRIVATE);
String data1 = sPref.getString("data1", "");
mainGameView = new MainGameView(this, gameLogic);
final RelativeLayout layout = new RelativeLayout(context);
layout.addView(mainGameView);
Runnable runnable = new Runnable() {
#Override
public void run() {
}
};
new Thread(runnable).start();
if(true)
{
setContentView(layout);
}
}

public static void setScore(int s) {
score=s;
}
public static int getScore()
{
return score;
}
Now you can use as in your main Activity :
int scr=Game.getScore();
above code will return the score

Create one interface
public interface GameScoreListener{
void onScoreIncrease(int incrementBy);
void onScoreDecrease(int decrementBy)
}
Implement GameScoreListener in MainActivity.
Create GameScoreListener setter and getter in the class where you're changing score. When Score change in any method check GameScoreListener for NPE, then make callback from GameScoreListener.

Related

Appcompatactivity onCreate() not getting triggered when instantiating a class

I am still learning Android development and I am stuck at a point where I assume I am doing something wrong. Would appreciate your help.
I have my main class that extends AppCompatActivity like this, and inside it, I have a function that instantiates another class where I want to do some calculations based on the store sharedpreferences:
public class Level1_0 extends AppCompatActivity {
.....
public void isTwoUnlocked(){
CalculateAvg calc = new CalculateAvg();
boolean L = calc.level2();
if(L == true){
showPopup();
calc.finish();
}
}
.....
}
CalculateAvg is the class I am instantiating. That class has a method called level2(), this is where I do some checks and return True or False as boolean. When I run the code, init() never gets called by onCreate(). I also tried writing the entire code of init inside onCreate itself, still same problem, onCreate never gets triggered.
CalculateAvg class
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class CalculateAvg extends AppCompatActivity{
public static final String SHARED_PREFS = "sharedPrefs";
private static final String TAG = "Level1_0";
level10 = sharedPreferences.getBoolean(LEVEL10, false);
........
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
public void init(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
........
// do my calculations here but init() never gets called by onCreate().
// I even tried writing entire code inside onCreate but it also didn't work
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}
Any idea why onCreate is not getting triggered when I instantiate it in my main class?
According your requirements there is no need to use AppCompatActivity. You can simply use like class and pass context to access SharedPreferences.
public class CalculateAvg {
private Context mContext;
....
public CalculateAvg(Context context) {
mContext = context;
init();
}
public void init(){
SharedPreferences sharedPreferences = mContext.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
....
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}
And instantiate CalculateAvg with your activity's context like below:
CalculateAvg calc = new CalculateAvg(Level1_0.this);
This Android not a java you can not call activity with creating new instance to call CalculateAvg from Level1_0 do below code in Level1_0 onCreate().
public class Level1_0 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =new Intent(this,CalculateAvg.class);
startActivity(intent);
}
}

How to correctly implement android Lifecycle with the architecture component

I'm new to architecture component, I have created a ViewModel class and implemented LifecycleObserver as per the architecture component, inside the ViewModel class i have a overriden run() method of runnable interface and call it recursively with delay by the help of handler class, inside this value images array changes and wrapped by the live data.
MainActivity observe the changes of the images array and as the value changes, ImageView binds the value of images array.Main activity is also the lifecycle owner.
Now i want to implement Lifecycle observer, so that when i pause my application run() method should also pause and when i resume the application it start from where i pause.
I tried it by creating pause and resume method in the handler, but it didn't work.
Help me with this.
MainActivity Class
private ImageViewModel imageViewModel;
private ImageView imageView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialogueBox();
}
private void showDialogueBox() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialogue_box);
dialog.setTitle("custom");
Button button =(Button)dialog.findViewById(R.id.button1);
button.setEnabled(true);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageViewModel = ViewModelProviders.of(MainActivity.this).get(ImageViewModel.class);
subscribe();
dialog.cancel();
}
});
dialog.show();
}
private void subscribe() {
final Observer<Integer> imageTimeObserver = new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
imageView = findViewById(R.id.imageView);
imageView.setImageResource(integer);
getLifecycle().addObserver(new BrainalyseComponent(MainActivity.this,getApplicationContext(),imageViewModel));
}
};
final Observer<Integer> progressbarTimeObserver = new Observer<Integer>() {
#Override
public void onChanged(#Nullable Integer integer) {
progressBar = findViewById(R.id.progressBar);
progressBar.setProgress(integer);
}
};
imageViewModel.getImage().observe(this,imageTimeObserver);
imageViewModel.getProgressbarStatus().observe(this,progressbarTimeObserver);
}
ViewModel class
private int imagesIndex;
private int delay;
public Handler handler;
private MutableLiveData<Integer> imageLiveData = new MutableLiveData<>();
private MutableLiveData<Integer> progressbarLiveData = new MutableLiveData<>();
private int progressBarStatus;
private HashMap<Integer,Integer> imagesAndDelay;
private int images[] =
{
R.drawable.food_1,
R.drawable.food_2,
R.drawable.food_3,
R.drawable.food_4,
R.drawable.food_5,
R.drawable.food_6,
R.drawable.food_7,
R.drawable.food_8,
R.drawable.food_9,
R.drawable.food_10
};
public ImageViewModel(){
imagesIndex = 0;
progressBarStatus = 0;
delay = 2;//to be changed as delay will be discussed
handler = new Handler();
imagesAndDelay = new HashMap<>();
shuffleImages();
runnable.run();
}
private void shuffleImages() {
Random random = new Random();
for (int i = 0; i < images.length; i++) {
int j = random.nextInt(images.length);
int temp = images[i];
images[i] = images[j];
images[j] = temp;
}
}
public Runnable runnable = new Runnable() {
#Override
public void run() {
if (imagesIndex<images.length){
progressBarStatus += 100/images.length;
progressbarLiveData.postValue(progressBarStatus);
imageLiveData.postValue(images[imagesIndex]);
imagesAndDelay.put(images[imagesIndex],delay);
imagesIndex++;
delay += 2;
}else {
stopTask();
return;
}
handler.postDelayed(runnable,2000);
}
};
public Thread newThread = new Thread(){
public void run(){
if (imagesIndex<images.length){
progressBarStatus += 100/images.length;
progressbarLiveData.postValue(progressBarStatus);
imageLiveData.postValue(images[imagesIndex]);
imagesAndDelay.put(images[imagesIndex],delay);
imagesIndex++;
delay += 2;
}else {
stopTask();
return;
}
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
run();
}
}
};
public LiveData<Integer> getImage(){
return imageLiveData;
}
public LiveData<Integer> getProgressbarStatus(){
return progressbarLiveData;
}
private void stopTask() {
delay = 2;
progressBarStatus = 0;
imagesIndex = 0;
Utility.setImagesAndDelay(imagesAndDelay);
handler.removeCallbacks(runnable);
}
LifecycleObsever
private Context mContext;
private static final String LOG_TAG = BrainalyseComponent.class.getSimpleName();
private ImageView imageView;
private ProgressBar progressBar;
private Integer integer;
LifecycleOwner lifecycleOwner;
private ImageViewModel imageViewModel;
public BrainalyseComponent(LifecycleOwner lifecycleOwner, Context context, ImageViewModel imageViewModel) {
this.mContext = context;
this.imageView = imageView;
this.imageViewModel = imageViewModel;
this.integer = integer;
this.progressBar = progressBar;
this.lifecycleOwner = lifecycleOwner;
}
#OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(){
Log.d(LOG_TAG,"on resume of app");
}
#OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){
}
You're missing listener and you'll need to remove it at some point (from onDestroy for example)
public BrainalyseComponent(LifecycleOwner lifecycleOwner, Context context, ImageViewModel imageViewModel) {
this.mContext = context;
this.imageView = imageView;
this.imageViewModel = imageViewModel;
this.integer = integer;
this.progressBar = progressBar;
this.lifecycleOwner = lifecycleOwner;
lifecycleOwner.getLifecycle().addObserver(this);
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(){
lifecycleOwner.getLifecycle().removeObserver(this);
}

Sharing data between an activity and a class

I have an activity MyActivity that holds a service class MyService.
I would like the service to send String data to the activity, and then create a button using this data.
Following this post I created a static method in the activity.
The problem of course is that i can't use this in a static context.
public class MyActivity extends Activity {
private MyService myService;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
myService = new MyService();
}
public static void connectMethod (String buttonName) {
Button btn = new Button(this); // error
btn.setId(i);
final int buttonID = btn.getId();
btn.setText(buttonName + buttonID);
}
}
public class MyService {
...
private void showButton (String data) {
MyActivity.connectedMethod(data);
}
}
Two possible solutions to avoid your error:
public static void connectMethod (Context context, String buttonName) {
Button btn = new Button(context);
btn.setId(i);
final int buttonID = btn.getId();
btn.setText(buttonName + buttonID);
}
// ...
public class MyService {
private Context context;
public MyService(Context context) {
this.context = context;
}
...
private void showButton (String data) {
MyActivity.connectedMethod(context, data);
}
}
Or create a static class field : private static Context context;
public static void connectMethod (String buttonName) {
Button btn = new Button(context);
btn.setId(i);
final int buttonID = btn.getId();
btn.setText(buttonName + buttonID);
}

Object-oriented-ness got out of control (plus maybe some threading problems)

I don't have much experience with building well-designed object oriented systems, and this time I improvised, which lead to the system not working and not giving me any errors.
Basically in my android app, I have a user profile activity that calls a class that queries the remote database using the user ID, and returns values for user avatar and user name.
Until the class was nested inside the profile activity class it was alright, but I decided to move it out of there and change some other stuff and now when I go to My profile I do not see my avatar and I do not see my user name.
Here is the GetUserData class:
public class GetUserData extends Activity {
private String currentlyLoggedInUserString;
SharedPreferences sharedPrefs;
Editor editor;
int currentlyLoggedInUser;
private JSONParser jsonParser = new JSONParser();
private Configurationz configurationz = new Configurationz();
private ToastMaker toastMaker = new ToastMaker();
private static final String TAG_SUCCESS = "success";
private static final String TAG_USER_AVATAR = "user_avatar";
private static final String TAG_USER_NAME = "user_name";
private static final String TAG_USER_EMAIL = "user_email";
private static final String TAG_USER_SEX = "user_sex";
private static final String TAG_USER_DATE_REGISTERED = "user_date_registered";
private static final String TAG_USER_LAST_SEEN = "user_last_seen";
private static final String TAG_USER_PASSWORD = "user_password";
private static final String APP_SHARED_PREFS = "asdasd_preferences";
private String userName;
private String userEmail;
private String userSex;
private String userPassword;
private String userAvatar;
private String userDateRegistered;
private String userLastSeen;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserAvatar() {
return userAvatar;
}
public void setUserAvatar(String userAvatar) {
this.userAvatar = userAvatar;
}
public String getUserDateRegistered() {
return userDateRegistered;
}
public void setUserDateRegistered(String userDateRegistered) {
this.userDateRegistered = userDateRegistered;
}
public String getUserLastSeen() {
return userLastSeen;
}
public void setUserLastSeen(String userLastSeen) {
this.userLastSeen = userLastSeen;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getApplicationContext().getSharedPreferences(APP_SHARED_PREFS, Context.MODE_PRIVATE);
new GetUserDataGetter().execute();
}
public class GetUserDataGetter extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
int success;
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
// fix these shitty variables.
currentlyLoggedInUser = sharedPrefs.getInt("currentLoggedInUserId", 0);
currentlyLoggedInUserString = Integer.toString(currentlyLoggedInUser);
parameters.add(new BasicNameValuePair("user_id", currentlyLoggedInUserString));
final JSONObject json = jsonParser.makeHttpRequest(configurationz.URL_PHP_GET_USER_DATA, "POST", parameters);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// user data found
setUserLastSeen(json.getString(TAG_USER_LAST_SEEN));
setUserDateRegistered(json.getString(TAG_USER_DATE_REGISTERED));
setUserAvatar(json.getString(TAG_USER_AVATAR));
setUserSex(json.getString(TAG_USER_SEX));
setUserPassword(json.getString(TAG_USER_PASSWORD));
setUserEmail(json.getString(TAG_USER_EMAIL));
setUserName(json.getString(TAG_USER_NAME));
//return json.getString(TAG_USER_AVATAR);
return null;
} else if (success == 2) {
//toast about not being able to connect to db;
runOnUiThread(new Runnable() {
public void run() {
//this might cause some SHIT!!!!!!!!!!!! TEST IT!!!
toastMaker.toast(getBaseContext(), configurationz.ERROR_MESSAGES_SIGNUP_DEVICE_UNABLE_TO_TAKE_PHOTOS, configurationz, Toast.LENGTH_LONG);
}
});
setUserLastSeen("");
setUserDateRegistered("");
setUserAvatar("");
setUserSex("");
setUserPassword("");
setUserEmail("");
setUserName("");
return null;
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
and here is the MyProfile class:
public class MyProfile extends ActionBarAndSlidingMenu {
private TableRow myProfileActionButtonsHolder;
private TextView tvUserName;
private ImageButton iUserAvatar;
private Bitmap iUserAvatarBitmap;
private String avatarPath;
private String userName;
private static final String APP_SHARED_PREFS = "asdasd_preferences";
SharedPreferences sharedPrefs;
Editor editor;
int currentlyLoggedInUser;
boolean userLoggedInState = false;
private GetUserData getUserData = new GetUserData();
public MyProfile() {
super(R.string.app_name);
}
// do a check here whether this is the user themselves or some other user
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getApplicationContext().getSharedPreferences(APP_SHARED_PREFS, Context.MODE_PRIVATE);
setContentView(R.layout.user_profile);
// check whether user is logged in, otherwise redirect them to
// login/signup page
userLoggedInState = sharedPrefs.getBoolean("userLoggedInState", false);
if (!userLoggedInState) {
// start intent to get them out of here.
// Research whether this step is necessary at all
}
// define the view components
myProfileActionButtonsHolder = (TableRow) findViewById(R.id.userProfileActionButtonsHolder);
// set avatar image
iUserAvatar = (ImageButton) findViewById(R.id.iUserAvatar);
avatarPath = getUserData.getUserAvatar();
if (avatarPath != "") {
iUserAvatarBitmap = BitmapFactory.decodeFile(avatarPath);
iUserAvatar.setImageBitmap(iUserAvatarBitmap);
} else {
iUserAvatar.setImageResource(R.drawable.avatar_default_male);
}
//set user display name
userName = getUserData.getUserName();
tvUserName = (TextView) findViewById(R.id.tvUserName);
tvUserName.setText(userName);
// create action buttons fragment with "edit" and "settings" buttons
getSupportFragmentManager().beginTransaction().replace(R.id.userProfileActionButtonsHolder, new MyProfileActionButtonsFragment()).commit();
}
}
First, you need to read up on programming in general and proper coding guidelines in particular, as this is a bit of a chaos. As soon as your project becomes more complex, this gets unreadable and undebuggable. Second, you should read up on how Android works.
Here's your problem in a nutshell:
An Activity is not just Android's own version of a class and you can't use it as such. An Activity represents a screen that is displayed to the user. No screen to display? No Activity.
Thus, your getUserData Activity should be a regular class and not extend activity.
Now, in MyProfile you just declare a member variable with
private GetUserData getUserData = new GetUserData();
This does nothing and it certainly never runs that class' onCreate. Thus, your task is never executed and all your fields return null.
Here's what to do in a nutshell:
Create a class UserDetails that has a constructor that takes the username, etc. plus the getters necessary to get these details. Add nothing else. This is what we call Java's version of a value object.
public class UserDetails {
private final String mUsername;
public UserDetails(String username) {
mUsername = username;
}
public String getUsername() {
return mUsername;
}
}
Create an interface called IOnUserDetailsReceivedListener with the method onUserDetailsReceived(UserDetails userDetails). The reason for this is that your download task will take some time. You need to get informed when it's done and that's what we use this interface for. This is called a listener pattern.
public interface IOnUserDetailsReceivedListener {
public void onUserDetailsReceived(UserDetails userDetails);
public void onUserDetailsError();
}
Create a class Downloader that contains your AsyncTask and that has a method retrieveUserDetails(); or something. In that method, run the async task to download. When you get the data from the server, fill it into a new UserDetails(...) object and then call listener.onUserDetailsReceived(userDetails).
public class UserDetailsDownloader {
private IOnUserDetailsReceivedListener mListener;
public UserDetailsDownloader(IOnUserDetailsReceivedListener listener) {
mListener = listener;
}
public void downloadUserDetails() {
//Execute the async task here. In it's onPostExecute, do mListener.onUserDetailsReceived(userDetails).
}
private class DownloaderTask extends AsyncTask<String, Integer, UserDetails> {
#Override
protected UserDetails doInBackground(String... params) {
//Download code
//In downloading there might go stuff wrong. If so, return null as an easy method without any error handling.
UserDetails userDetails = new UserDetails("downloadedUsername");
return userDetails;
}
#Override
protected void onPostExecute(UserDetails userDetails) {
if(userDetails == null) {
if(mListener != null) {
//Something went wrong. Tell the listener.
mListener.onUserDetailsError();
}
} else {
if(mListener != null) {
//Cool! Lets pass the userDetails to the activity.
mListener.onUserDetailsReceiver(userDetails);
}
}
}
}
}
Let your activity implements IOnUserDetailsReceivedListener.
public void UserActivity extends Activity implements IOnUserDetailsReceivedListener {
private UserDetailsDownloader mUserDetailsDownloader;
public void onCreate(...) {
mUserDetailsDownloader = new UserDetailsDownloader(this);
mUserDetailsDownloader.downloadUserDetails();
}
public void onUserDetailsReceived(UserDetails userDetails) {
//Yeeh we received user data.
}
public void onUserDetailsError() {
//Something went wrong. Tell the user?
}
}
When your task is done, it'll call your Activities onUserDetailsReceived method and pass you the UserDetails value object with which you can then do what you want.
I don't know if this is your only problem or not but too much for a comment. You shouldn't use runOnUiThread() in doInBackground()
runOnUiThread(new Runnable() {
public void run() {
//this might cause some SHIT!!!!!!!!!!!! TEST IT!!!
toastMaker.toast(getBaseContext(), configurationz.ERROR_MESSAGES_SIGNUP_DEVICE_UNABLE_TO_TAKE_PHOTOS, configurationz, Toast.LENGTH_LONG);
}
});
this is why AsyncTask has onPostExecute() and its other methods...they all run on the UI Thread except for doInBackground()
Instead of return null, returnsuccessand depending on that value, do what you need to inonPostExecute()`.
Edit
onPostExecute() gets its parameter from what doInBackground() returns which is the third param in your declaration public class GetUserDataGetter extends AsyncTask<String, String, String>. So you can change that param or return a String to onPostExecute() from doInBackground().
AsyncTask Docs

Passing of values from a class extending in Activity to class extending in SurfaceView

I want to pass some values from my Game extends Activity to Screen extends SurfaceView using getters, but I always got 0 and I don't know what's happening.
This is my code for Game class:
public class Game extends Activity{
Screen screen;
Map map;
int mouseEvent;
private int mouseX;
private int mouseY;
private Bundle extra;
private int tileRows;
private int tileColumns;
private int minBlocks;
private int maxBlocks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
extra = getIntent().getExtras();
tileRows = extra.getInt("numRow");
tileColumns = extra.getInt("numColumn");
minBlocks = extra.getInt("numMinBlock");
maxBlocks = extra.getInt("numMaxBlock");
setContentView(R.layout.game);
}
public boolean onTouchEvent(MotionEvent event){
mouseEvent = event.getAction();
mouseX = (int) event.getX();
mouseY = (int) event.getY();
return super.onTouchEvent(event);
}
public int getMouseX() {
return mouseX;
}
public int getMouseY() {
return mouseY;
}
public int getTileRows() {
return tileRows;
}
public int getTileColumns() {
return tileColumns;
}
public int getMinBlocks() {
return minBlocks;
}
public int getMaxBlocks() {
return maxBlocks;
}
public void setMouseX(int mouseX) {
this.mouseX = mouseX;
}
public void setMouseY(int mouseY) {
this.mouseY = mouseY;
}
}
And this is my code for Screen class:
public class Screen extends SurfaceView implements Callback
{
private Map map;
private SurfaceHolder holder;
private GameThread gamethread;
private Penguin penguin;
private boolean isSurfaceCreated;
private Bitmap tiles, character;
private int tileRows, tileColumns, minBlocks, maxBlocks;
public Screen(Context context, AttributeSet attb) {
super(context, attb);
tiles = BitmapFactory.decodeResource(getResources(), R.drawable.tile_sprites);
character = BitmapFactory.decodeResource(getResources(), R.drawable.penguin_sprite);
this.getHolder().addCallback(this);
this.tileRows = new Game().getTileRows();
this.tileColumns = new Game().getTileColumns();
this.minBlocks = new Game().getMinBlocks();
this.maxBlocks = new Game().getMaxBlocks();
}
}
Your help will be deeply appreciated :)
Activity classes aren't supposed to be instantiated by your code; they are created/re-used as needed when you use Intents. When you create a new Game(), there's no intent associated with that and thus the getExtras calls in its constructor don't find the integers you're looking for--thus everything coming up as 0.
If you know Screen objects are only used by the Game activity, you could cast your context to Game and then call the getters directly.

Categories

Resources