How to assign dynamic names in Java Android? - java

How do you initialise the name of a TextView or any other Android component with a name only known at runtime?
For example:
LinearLayout linLayout = (LinearLayout) findViewById(R.id.dynamicLayout);
linLayout.setOrientation(LinearLayout.VERTICAL);
for(int i = 1; i < 5; i++){
String dynamic_name = "myTextView"+i;
//Create new textView named dynamically
TextView dynamic_name = new TextView(this);
//style textView here etc
linLayout.addView(dynamic_name);
}

How do you initialise the name of a textView or any other Android component with a name only known at runtime?
You can't.
TextView this_variable_changes is defined at compile time while String this_variable_changes changes at runtime.
Then how to create a variable amount of textViews based on a number that can only be known at run-time?
Once you've got the amount of TextViews at runtime, programmatically create that much TextViews and add those to a layout.
You don't need dynamic names by the reason mentioned above. What you can do is to map the received amount to the corresponding number of TextViews, i.e. use Map with the keys indexed up to the received amount and values of TextViews.

In Java, but you can create Maps or Arrays to deal with your particular issue. When you encounter an issue that makes you think "I need my variables to change names dynamically" you should try and think "associative array". In Java, you get associative arrays using Maps.
That is, you can keep a List of your arrays, something like:
List<String[]> kList = new ArrayList<String[]>();
for(int k = 0; k < 5; k++){
kList.add(new String[3]);
}
Or perhaps a little closer to what you're after, you can use a Map:
Map<Integer,String[]> kMap = new HashMap<Integer,String[]>();
for(int k = 0; k < 5; k++){
kMap.put(k, new String[3]);
}
// access using kMap.get(0) etc..

Simple solution for me was going to your cmd type ipconfig Copy your IP v4 address and paste in android emulator host
http://your-ip-v4-address:3000/

Related

How to get values of vars by its name

I'm using the CPLEX Java interface to do some MIP problems, the optimizer is doing well but I can't get values of vars by their names.
The definitions of my vars are in a for loop, so in the outer code, I can't use cplex.getValue() function to get their values.
Please remind me of any methods that can get all the values or get values by their names.
for (int i = 0; i < count; ++i){
// c1 is changing when i increase
IloNumVar[] x = new IloNumVar[c1];
for (int j = 0; j < c1; ++j) {
x[j] = cplex.numVar(0, 1, IloNumVarType.Int, "x" + String.valueOf(i) + "_" + String.valueOf(j));
}
}
...
cplex.solve();
How to retrieve all x values outer for loop after cplex.solve()?
Just don't try to recover them by their names. Keep your CPLEX variables in lists, arrays, dictionaries, structures, class instances or whatever in your code. Your IloNumVars are just normal objects that can be stored like any other. In your example code, just keep those IloNumVar arrays in a structure declared outside the loop (e.g. a list of those IloNumVar[] arrays).
If you really need to retrieve them by name, then put them in a dictionary, keyed on the variable name - again that would have to be declared outside your loop above. But that would be less efficient than just keeping them in your usual Java data structures as it would require extra lookup processing inside the ictionary to find the item by name.

How can I get and set a string resource dynamically in a for-loop using a findViewById() method?

In my app, I want a counter from 0 to 8 to decide the number of players in a game.
Below there are 8 possible fields to write a name inside, which are all set to invisible. If the players-counter is set to 3 players, there should be the first 3 fields visible. Depending on the actual number of the counter, the visibility of the fields changes (1player = first field, 5 players = first 5 fields).
When the +1 (player) button is clicked, a certain method is activated. I tried to run a for-loop everytime the button is clicked. In this for-loop from 0 to "whatever amount" (max. 8 players) the actual fields should be found with "findById" and set to visible.
I tried it with a string resource (.xml) and I can get the text of the resource but with my thought process, I have to update the string resource to every number of the field (if 3 players: "field_" + "1", "field_" + "2", "field_" + "3").
How can I get and (most importantly) set/update a string resource for this specific purpose?
(Switch is too inefficient and I can't use a string with the findViewBy Id()-method by updating the String (not string resource) like mentioned before.
Please help, and accept the fact that I'm new to Android Studio for one week!)
You can use "getIdentifier" which takes a String parameter. So you can set the type as "id" in the second parameter of this method. This method returns the id of the view you want, but beware, it will throw a "FATAL EXCEPTION" if the id of the View doesn't exist. With this id, you can use findViewById to fetch the TextView and change its visibility. The "getIdentifier" method can be called from the "getResources()" method.
Below you can see what it would be like to make visible a TextView that has the id "textView1":
int id = getResources().getIdentifier("textView1", "id", getPackageName());
TextView textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
Below you can see how you would make 8 TextView with id 1 to 8 visible:
TextView textView;
for (int i = 1; i <= 8; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
So, just put the limit at i <= x , with x being the limit of players who will play:
TextView textView;
for (int i = 1; i <= totalPlayers; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
Do you just want to make some EditTexts visible and others not? Personally I'd keep it simple, do the lookups once (in onCreate or wherever) and store the references in a list. Then when you need to display n fields, you can just iterate over the list and set the first n to VISIBLE and the rest to INVISIBLE.
I feel like it's fine to just list all the EditText IDs (R.id.field_1 etc) and generate your list of actual Views from that, but if that repetition bothers you, there's a few things you could do. Like:
set a tag attribute on each field in the XML, and use findViewWithTag to look them up, generating the lookup strings programmatically, like "field_" + i
do a similar thing with the resource ID, like in #Moises's answer
lookup their containing layout, use getChildCount and [getChildAt] to iterate over the views in that layout, and use isInstance to collect all the EditTexts in order3
create and add the EditTexts in code - you probably don't want to do this, but you could!
I'm not really sure what you mean about the string resource or what you're trying to do - I'd honestly just make a list of R.id.field_1 etc, iterate over that to do findViewById on each and store those in a new list, and you're done. Also my Java's a bit rusty so sorry no example code!

Trying to Reference a Button With a String

I have a situation in an app I'm making where I have an activity that has 15 buttons and a string[] that contains 15 strings. I'm looking for an easy way to assign each string in the string[] to its corresponding button. I was hoping I could somehow do something like:
for(int i; i<myStringArray.length; i++){
String ref = "btn" + (i + 1);
ref.setText(resultString[i]);
}
where all the buttons are labeled "btn1", "btn2", etc so that they could all be accessed with the string "ref". Obviously this doesn't work so I was wondering if there was another way of doing something similar to this instead of doing:
btn1.setText(resultString[0]);
btn2.setText(resultString[1]);
btn3.setText(resultString[2]);
...
thanks for the help!
I think you can solve this by having a Button[] table where you store all your Button objects and then you can access them by index instead of the actual object name:
Button[] btns = new Button[15]
for(int i = 0; i < btns.length; i++) {
btns[i].setText(resultString[i]);
}
Hope that helps.
EDIT: Ofcourse you have to fill your Button[] btns with your objects first.
You can do what you tried using reflection. It would be way better in your case to store your buttons in an Array or a Map instead though.

For loop counter in dot operator

I'm working in the Android ADT plugin for Eclipse.
What I try to do is this:
I have some drawables named from 0 to 150 and i want to get them into an array to use them.
As far as I know, to be usable, they have to be assigned with
"R.drawable.FilenameWithoutExtension".
To make the array creation easy and fast I want to use a for loop:
for (int i = 0; i <= 150; i++) {
imagesArray[i] = R.drawable.i;
}
But for now I get an error for that "R.drawable.i" because there is no file "i".
Is there a way to use the numeric value of "i" instead of the letter for the assignement "R.drawble."?
You can get a resource identifer from its name using the getIdentifier() method:
for (int i = 0; i <= 150; i++)
imagesArray[i] = getResources().getIdentifier(String.valueOf(i), "drawable", "your.package.name");
The file names must start with a letter because at build time the file names are converted to java identifiers.
After you do that you can use reflection access each of the members of R.drawable.

Java Can Variables Be Used in Variable Names

I have this little script repeated below in my code a few times. I know that I could run a function to do this easily, but can I use a variable as a variable name like in PHP.
if (4val != null && 4val.length() > 0){
Button 4 = new Button(this);
4.setText(4val);
4.setTextSize(20);
}
I want to be able to do something like
i=1;
while{i > 10}{
$$i = value;
//do stuff with $$i
i++;
}
Is this possible in Java?
No. But you can stick the buttons in an array, and then iterate through.
Button[] buttons = new Button[10];
// instantiate all the buttons
for (int i = 0; i < buttons.length; i++) {
// update the button
}
use Map instead
map.put("key","val");
map.get("key");
Well you can also use array, List , but if you use HashMap you retrieval process would be almost o(1)

Categories