I have been trying to find a way to set variables for one class while in another class withous changing intents. Maybe I'm searching the wrong things, maybe I'm over complicating this, I don't know.
Basically, what I am doing at the moment is getting the listView item that is selected, checking its index value, and chaning a variable or two(from a different class) based on the choice.
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
theGame settings = null;
switch(position){
case 0:
settings.baseWave = 10;
settings.baseRate = 5;
break;
case 1:
settings.baseWave = 20;
settings.baseRate = 10;
break;
case 2:
settings.baseWave = 30;
settings.baseRate = 15;
break;
}
}
"theGame" is my outside class and "baseWave" and "baseRate" are the corrisponding varriables. Obviously, what I am doing here is not working for me. Im fairly new at all of this so be gentle.
Thank you for any help you can offer, it is much appreciated :)
~TG
It's nice that it struck you that you may have a bad design, but it should also have struck you that you don't know Java, that you're having this problem because you don't know Java, and that a good Java book would help you.
Well, this is the shortest path to getting this attempt of yours working: have theGame store a reference to itself in a static member; use the static member in your code.
That is,
class TheGame {
public static TheGame theGame = null;
TheGame() {
theGame = this;
}
}
And elsewhere: TheGame.theGame.baseWave = 10 * (position + 1);
Or you may need it put this way:
public class TheGame extends Activity {
public static TheGame theGame = null;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
theGame = this;
}
}
A good Java book would describe this sort of thing to you, give you a name for it, and warn you away from it.
Related
in java i know this code is a good programming practice,
but i read some article there are good programming practice that
is bad for Android, i just want to know if this type of code
can affect the Aplication Performance issue when it comes to android programing?
for example
public class Main {
static int age = getAge(10); /***************** THIS LINE */
public static void main(String[] args) {
System.out.println(age);
}
private static int getAge(int i) { /***************** THIS METHOD */
i = i + 1;
return i;
}
}
This situation seems perfectly fine and wouldn't effect performance.
I personally would be careful with this practice though, you could potentially call a method dependant on variables that are yet to be initialized.
public class Main {
static int age = getDogYears(10);
int dogRatio; // dogRatio is not yet initialized
public static void main(String[] args) {
System.out.println(age);
dogRatio = 7;
}
private static int getDogyears(int i) {
i = i * dogRatio; // null pointer exception because dogRatio is not initialized
return i;
}
}
If the problem is really this simple though I would also ask why you wouldn't just make age = 11;
You're not going to see any noticeable performance hits, and I can't see anything wrong with the code, but it could be improved.
This method is a lot easier to read and cleans up the code a little:
private static int getAge(int i){
return i++;
}
You also then have to wonder why you even need it. As you're passing it an integer and not the value of a variable, why not just initialise it without the method call?
static int age = 11;
I am not sure I did the right thing. The main reason for my doubts is that I cannot find, in this or other forums, someone who has done a similar thing.
I created an abstract java class in my project. Named it lib. I put there several structures and methods used by all other classes in the project.
It works for me, but I want to know if there is a more accepted method of gathering all common methods and structures.
Note: All methods of course are declared as public static.
Note II: I did not know how to get the context within the abstract class, so if needed I had to pass it as argument to the method.
Is this wat you are looking for?
public abstract class AbstractActivity extends Activity{
public static synchronized boolean showAlertBox(Context ctx,final String title,final String message,final String okBtnTxt,final OnClickListener clickListener){
AlertDialog.Builder alertbox; alertbox = new AlertDialog.Builder(ctx);
this.runOnUiThread(new Runnable() {
#Override
public void run() {
alertbox.setTitle(title);
alertbox.setMessage(message);
if(okBtnTxt!=null || clickListener!=null)
alertbox.setNeutralButton(okBtnTxt,clickListener);
alertbox.show();
.....
}
});
return true;
}
}
In the class extending this abstract class you can just call it by using showAlertBox(this);
Other wise use AbstractActivity.showAlertBox(Context);
Well, thanks to #Matt Wolfe's comment I came to know that what I did is called "Utility class" and it is widely used to share common code in a project.
The general template is:
public abstract class lib {
public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
public static void func1(int i) {
}
public static void func2(int i, String s) {
}
}
and you can use it like this from any other code:
...;
lib.func1( lib.ZERO );
lib func2( lib.TWO, "sandwich" );
...;
Knowing that makes me confident that what I did is OK.
It would be perfect to find a way to avoid the prefix lib. and just have ECLIPSE, and the compiler, find the right import and recognize the function with just its name, like they do for global libraries.
What i need to do is create an app which will generate a random mathmatical expression for the user to solve based on a difficulty level that they select.
eg. novice: a random operation on 2 terms
easy: random operations on 2 or 3 terms
What I'm struggling with is creating a class to handle the creation of expressions
My Game class is as follows:
package w1279057.CW1;
import android.app.Activity;
import android.os.Bundle;
public class Game extends Activity {
public static final String KEY_DIFFICULTY = "w1279057.CW1.difficulty";
public static final int DIFFICULTY_NOVICE = 0;
public static final int DIFFICULTY_EASY = 1;
public static final int DIFFICULTY_MEDIUM = 2;
public static final int DIFFICULTY_GURU = 3;
private int puzzle[];
#Override
public void onCreate(Bundle savedInstanceState) {
int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_NOVICE);
setContentView(R.layout.gameview);
}
}
What i think i need is a class which has methods for generating a specific amount of operations randomly and then generating the random numbers for the expressions as well, once i have a valid expression i need to update a textview to display the expressions.
Am i on the right track?
I think this could be a good approach, as you will decouple the mathematical logic from your Activity. So... my advice is to go in this way :)
I am developing an android board game and I am stuck with an error from one of my parameters. It is a mancala-based game with a view (TableView.class) containing rows of pits with stones in then, and a main activity (Game.class). I am attempting to define a pit and its contents.
Here is a snippet of the code:
public class Game extends Activity {
int pitIndex, pitContents;
int _pitContents=4;
int pitsPerRow=5;
//more code here .......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
table_view = getInitialTableView();
tableView = new TableView(this);
setContentView(tableView);
tableView.requestFocus();
//...more code here
//
// ...
// define a playing pit
public int Pit(int pitIndex, int pitContents) {
this.pitIndex=pitIndex;
this.pitContents=pitContents;
}
// set player1's pits and populate them
public int Player1Pits[] = new int[16*2];
{
for (int i = 0; i < (2 * pitsPerRow); i++) {
if (i < pitsPerRow) {
Player1Pits[i] = new Pit(i,_pitContents);
else {
// do nothing
}
}
}
//.....
}
The error I get from Eclipse is that "Pit cannot be resolved to a type" when I try to instantiate a new pit:
Player1Pits[i] = new Pit(i,_pitContents);
Does anyone know where I am going wrong? Do I have to define Pit as a class outside the Game class?
I have searched exhaustively for a solution before posting this question. Your input will be appreciated. Thanks in advance.
Get rid of your method called Pit and make a pit class like this:
public class Pit {
public int mPitIndex, mPitContents;
public Pit(int pitIndex, int pitContents) {
this.mPitIndex = pitIndex;
this.mPitContents = pitContents;
}
}
What languages are you familiar with by the way?
Is Pit a class somewhere in the 'more code' sections? From what I see, you're trying to do new on a function directly, not on a class.
Hey I am having trouble declaring, changing, and using a global variable. I tried the whole "make a class that extends your application and put variables there" thing but I'm not sure how to implement it. Here is my class with the variable in it.
public class MyApp extends Application {
public int listPos;
}
I then tried to access and change int listPos here.
public class Browse extends ListActivity{
MyApp app = ((MyApp)getApplicationContext());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] coffeeTypes = getResources().getStringArray(R.array.coffeeTypes);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listview, coffeeTypes));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
app.listPos = position;
startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
});
}
}
Then I tried to access the variable in the following activity to determine the outcome of an if else statement
public class CoffeeTypes extends Activity{
MyApp app = ((MyApp)getApplicationContext());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(app.listPos == 0){
Toast.makeText(this, "WEEEEEEE!0", Toast.LENGTH_LONG).show();
}
else if(app.listPos == 1){
Toast.makeText(this, "RAWR!1", Toast.LENGTH_LONG).show();
Anyone have any idea what I am doing wrong?
You can use soorya's answer with some modifications. I would personally still use your myApp class but change listPos to static and access it that way. Doing it this way lets you use the Application class onCreate method to initialize values if needed (though it won't be needed in this example) or other Android methods.
public class MyApp extends Application {
public static int listPos;
}
//~~ Elsewhere:
MyApp.listPos = 5; //etc
But this isn't the best way to handle your type of problem.
You should be passing the list position information (or the id of the item clicked or however you are handling your data) via the Intent.
Instead of having a global variable to track this information, keep it local to just the Intent:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//app.listPos = position;
Intent intent = new Intent(Browse.this, CoffeeTypes.class);
intent.putExtra("position", position);
startActivity(intent);
//startActivity(new Intent(Browse.this, CoffeeTypes.class));
}
This passes the position data to the new Activity via the intent. In your CoffeeTypes Activity you should start with something along the following:
//in onCreate...
int incomingPosition = getIntent().getIntExtra("position",-1));
if(incomingPosition != -1) { //do stuff }
This will read the "position" data from the incoming Intent so you can use it. The -1 above is the default value if nothing is added.
One final warning: you might want to be careful sending the list position back and forth, depending on how your application is set up if new items are added/items are deleted the list position might no longer refer to the item you thought it did. If these coffee types/whatever you are using have a separate unique ID that might be more appropriate to avoiding the above situation, consider using that instead.
I'm not sure if it's a visibility issue with the android OS, are you able to make an public functions that may be able to act as getters for the variable?
int getListPos(){ return this.listpos; }
I know that you can pass variables between contexts, you may have to do that.
Perhaps a temporary workaround to get you moving could be creating a static class of accessible variables too?
Create a class like this
class globalClass
{
static int lastPos;
}
You can set values using
globalClass.lastPos = value;
and get function is
int myVal = globalClass.lastPos;
i do Application variable classes by making the variables private, and then create public get() and set() methods to change the variables. you can try that, but it seems like you are doing it right, technically
one reason why it might be going wrong is because you are implementing the stuff in onCreate and not onStartCommand. if you are testing this function with the wrong assumptions/knowledge of the Activity cycle, it could go wrong