How do i create a class and the methods I need? - android

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 :)

Related

Android Header? How to create enums visible in whole project?

I'm looking for a way to create a "header" or something like that to specify some variables like:
enum Misc
{
double EFFECT_DAMAGE = Math.pow(2,0);
double EFFECT_ABSORB = Math.pow(2,1);
double EFFECT_HEAL = Math.pow(2,2);
int SPELL_FIREBALL = 51673;
}
And in every .java file I want to be able to write:
double effect = 1;
if (effect == EFFECT)
{
...some code...
}
Is there a nice way to do this?
I'm creating a mini game for now and want to have all the files nice and tidy to manage my project in the future easier once it gets bigger.
Thx in advance.
public enum Misc
{
EFFECT_DAMAGE(0), // 2^0
EFFECT_ABSORB(1), // 2^1
FIREBALL(245151);
private double value;
private Misc(double d){
value = d;
}
public String toString(){
return String.valueOf(value);
}
}
Access like this:
System.out.println("Fireball damage:" + Misc.FIREBALL);
You cannot assign values this way to a enum in java.
Instead you should use a public class with public static final variables to make them constants.
public class Misc {
public static final double EFFECT_DAMAGE = Math.pow(2,0);
public static final double EFFECT_ABSORB = Math.pow(2,1);
public static final double EFFECT_HEAL = Math.pow(2,2);
public static final int SPELL_FIREBALL = 51673;
}
So you can use in your code like
if (effect == Misc.EFFECT_DAMAGE )
{
...some code...
}
If you want use only the field without the class name first you should import the class as static:
import static test.Misc.*;
....
if (effect == EFFECT_DAMAGE ) {

Is this a Bad Programming Practice in Android?

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;

Android project local manually created lib

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.

Android, Best way to provide app specific constants in a library project?

I am creating a library project for a number of android apps.
The apps all have some common functionality that I wish to include in the library project but the library project functions require use of application specific constants
So I am looking for a way to provide the library functions with the names of the constants and allow each app to define them
An example of a specific app constant and how it is used within the library project
public class AppConstants {
public static final long APP_ID = 6;//Needs to be set for each app
}
public static long getCurrentAppId(Context context) {
return getLongPreference(context, CURRENT_APP_ID_KEY, AppConstants.APP_ID);
}
This is just one example of approximately 60 constants that need to be defined for each app for a large number of library functions
Obviously I would normally just import/include the project specific app_constants.java file but this is not possible in the library project files as it hasn't got a clue about the specific applications (rightly so)
So what is the best way to have each specific app override the constants?
Update
I took a long time deciding on which of the superb answers I have been provided with best suited my needs (Thanks everyone) In the end I chose the xml solution. I don't particularly like it because it clutters up my apps resources and I did seriously consider using the interface solution but the xml solution does work nicely
Option #1
Extend your AppConstants class in each project
Better Option#2
Use XML resources to define the constants
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="integer" name="app_id" format="integer">6</item>
</resources>
then you can retrieve them by
Context.getResources().getInteger(R.integer.app_id);
add the xml file to your resources in each project with only the values you need different
I don't know of a great schema to do that but it would certainly work this way:
define some base class in your library
// class, enum or whatever you want it to be.
class BaseConstants {
// use some real singleton instead
public static final BaseConstants instance = new BaseConstants();
// define those values - sadly static inheritance does not work
private static final int APP_ID = 0;
private static final int CURRENT_APP_ID_KEY = 24;
// so we have to do that via methods
protected int getAppId() {
return APP_ID;
}
protected int getAppIdKey() {
return CURRENT_APP_ID_KEY;
}
}
let each Activity that wants something custom implement that
class App1Constants extends BaseConstants {
public static final App1Constants instance = new App1Constants();
private final static int APP_ID = 1;
// want a different APP_ID here.
protected int getAppId() {
return APP_ID;
}
// getAppIdKey not implemented here, uses default
}
Use that class as context to the constants for your library
class Library {
public static long getCurrentAppId(Context context, BaseConstants settings) {
return getLongPreference(context, settings.getAppIdKey(), settings.getAppId());
}
}
Activities would be like so
class myActivity extends Activity {
// each Activity can implement it's own constants class and overwrite only some values
private static final BaseConstants CONSTANTS = App1Constants.instance;
private void whatever() {
long appId = Library.getCurrentAppId(this, CONSTANTS);
}
}
class myActivity2 extends Activity {
// or could just use the default ones
private static final BaseConstants CONSTANTS = BaseConstants.instance;
private void whatever() {
long appId = Library.getCurrentAppId(this, CONSTANTS);
}
}
That schema is kind of ugly but it would work at least
Define them as enum's in your library project, like
public enum Planet { MERCURY, VENUS, MARS }
Android proper takes another approach, the dreaded constant interface, like,
interface Planets {
static final int MERCURY = 1;
static final int VENUS = 2;
...
}
However, this is a well-known Java anti-pattern (constant interface, and is covered in detail in Effective Java, I quote,
The constant interface pattern is a poor use of interfaces. That a
class uses some constants internally is an implementation detail.
Implementing a constant interface causes this implementation detail to
leak into the class’s exported API. It is of no consequence to the
users of a class that the class implements a constant interface. In
fact, it may even confuse them. Worse, it represents a commitment: if
in a future release the class is modified so that it no longer needs
to use the constants, it still must implement the interface to ensure
binary compatibility. If a nonfinal class implements a constant
interface, all of its subclasses will have their namespaces polluted
by the constants in the interface.
If you need the constants to have int values for some reason, and calling toString() on the enum isn't sufficient, you can give the enum's a extra information like,
public enum ZipCode {
LYNNWOOD(98036), SAN_JOSE(95112), ...;
private int zipCode;
private ZipCode(int zipCode) { this.zipCode = zipCode; }
public int getZipCode() { return zipCode; }
}
Note that enum's are slightly less performing than integer constants, but from a code organization and clarity perspective they are far superior.

How to organize Android dialog IDs?

I have a base class ActivityA that has some dialogs:
public static final int SOME_DIALOG_ID = 1;
public static final int OTHER_DIALOG_ID = 2;
ActivityB inherits ActivityA and comes with its own dialogs:
public static final int MY_DIALOG_ID = 1;
public static final int CONFLICT_DIALOG_ID = 2;
As you can see, the dialog IDs are no longer unique within the activity. This is a problem that I keep running into. Easy to fix, but tedious to maintian. There must be some good design pattern for this particular issue. Please, enlighten me!
Q: What is the best way to organize dialog IDs?
In my situation, I create class called AppConstant.java that contain all constant in current application, some of it:
public static final int INTENT_REQUEST_CODE_ACT_MAIN_BROWSE_PICTURE = 1;
public static final int INTENT_REQUEST_CODE_ACT_MAIN_CAMMERA_SNAP = 2;
public static final int INTENT_REQUEST_CODE_ACT_PROCESS_IMAGE_PROCESS = 3;
public static final int INTENT_REQUEST_CODE_ACT_PROCESS_BROWSE_PICTURE_FOR_BACK_DATA = 4;
Using this convention, I can easily maintain my ID within single class.
How about use 1, 2 for ActivityA, then 11, 12 for inherited class, then 101, 102 (or 21, 22) for further inheritance depth.

Categories

Resources