Android Getting value from an Integer arraylist becomes a number - java

I am new to Android and from what I read here most of the question goes to Imageview setting image. Here is my problem same as ImageView errors
Ive created a arraylist of Integer because of some function needed Int List rather than String List. Basically like most of function I created it like this one
private ArrayList<Integer> myArrayList = new ArrayList<Integer>();
public void setPicture(Integer datanumber)
{
if (datanumber>=10)
{
myArrayList.add(R.drawable.picture);
}
else{
myArrayList.add(R.drawable.picture_gray);
}
///and so on
}
Everything works fine until I found out that I cannot get this string ex "R.drawable.picture" using this code
myArrayList.get(0).toString();
Instead it gives me random number that I cannot understand.
My question is how can I return it to default value(or the one that I add on my list)
Thank you for spending time reading my question

Use String.valueOf(myArrayList.get(0));
instead of myArrayList.get(0).toString();

It isn't giving you a Random number. It is giving you the value of R.drawable.picture. All resources in R.*.*are referenced through numbers. This is evident if you take a look inside R.java, which shows something like:
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int help=0x7f020000;
public static final int ic_action_search=0x7f020001;
public static final int ic_launcher=0x7f020002;
public static final int splash1=0x7f020003;
}
public static final class id {
public static final int userName=0x7f070002;
}
public static final class layout {
public static final int splash=0x7f030003;
}
public static final class menu {
public static final int action=0x7f060000;
public static final int menu=0x7f060001;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int create_user=0x7f040004;
public static final int help=0x7f040001;
public static final int image=0x7f040002;
public static final int primarymodtext=0x7f040003;
}
}
What you are getting is the int value R.drawable.picture. This is because when you're adding a value to the array list, you're passing in the int value stored in R.drawable.picture.
You can still use this integer value you get like you would use R.drawable.picture. Just pass it in normally.

Related

How to construct several objects in one class, then read in another class

I apologize if this is a basic question.
I am attempting to create several unique objects in one class, then get the values of one of the objects in another class.
I have created two classes and followed some examples to end with this
public class Type {
public String name;
public int healthmod;
public int strmod;
public int accmod;
public int armmod;
public int refmod;
public int intmod;
public String advantages;
public String disadvantages;
public Type() {
Type fire = new Type();
fire.name = "Fire";
fire.healthmod = 0;
fire.strmod = 1;
fire.accmod = 0;
fire.armmod = 0;
fire.refmod = 0;
fire.intmod = 1;
}
}
and then in the main class:
Player.typename = Type.fire.name;
Edit
public class Player {
public static String name, classname, racename, elementname;
public static int maxhealth, healthpts, healthptscost, healthupgnum, healthmod, currenthealth, basehealth;
public static int str, strpts, strptscost, strupgnum, strmod;
public static int acc, accpts, accptscost, accupgnum, accmod;
public static int arm, armpts, armptscost, armupgnum, armmod;
public static int ref, refpts, refptscost, refupgnum, refmod;
public static int intelligence, intpts, intptscost, intupgnum, intmod;
public static int mana, maxmana, managain, managainak;
public static int hitChance, critChance, Level, statPts, statTotal, damage, damageDealt, goldmult, itemmod, itemdefboost, itemdamboost, itemmodboost;
public static String[] focusStats;
}
What I am trying to do is create a few objects in the Type class and access them in the Main class in order to store the values in the Player class, but in the Main class, fire "cannot be resolved or is not a field"
Edited to provide more clarity on the purpose.
You are completely mixing things here.
In the concstructor of Type you are creating a new local Object named fire. This object is only available in this constructor and not outside of it, e.g. in the main class.
A valid solution can only be found if you give more information about what you try to accomplish.
I could write like that your Type construct:
public Type() {
this.name = "Fire";
this.healthmod = 0;
this.strmod = 1;
this.accmod = 0;
this.armmod = 0;
this.refmod = 0;
this.intmod = 1;
}
So when using the Player class in your Main method, like that:
public static void main(String args[]) {
Type type = new Type();
Player.typename = type.name;
}
You can also put a reference of type inside Player class like that:
public class Player {
public static Type fire;
}
So in your main method like that:
public static void main(String args[]) {
Player.fire = new Type();
System.out.println(Player.fire.name);
}

Android static variables are lost

I am using a class with only static variables to store all constants and run-time properties. But, recently I have seen instances when I'm referencing these variables, I get null.
Following is my class definition:
public class PlayerProperties {
// Runtime but constant properties
public static int screenHeight;
public static int screenWidth;
public static String androidId;
// Static properties
// Urls
public static final String baseUrl = "http://www.blynq.in/api/player/";
public static final String registerUrlAppender = "activationKeyValid";
public static final String schedulesUrlAppender = "getScreenData";
public static final String updateUrlAppender = "updateAvailable";
public static final String tokenRegisterUrl = "fcmRegister";
public static final String mediaStatsUrl = "mediaStats";
public static final String logsUrl = "logs";
public static final String pingUrl = "ping";
public static final String screenInfoUrl = "screenInfo";
// Developer Keys
public static final String youtubeDeveloperKey = "ABCDEFGH...";
// Folder structure
public static final String mediaFolder = "player/media";
public static final String imagesFolder = "player/media/images";
public static final String videosFolder = "player/media/videos";
public static final String pdfFolder = "player/media/pdf";
public static final String gifFolder = "player/media/gif";
public static final String webFolder = "player/media/web";
public static final String othersFolder = "player/media/others";
public static final String logsFolder = "player/logs";
public static final String defaultFolder = "player/default/";
public static final String serFolder = "player/ser/";
public static final String tempFolder = "player/temp/";
// Shared Prefs Keys
public static final String ANDROID_ID_KEY = "ANDROID_ID";
public static final String MY_PREFERENCES_KEY = "MyPrefs";
// General properties
public static final String dateTimeFormatString = "ddMMyyyyHHmmss";
public static final String dateFormatString = "yyyy-MM-dd";
// Timeouts
public static final int httpPollTimeout = 20000; // in millis
public static final int pingPeriodicity = 30; // in secs
public static final int updateCheckPeriodicity = 24; // in hrs
public static final int pushEnabledPollPeriodicity = 30; // in secs
public static final int pushDisabledPollPeriodicity = 30; // in secs
public static final int statsUploadPeriodicity = 60; // in mins
public static final int logsUploadPeriodicity = 24; // in hours
public static final int cleanupPeriodicity = 24; // in hours
public static final int registrationStatusRecheckPeriod = 20000; // in millis
public static final int tokenResendToServerPeriod = 20000; // in millis
// Others
public static final int maxTextHeight = 50; // in dp
...
}
I have not stored any reference instantiatin PlayerProperties class, as all variables contained within are static.
When I am referencing the variable androidId using PlayerProperties.androidId , I SOMETIMES get null.
I have initialized the variable in one of the activities:
PlayerProperties.androidId = sharedpreferences.getString(PlayerProperties.ANDROID_ID_KEY, String.valueOf(UUID.randomUUID()));
My suspicion is that garbage collector was kicked by android in between. If gc does kick in, would it knock off all my runtime-initialized static variables ?
Which memory segment are the static variables stored ?
If not, what else could be the issue ?
Extra details: My app is configured to automatically launches on boot. I am facing the above described issue only with low end processors and when app is automatically triggered on boot.
Please note the following in reference to above question:
Garbage collector removes only unreferenced objects. Static variables will lose their values only when they are unloaded from JVM during run-time.
Initialization happens when app is launched via activities. If there are any services/broadcast receivers that are accessing methods within other classes and use these ids, and the app is not yet running by that time, the uninitialized values are referenced as default value. In case of string - it is null.
Nothing to do with low-end processors, easy to blame them often but JVM is powerful enough.
Only public static String androidId; can be null, when you want to use it you should init it in this class or in some other class in onResume()
androidId is a reference to an string, string is a class that will get by default a null reference as intial value if you dont do it....
look at this taken from oracle's doc
So basically androidId is null because is not initialized....the fact that the variable is static or not is not relevant in this case...
see here for more details
...I SOMETIMES get null.
yes, you will get always null unless its value change at run time...

Suggest proper Design for Java integer constants extension

I am sorry if this question was asked before, but I need a good suggestion to solve next design problem:
Task: given that we have a base service that operates with data of given set of types, we need to design support of extensions for that service that has extended type set.
Bad Solution:
class BaseServiceType {
public static final int TYPE_A = 0;
public static final int TYPE_B = 1;
public static final int LAST_USED_BASE_TYPE_INDEX = TYPE_B;
}
And its extension
class ExtendedServiceType extends BaseServiceType {
public static final int TYPE_E = LAST_USED_BASE_TYPE_INDEX + 1;
public static final int TYPE_F = LAST_USED_BASE_TYPE_INDEX + 2;
}
My task is fairly simple that has only one extension. I am not trying to solve more general problem with multiple independent extensions.
I have a feeling that enum would work here, but no idea if it feasible.
One solution is to build the ids dynamically. Class initilization is thread safe so you can do this.
class BaseServiceType {
protected static int id = 0;
public static final int TYPE_A = id++;
public static final int TYPE_B = id++;
}
And its extension
class ExtendedServiceType extends BaseServiceType {
public static final int TYPE_E = id++;
public static final int TYPE_F = id++;
}
class AlsoExtendedServiceType extends BaseServiceType {
public static final int TYPE_X = id++;
public static final int TYPE_Y = id++;
}
The only problem is the order classes are initialized change the ids. If this matters, you need to access the classes in the order you need.

Using constants across the application

I have few constant values which I refer across my application. I am creating a class something like below snippet.
public class Styles {
public static final String tableStyle = "TableGrid";
public static final String fontFamily = "Calibri";
public static final String headerStyle = "Heading2";
public static final String footerStyle = "Heading3";
public static final String tableHeaderStyle = "Heading1";
public static final String tableDataFontFamily = "Cambria";
public static final int tableHeaderFontSize = 16;
public static final int tableDataFontSize = 12;
}
I am assigning the values in it and I am referring them like Styles.headerStyle . My doubt is, is this the good way or is there any better approach to achieve this? something like Enum ?
Thanks in advance.
It depends on the nature of your application, in most cases it is not a good practice to have a collection of constants in that way, but it is difficult to tell without knowing the context of your application. BTW, are sure that you'll never (or almost never) change things like "fontFamily"?
Of course an enum would be a little less verbose and more functional:
public enum Styles {
TABLE_STYLE("TableGrid"),
FONT_FAMILY("Calibri"),
HEADER_STYLE("Heading2"),
FOOTER_STYLE("Heading3"),
TABLE_HEADER_STYLE("Heading1"),
TABLE_DATA_FONT_FAMILY("Cambria"),
TABLE_HEADER_FONT_SIZE("16"),
TABLE_DATA_FONT_SIZE("12");
private String value;
private Styles(String value) {
this.value = value;
}
public String getStringValue() {
return value;
}
public int getIntValue() {
return Integer.valueOf(value);
}
}
1) You can use an external file as a Property File.
2) You can use an enum as #morgano answer
3) I would change your class declaration to
public final class Styles { // final class can't have childs
private Styles(){} // you cannot instanciate
public static final String tableStyle = "TableGrid";
.
.
.
}

Static members not initialized as expected

The following code simply subtracts a value (10 in this case, just for the demonstration) from the current year obtained by using the java.util.Calendar class.
public final class Test
{
private static final Test TEST = new Test();
private static final int YEAR = Calendar.getInstance().get(Calendar.YEAR);
private final int eval=YEAR - 10;
public static void main(String[] args)
{
System.out.println("Evaluation "+TEST.eval);
}
}
I expect this code to display 2003 (current year - 10) but instead, it displays -10. I assume the constant YEAR hasn't been initialized. Why does this happen in this case?
This happens because you are initializing Test before you have initialized YEAR - meaning it will go to the (implicit) constructor and initialize eval to YEAR-10 before YEAR has a value (so it defaults to 0).
As denoted in the comments, simply changing the order of YEAR and TEST in the initialization will do the trick.
Because it's not static - you have to create an object in order to use this field! (or change it to static)
Try:
public final class Test
{
private static final Test TEST = new Test();
private static final int YEAR = Calendar.getInstance().get(Calendar.YEAR);
private final int eval=YEAR - 10;
public static void main(String[] args)
{
Test t = new Test();
System.out.println("Evaluation "+t.eval);
}
}
Make eval static and it will work. If you do not want it static, then do the computation in the main method.
As others have mentioned, the problem is in the order of the static fields. But, you can avoid the ordering problem entirely by lazily initializing TEST using a method (like is done in the singleton pattern):
public final class Test
{
private static Test TEST = null;
private static final Test getInstance() {
if (TEST == null) {
TEST = new Test();
}
return TEST;
}
private static final int YEAR = Calendar.getInstance().get(Calendar.YEAR);
private final int eval=YEAR - 10;
public static void main(String[] args)
{
System.out.println("Evaluation "+Test.getInstance().eval);
}
}

Categories