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;
Related
I observed strange behavior of SparseArray defined as static final field of Enum while testing with JUnit4. Enum class:
public enum ConstantType {
PI(0, Math.PI),
E(1, Math.E),
;
private static final SparseArray<ConstantType> BY_VALUE = new SparseArray<>();
final int id;
final double value;
static {
for (ConstantType type : values()) {
BY_VALUE.append(type.id, type);
}
}
ConstantType(int id, double value) {
this.id = id;
this.value = value;
}
#Nullable
static ConstantType fromValue(int value) {
return BY_VALUE.get(value);
}
}
Problem is when I access method ConstantType.fromValue(0), this method returns always null. I also used debugger to check if filling of BY_VALUE was called, but strangely, debugger show this value as "null" without NullPointerException.
Replacing of SparseArray by HashMap fixed my issue, but I am curious, why SparseArray is not working.
While this question is 3 years old, it is still a relevant question.
SparseArray (android.util.SparseArray) is part of the Android SDK, not native Java/Kotlin. Unfortunately, that means it would not behave like, for an example, an Array. Instead, it would behave like one of your classes. That means that you have to mock/fake it for it to work.
In general, try to avoid having static fields, as they make testing harder. Had your value not been static, you could have injected a provider which could provide a mock/fake.
I'm busy trying to translate some iOS code to Android code. The iOS code contains Enums, like the following:
typedef NS_OPTIONS(NSUInteger, Traits) {
TraitNumberOne = 1<<0,
TraitNumberTwo = 1<<1,
);
I have never worked with Enums before in Android, and am having trouble interpreting the documentation and examples that are available. How would I translate the above example to Android code?
use this
public enum NS_OPTIONS {
TraitNumberOne (1<<0),
TraitNumberTwo (1<<1);
private final int Option;
public int getOption()
{
return Option;
}
private NS_OPTIONS(int option) {
this.Option= option;
}
}
Use it like this:
int value = NsOptions.TraitNumberOne.getOption();
Java enums are relatively simple, but can be made more complex to fit whatever needs you want to use them for. If you just want the type-safety of an enum, you can just declare the variable names like this:
public enum Traits{
TraitNumberOne,
TraitNumberTwo
}
If you want more advanced features of an enum, it's treated exactly like a class that is instantiated statically for each item in the enum. So, you can have a constructor and input whatever value you want associated with each individual item, like so:
public enum Traits{
TraitNumberOne(0x01),
TraitNumberTwo(0x02),
// future items go here
; // don't forget the semi-colon, which indicates the list of items is ending
// now, create a private variable to store the data
private final int data;
// and the constructor to set the data
private NsOptions(int data){
this.data = data;
}
// now, you can provide an accessor to provide access to the data
public int getData(){
return this.data;
}
}
You can use the above enum like this:
Traits currentOptions = Traits.TraitNumberOne;
int optionsData = currentOptions.getData();
The idea of NS_OPTIONS is to allow all possible combinations of the enumerated values to be represented by one value (this is why bitwise operators are used). In Java, I guess the equivalent would be:
public enum Permission {
TraitNumberOne (0b01),
TraitNumberTwo (0b10);
...
}
We can implement in android like ,
public enum NS_OPTIONS{
TraitNumberOne(1),TraitNumberTwo(2);
private int type;
NS_OPTIONS(int type){
this.type = type;
}
public int getType(){
return type;
}
}
and if you want to use above enum from your class you can use it like,
int i =NS_OPTIONS.TraitNumberOne;//which will return 1
int j =NS_OPTIONS.TraitNumberTwo;//which will return 2;
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.
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.
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 :)