Set resource ID of String in code - java

Is there a way to set the ID of a string in code, so I can call the string in other Activities by R.strings.codegenstring. I can't predefine them in the string.xml since there will be a variable amount of code generated strings.

No. But you can define a String as static
public class A {
public static String s;
public void yourStringGeneratingFunction() {
s = "blahblah";
}
}
And access it from another class by:
A.s

No, there no way. To call string by R.string.codegenstring you must define public static string variable in R class. But R class are built by Android during compiling and you shouldn't modify it.

Related

Java: Select class member by string [duplicate]

How can I set or get a field in a class whose name is dynamic and stored in a string variable?
public class Test {
public String a1;
public String a2;
public Test(String key) {
this.key = 'found'; <--- error
}
}
You have to use reflection:
Use Class.getField() to get a Field reference. If it's not public you'll need to call Class.getDeclaredField() instead
Use AccessibleObject.setAccessible to gain access to the field if it's not public
Use Field.set() to set the value, or one of the similarly-named methods if it's a primitive
Here's an example which deals with the simple case of a public field. A nicer alternative would be to use properties, if possible.
import java.lang.reflect.Field;
class DataObject
{
// I don't like public fields; this is *solely*
// to make it easier to demonstrate
public String foo;
}
public class Test
{
public static void main(String[] args)
// Declaring that a method throws Exception is
// likewise usually a bad idea; consider the
// various failure cases carefully
throws Exception
{
Field field = DataObject.class.getField("foo");
DataObject o = new DataObject();
field.set(o, "new value");
System.out.println(o.foo);
}
}
Class<?> actualClass=actual.getClass();
Field f=actualClass.getDeclaredField("name");
The above code would suffice .
object.class.getField("foo");
Unfortunately the above code didn't work for me , since the class had empty field array.

How to initialize variable and use it in the whole java class

I am new to java.
I want to know how I can use the variable in the whole java class and keeping the value of it. Suppose in a method I fill the variable with a value and I want to use the value of it in another method.
public class Test {
public String id;
public void includeClient() {
String id = baseClass.createCleint();
}
public void removeClient() {
System.out.println(id);
}
}
in second function it returns null. Any idea?
In the method includeClient() you assigned the value to a local variable having the same name as the instance variable. The other method (which, BTW, can't have the same signature as the first method) sees the instance variable, which is still null.
Change it to :
public void includeClient() {
id = baseClass.createCleint();
}
Remove String from String id = baseClass.createCleint(); as it is local variable for the method and will be assiged the value when you call method and garbage collected after the execution of method and not accessible outside the method.
In short you are not assigning value to the variable declared at class level but you are creating another one.You better use Constructor to perform initialization.
Secondly you have declare public void includeClient() { twice I bet it's typo.
public class Test {
public String id;
public void includeClient() {
id = baseClass.createCleint();
}
}
public class Test {
public String id;
public void includeClient() {
String id2 = baseClass.createCleint();
System.out.println(id2);
id = id2;
}
public void includeClient2() {
System.out.println(id);
}
}
Use this to understand and test.
List of changes made -
Changed second method name to make it unique
Assigned return value to local variable named different than class member variable.
First print return value to check what it is returning
Assign local value to member variable.
Note: You still need to read a lot about java. Just keep practicing.
Replace:
String id = baseClass.createCleint();
by
this.id = baseClass.createCleint();
or
id = baseClass.createCleint();
An important thing to note about this is that there's two ways to share a variable like this - you can have each object of the class have its own copy of the variable, or you can have every object of the class share the same one variable. The keyword static lets you do the latter:
class Test {
public String message;
}
class TestStatic {
public static String message;
}
If you have instances of the first class, they behave like each instance has its own message:
Test testA = new Test();
Test testB = new Test();
testA.message = "Hello!";
testB.message = "Greetings!";
System.out.println(testA.message);
System.out.println(testB.message);
But with the second class, what happens is that the class itself has a message and all instances of the class refer to it, so there's only one message that's shared between all of them:
TestStatic testA = new TestStatic();
TestStatic testB = new TestStatic();
TestStatic.message = "Hello!";
System.out.println(testA.message);
System.out.println(testB.message);
Note that we didn't set message using either testA.message or testB.message as above - we set it using the class with TestStatic.message. This is because message doesn't really belong to either testA or testB, it belongs to the class and testA and testB simple have access to their class's members.

Get name of class during static construction

In C# I can assign the name of a class to a local static variable like this.
public class MyClass
{
private static string TAG = typeof(MyClass).Name;
}
I've found this very useful, because the value of the string automatically updated if the class is refactored to another name. Handy for tagging debug messages and such.
Is something like this possible in Java?
public class MyClass
{
private static String TAG = ????;
}
I know I could use getClass().getName() but that requires a reference to an object. Is there a way to do this on a static variable?
You don't need to assign the name of a class to field instead of writing.
MyClass.TAG
you can write
MyClass.class.getName();
If you really need to you can assign this to TAG but I don't see the point.
A trick is also available that does not require programmer's knowledge of the class name beforehand:
public class MyClass
{
private static String TAG =
new Object() { }.getClass().getEnclosingClass().getName();
}
This trick uses a nested anonymous Object subclass to get hold of the execution context. It has a benefit of being copy/paste safe in case of cloning your code across different classes...

Accessing data from a data class returning null

OK, I'm not super new to java but for some odd reason I can't figure out why this is not working for me. Basically I have 3 classes in my applet.
My main, my string constructor, and my data class.
The main class calls the string constructor, the string constructor stores its final product into the data class. Last, I'm trying to access the data class using my Main class.
The returned value to the main is always null and I can't figure out why. My suspicion is I'm somehow creating 2 separate data class objects but Ive looked at examples of code and it all seems correct. Here are the classes..
main.
public class LaneGUI extends javax.swing.JApplet {
private laneData laneData;
Timer timer;
/** Initializes the applet LaneGUI */
public void init() {
laneData = new laneData();
xmlParser.parseInputString(connection.getFinalXMLString());
System.out.println(laneData.getLaneID());
string contructor...
public class XMLParser {
private laneData laneData;
public void parseInputString(String input){
try{
/*some xmlparsing*/
laneData = new laneData();
laneData.setLaneID(string);
data class
public class laneData {
private String laneID;
public String getLaneID() {
return laneID;
}
public void setLaneID(String laneID) {
this.laneID = laneID;
}
}
There is a lot of editing here, like in the string class I took out all of the xml parsing and string editing.
Basically, when i check the getLaneID after i set it in the string constructor the value is correct. But when i call a get from the main, its null.
XMLParser and LaneGUI are referring to two different instances of laneData.
Instead of your final line in LaneGUI, which says this:
System.out.println(laneData.getLaneID());
You need something like this:
System.out.println(xmlParser.getLaneData().getLaneID());
You'll also, of couse, need to add a getLaneData() to XMLParser that returns it's laneData instance (or a deep copy thereof.)
As you rightly speculated, you have two different instances of laneData. The XMLParser class has a local instance of laneData different from the instance referenced by LaneGUI.

Duplicate static field (Array vs String)

I have a question about the following code:
public Class Settings{
public static final String WelcomeMessage= "helloworld";
public static final String ByeMessage= "yo";
public static String[] widgets = {WelcomeMessage,ByeMessage};
}
The compiler complains about duplicat variables. Can I delete the 2 separate variables and still acces WelcomeMessage by Settings.WelcomeMessage? I don't need to acces it by Settings.widget[0]? And is it possible to add another variable to the WelcomeMessage variable (by for instance using a static hashtable)?
Edit: I know this code doesn't look right but it's just an example because I wondered why the compiler thinks WelcomeMessage (as a separata variable) is the same as the variable in the Widgets array.
I would consider java-enums in your case:
public enum Settings {
WelcomeMessage ("helloworld"),
ByeMessage ("yo");
public final String value;
Settings(String value) {
this.value = value;
}
}
You can access now the values via Settings.WelcomeMessage.value. Also you get a List of the enums with Settings.values().
You've marked the fields as public static which means that yes you'll be able to access them via:
Settings.WelcomeMessage
or if you you use a static import in your class, just:
WelcomeMessage
You haven't actually used these constants in the widgets array, you've just created two new strings in there "WelcomeMessage" and "ByeMessage"
public static String[] widgets = {"WelcomeMessage","ByeMessage"};
No, if you delete the WelcomeMessage and ByeMessage constants you can't access them in that way, you'd have to go through the widgets array and access them as:
Settings.widgets[0]
I think you meant to use this instead:
public Class Settings
{
public static final String WelcomeMessage= "helloworld";
public static final String ByeMessage= "yo";
public static String[] widgets = {WelcomeMessage,ByeMessage};
}
But this is better:
public Class Settings
{
public static String[] widgets = {"WelcomeMessage","ByeMessage"};
}
And yes you can access WelcomeMessage via Settings.widgets[0].
Edit: Oops - yep - of course you cannot access them by name, only index into the array.
Edit 2: If you make the field protected or private and provide 'getter' methods, then it doesn't matter to any user classes how they are implemented:
public Class Settings
{
private static final String welcomeMessage= "helloworld";
private static final String byeMessage= "yo";
public static String getWelcomeMessage()
{
return welcomeMessage;
}
public static String getByeMessage()
{
return byeMessage;
}
}

Categories

Resources