Passing variable into findViewByID - java

I have the following setup. In my xml i have a bunch of image views. I am trying to show only one of them depending on the number set in preferences and the day of week. This must be really easy but i can't find out the correct way to pass variable into findViewByID. Here is code snippet:
String groupName = "R.id."+prefs.getString("groupListKey", "<unset>")+"_"+(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
ImageView image = (ImageView) findViewById(groupName);

findViewById() expects you to pass it an integer that represents a resource identifier. You are trying to pass it a string
Your best bet would be to have a conditional statement that evaluates your day of week and returns you the proper ID rather than doing it the way you are
int resourceId = 0;
switch (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
resourceId = R.id.sundayView;
break;
case Calendar.MONDAY:
resourceId = R.id.mondayView;
break;
...etc
}
ImageView image = (ImageView) findViewById(resourceId);

findViewById receives an int as an argument, which is one of the generated in the R.id class.
You can have an array with your ids:
int[] imagesIds = new int[] { R.id.image1, ... R.id.image7 };
And then determine the index based on your conditions:
int imageIndex = ...
ImageView image = (ImageView) findViewById(imagesIds[imageIndex]);

Related

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!

Java - dynamically build textview reference

New Android/Java coder. Trying to replicate in Android app a project I built in MS-Access.
I have a layout with similar named TextViews, like text10, text12, etc. In MS-Access I can dynamically build those names with collection referencing:
For X = 10 To 15
Me.Controls("text" & X) = Null
Next
There is no array required. So looking for structure in java that can accomplish the same functionality.
I want to dynamically set background color of multiple TextView based on two inputs. One is to build TextView reference and the other is a state indicator that will determine color.
Here is one procedure calling setSubColor:
public void Clear(MenuItem mi) {
puz.setText("");
sol.setText("");
for (int i=0; i<26; i++) {
setSubColor(aryA[i].charAt(0), 0);
What I have so far for setSubColor:
public void setSubColor (char c, int i) {
TextView v = (TextView) >>>dynamically reference v using name built with ("tv" + c)
if (i == 0) {v.setBackgroundColor(Color.TRANSPARENT);}
else {v.setBackgroundColor(Color.YELLOW);}
You can get the res id from the res name at runtime. So if your textview had name "text1", you could get the integer id by using:
int id = getResources().getIdentifier("text1", "string", getPackageName());
TextView view = findViewById(id);
But do so only as a last resort, it's error prone, slow and somewhat of an anti pattern.
EDIT by OP: No matter what the name argument is always returns 0 but marked as answer because it led to the following code that works exactly as I want, anti-pattern or not.
TextView v = (TextView) findViewById(getResources().getIdentifier("tv" + c, "id", getPackageName()));
Instead of the TextView Id field use its Tag field.
String tag = (String)textView.getTag() and textView.setTag(Object tag) with tag instanceof String
then you can find the TextView by Tag

ImageView setBackround inside the activity dynamically

Inside my drawabale folder I have these images: levelone, leveltwo, level three.
i need to set the ImageView according to the inputted string as follows:
levelindicatorImageView = (ImageView) findViewById(R.id.levelindicatorImageView);
String tempo="R.drawable.level"+LevelReached;
Drawable replacer = getResources().getDrawable(tempo);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
levelindicatorImageView.setBackgroundDrawable(replacer);
} else {
levelindicatorImageView.setBackground(replacer);
}
levelindicatorImageView.invalidate();
now inside LevelReached variable i have the needed level (one, two, three)
I need to set the Image R.drawable.leveltwo etc...
How is that possible please?
as getDrawable doesn't work with tempo (needs int)
thanks for the help!
You have 2 options:
Option 1:
Simply use a switch-case to get the correct drawable, then set it as a background image as you normally would
// Get the level drawable resource id
int imageRes = R.drawable.default_image;
switch (levelReached) {
case LEVEL_ONE: // 1
imageRes = R.drawable.level_one;
break;
case LEVEL_TWO: // 2
imageRes = R.drawable.level_two;
break;
...
}
// Set the drawable as a background
levelIndicatorImageView.setBackgroundResource(imageRes);
Where LEVEL_ONE == 1; LEVEL_TWO == 2; as const or enum.
Option 2:
You can find a drawable resource by name (as you wanted), but it is less recommended since it is more error prune. But if you must, use following example:
// Get the level drawable resource id
int imageRes = getResources().getIdentifier("level"+levelReached, "drawable", getPackageName());
// Set the drawable as a background
levelIndicatorImageView.setBackgroundResource(imageRes);
Note:
You don't need to explicitly invalidate the view if you set the background since setting a new background will trigger invalidation by itself. So, this line:
levelindicatorImageView.invalidate();
is not needed.
You cant append input string to image name, but what you can do is,
select the image based on input string and then If you have 3 different images, try with ;
if(input.equalsIgnoreCase("input one"))
{
int id = R.drawable.<img one>;
}
else
{
//so on
}
levelindicatorImageView.setBackground(getResources().getDrawable( id) );
You need to do something like this:
public int getResourecId(String level) {
if(level.equalsIgnoreCase("one"))
return R.drawable.levelone;
if(level.equalsIgnoreCase("two"))
return R.drawable.leveltwo;
if(level.equalsIgnoreCase("three"))
return R.drawable.levelthree;
return 0;
}
and then:
Drawable replacer = getResources().getDrawable(getResourceId(LevelReached));
You need to associate the levels to a resource, in this case, an int. An idiomatic way of doing this would be to store the levels as an enum, say
enum Level { ONE, TWO, THREE }
Using an enum in this way allows you some flexibility with your level conventions. For example, if you later wanted to add the level TWO_THIRDS, there is nothing stoping you. Then, associate each level with a resource in an EnumMap, for example:
Map<Level, Integer> levelResources = new EnumMap<Level, Integer>(Level.class);
levelResources.put(ONE, R.drawable.levelOne);
levelResources.put(TWO, R.drawable.levelTwo);
levelResources.put(THREE, R.drawable.levelThree);
Now, instead of passing around a string which describes your current level, you can pass around an enum, which you can use to determine the correct resource without concatenating strings. So, suppose that levelReached is of type Level, you could write:
Integer tempo = levelResources.get(levelReached);
Drawable replacer = getResources().getDrawable(tempo);

setText crashes app when trying to display byte values

I'm working on a android app that send and recieves data. In the app i have a button an a few texviews. When i press the button then data (two chars) will be send. And an the data that has been send will be shown in two tekst views.
I did the same with two integers and that worked now i want to do the same with bytes and chars and that failes.
The logcat gives the following error:
10-28 09:27:19.338: E/AndroidRuntime(13138): android.content.res.Resources$NotFoundException: String resource ID #0x0
Beloww is the onClick lisener code:
#Override
public void onClick(View v) {
// Control value
ArrayOutput[0] = 'B';
ArrayOutput[1] = 'B';
//Creating TextView Variable
TextView text = (TextView) findViewById(R.id.tv);
//Creating TextView Variable
TextView statustext = (TextView) findViewById(R.id.status);
//Sets the new text to TextView (runtime click event)
text.setText("You Have click the button");
// Convert string to bytes
ArrayOutput[0] = ArrayRecieved[0];
ArrayOutput[1] = ArrayRecieved[1];
final char Byte1 = (char) ArrayOutput[0];
final char Byte2 = (char) ArrayOutput[1];
final TextView Xtext = (TextView) findViewById(R.id.xtext);
final TextView Ytext = (TextView) findViewById(R.id.ytext);
Ytext.setText(Byte1);
Xtext.setText(Byte2);
try
{
statustext.setText("Sending....");
server.send(ArrayOutput);
statustext.setText("Sending succes");
}
catch (IOException e)
{
statustext.setText("Sending failed");
Log.e("microbridge", "problem sending TCP message", e);
}
}
});
Does anybody have a sugestion what the problem might be? Any suggestions is welcome! if i need to supply more information please say so.
Update
Thanks you all for your suggestions! For the onclick function it works! I tried to do the same for the recieve function. This event handler funnction is called when there is data avalable.
When i use the setText function it crashes my ap after a few cycles, in this function i have three settext operations. only the first one is called (then the app crashes). When i change the ordere of these operations then still only the first one is called. Could it be that the app displays the first settext operation but crashes? I use dummy data, so when the eventhandler function is called the actual recieved data is not used, but still the app crashes after the first operation. Does anybody have a sugestion?
On the other side data is send every second.
Below is the onRecieve (event handler)function:
#Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{
Log.e(TAG, "In handler!");
//Control value
ArrayRecieved[0] = 'C';
ArrayRecieved[1] = 'B';
if (data.length < 2){
return;
}
// Set data that has been recieved in array
//ArrayRecieved[0] = data[0];
//ArrayRecieved[1] = data[1];
char Byte1 = (char) ArrayRecieved[0] ;
char Byte2 = (char) ArrayRecieved[1] ;
TextView Xtext = (TextView) findViewById(R.id.xtext);
TextView Ytext = (TextView) findViewById(R.id.ytext);
Xtext.setText(""+Byte2);
Ytext.setText(""+Byte1);
TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");
}
});
TextView has two methods like
TextView.setText(CharSequence) and TextView.setText(int).
1) first method directly assigns a text to TextView which is passed as CharSequence (can be String,StringBuffer,Spannable...)
2) second methods searches for the String resource that you define in Resources with ID passed as parameter.
and you are passing char as parameter. this char is type casted into int and invokes it as TextView.setText(int) and searches for the Resource String with that int ID whose value is not defined in Resources.
type cast char as String like String.valueOf(char) and try once...
The signature for the method you are using takes a CharSequence, hence sequence of characters. Using setText(someEmptyString + Byte1), you create a sequence of characters from the concatenation of someEmptyString (which you would define as "") and Byte1.
set with some change like
Ytext.setText(""+Byte1);
setText() expects string or resource id (int). If you want to display numeric value, you need to convert it to string, i.e.:
setText(String.valueOf(someInt));
Try out as below:
Ytext.setText(""+Byte1);
Xtext.setText(""+Byte2);

Convert number in textview to int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this

Categories