How to generate id in android randomly and programmatically? - android

I'm trying to generate random ids for views as shown in following screenshot.
But it didn't work. It got null.
How should I findViewById ?

use textView.setId(View.generateViewId()) introduced in API 17.

TextView tv = new TextView(this);
This means you're creating the TextView dynamically. So you don't need to do findViewById.
findViewById is used when the view with id is present in xml file.
Remove the TextView cloneTextView = (TextView) findViewById(randomNo) line. Your question is vague, I tried to explain.

Best practices for unique identifiers
Java
String uniqueID = UUID.randomUUID().toString();
Kotlin
var uniqueID = UUID.randomUUID().toString()

I got my own solution...
It should be like that..
Random r = new Random();
randomNo = r.nextInt(1000+1);
TextView textView = new TextView(this);
textView.setId(randomNo);
linearLayout.addView(textView);
int childCount = linearLayout.getChildCount();
for(int i=0;i<childCount;i++){
if(linearLayout.getChildAt(i).getId()==randomNo){
TextView cloneTextView = (TextView) linearLayout.getChildAt(i);
cloneTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
cloneTextView.setText("I'm a clone...!");
linearLayout.removeAllViews();
linearLayout.addView(cloneTextView);
}
}
It works and that's what I want. Thank you all.

Something like this may work.
But I'm not sure about possible performance and memory issues, since it will return an instance of a view (if found). During a little test sequence it never hit an existing id, with other words the first random number was always ok.
private int createUniqueId() {
int id = RandomUtils.nextInt();
while(findViewById(id) != null) {
//id is not unique, try another one...
id = RandomUtils.nextInt();
}
//return unique id
return id;
}

You can create UUID (universal unique identifier) as follow :
String id= UUID.randomUUID().toString();

Related

Android array of ids to reference textViews

I have a screen with 24 TextViews that I want to change values of. It doesn't matter in which order I just need to change the value from every text field. Right now my code is as follows:
textView = (TextView) findViewById(R.id.textView1);
textView.setText(value1);
textView = (TextView) findViewById(R.id.textView2);
textView.setText(value2);
textView = (TextView) findViewById(R.id.textView3);
textView.setText(value3);
textView = (TextView) findViewById(R.id.textView4);
textView.setText(value4);
etc...
The number of TextViews is constant at 24. I am looking for a loop solution however the issue I run into is dynamically getting the R.id.textViewX value id. Is there a simple way to accomplish this so that I can use it in the following manner:
// Somehow get textViewArray of textView id's //
for(int i=0;i<textViewArray.length;i++) {
textView = (TextView) findViewById(textViewArray[i]);
textView.setText(value[i])
}
I'm open to the idea of dynamically creating the textfields in the Activity class but am looking for an XML solution. I'm not sure if this can be done using the arrays class. I've seen this done for #drawables but never for id's
Important to note is that the textView's are NOT in a list.
Use the getIdentifier() method:
for (int i = 0; i < 24; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
TextView textView = (TextView) findViewById(id);
textView.setText("Set text");
}

Android ImageView setImageResource in code

I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
My code (countryCode is the current countryCode in uppercase letters):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can I do this?
One easy way to map that country name that you have to an int to be used in the setImageResource method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
This is how to set an image into ImageView using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
you use that code
ImageView[] ivCard = new ImageView[1];
#override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
you may try this:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

android Iterating through Views by Id

I have a layout the contains 4 TextViews with ids: "Name1", "Name2", "Name3", "Name4"
I would like to iterate on them with a for loop,
is there any way to do this?
something like
for(int i = 1; i <= 4; i++)
{
findViewById(R.id."Name" + i)
}
I know that this code is far from being real, but any help?
Thank you!
Ron
No, you cannot do it like that because R.id.xyz is referencing a static int of a static class. It's not a string that can be concatenated like that. Also, your code ignores the return value of findViewById so it does nothing (though I realize you mentioned the code is far being real, but still an actual use case might help clarify what you're trying to do). R.id."Name" means nothing and will give you a compiler error.
To loop through you can do something like this:
int[] ids = {R.id.foo, R.id.bar};
then
for(int i = 0; i<ids.length; i++) {
View v = findViewById(ids[i]);
}
Sure you can do that sort of. You cannot access an member of R.id using a string literal you must type out the variable name.
R.id."Test" is no good but R.id.Test is fine.
If you examine the type of R.id.XYZ you will find that it is simply an integer. There is no reason why you cannot perform basic arithmetic on id values.
However it doesn't really make sense to do so. When you build your APK the compiler automatically creates a static class called R that contains references to the various resources and assets contained in your APK, such as layouts, drawables, sounds, etc..
Just because you know that the integer value for R.id.button1 is X there is no guarantee that the integer value for R.id.button2 will be X+1, in fact it could be anything.
If you want to create a list of TextViews to iterate over consider adding them to a List and then iterating over the list. Like so:
ArrayList<TextView> list = new ArrayList<TextView>();
list.add( (TextView) findViewById(R.id.textView1) );
list.add( (TextView) findViewById(R.id.textView2) );
list.add( (TextView) findViewById(R.id.textView3) );
list.add( (TextView) findViewById(R.id.textView4) );
int size = list.getSize();
for (int i=0; i< size; i++)
{
TextView tv = list.get(i);
// Do something with tv like set its label to i
tv.setText(Integer.toString(i));
}

Android : ImageView getID(); returning integer

I've set up an onTouch class to determine when one of my 40 buttons is pressed.
The problem I am facing is determining which button was pressed.
If I use:
int ID = iv.getId();
When I click on button "widgetA1"
I receive the following ID:
2131099684
I would like it to return the string ID "widgetA1"
from:game.xml
<ImageView android:layout_margin="1dip" android:id="#+id/widgetA1" android:src="#drawable/image" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
from:game.java
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView)v;
int ID = iv.getId();
String strID = new Integer(ID).toString();
Log.d(TAG,strID);
//.... etc
}
+-+-+-+-+-+-
I other wise works fine, it knows what button you are pressing. I am quite new to this Android JAVA. Let me know if you guys can help me.
Edit - TL;DR:
View v; // handle to your view
String idString = v.getResources().getResourceEntryName(v.getId()); // widgetA1
Original:
I know it's been a while since you posted, but I was dealing with a similar problem and I think I found a solution by looking at the Android source code for the View class.
I noticed that when you print a View (implicitly calling toString()), the data printed includes the ID String used in layout files (the one you want) instead of the integer returned by getId(). So I looked at the source code for View's toString() to see how Android was getting that info, and it's actually not too complicated. Try this:
View v; // handle to your view
// -- get your View --
int id = v.getId(); // get integer id of view
String idString = "no id";
if(id != View.NO_ID) { // make sure id is valid
Resources res = v.getResources(); // get resources
if(res != null)
idString = res.getResourceEntryName(id); // get id string entry
}
// do whatever you want with the string. it will
// still be "no id" if something went wrong
Log.d("ID", idString);
In the source code, Android also uses getResourcePackageName(id) and getResourceTypeName(id) to build the full string:
String idString = res.getResourcePackageName(id) + ":" + res.getResourceTypeName(id)
+ "/" + res.getResourceEntryName(id);
This results in something to the effect of android:id/widgetA1.
Hope that helps!
You cannot get that widgetA1 string...You will always get an integer. But that integer is unique to that control.
so you can do this to check, which button is pressed
int ID = iv.getId();
if(ID == R.id.widgetA1) // your R file will have all your id's in the literal form.
{
}
Xml
android:tag="buttonA"
Src
Button.getTag().toString();
Of course you can get widgetA1, simply do:
ImageView iv = (ImageView)v;
int id = iv.getId();
String idStr = getResources().getResourceName(id);
It should give you your.package.name:id/widgetA1, then do what you want with that string.
We will get the Integer value corresponds to the views id. For finding on which button you are clicking, better to use tags. you can set tag in the layout xml file and can compare which item you have clicked using.
<Button
android:id="#+id/btnTest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:tag="btntestTag"/>
This is sample usage.
i think that you can use this
try it
ImageView imgView = new ImageView(this);
String imgName = "img"//in your case widgetA1
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
For the implementation you could use the hint attribute to store the button name, which is accessible. For example in the button code (.xml file) use the following line:
android:hint="buttonName"
Then in the onClicked function (.java file), write the following to get the hint:
String hint = ((Button)v).getHint().toString(); //v is the view passed onClick

android dynamical binding

I want to work dynamically therefore I want to bind text views dynamically I think an example would explain me the best
assuming I want to bind 7 image views i can do it like this :
Country = (EditText)findViewById(R.id.CountryEditText);
City = (EditText)findViewById(R.id.CityEditText);
LivinigCreture = (EditText)findViewById(R.id.LivingCretureE);
Nature =(EditText)findViewById(R.id.NatureEditText);
Inanimate = (EditText)findViewById(R.id.InanimateEditText);
KnowenPersonality = (EditText)findViewById(R.id.KnowenPersonalityEditText);
Occupation = (EditText)findViewById(R.id.OccupationEditText);
but lets change 7 with NUMOFFILEDS as a final where i want to do the previous ?
myImages = new ImageView [7];
for (int i = 0; i<7;i++,????)
myImages[i] = (ImageView)findViewById(R.id.initialImageView01);
notice : in my R file the R.id.initialImageView01 - R.id.initialImageView07 are not generate in a cont gap between them therefore I don't know how to make this architecture possible .
and if there's a way can someone show me an example how to work dynmiclly (like using jsp on android combined way or something ?)
id its possiable to do so constant times is it possible to build an the same xml constant num of times like jsp does
thank u pep:)
You can store the IDs themselves in an array at the beginning of your Activity; that way you'll only need to write them once and you can index them afterwards.
Something like:
int[] initialImageViewIds = {
R.id.CountryEditText,
R.id.CityEditText,
R.id.LivingCretureE,
R.id.NatureEditText,
R.id.InanimateEditText,
R.id.KnowenPersonalityEditText,
R.id.OccupationEditText
};
Then you can access them with:
myImages = new ImageView [7];
for (int i = 0; i<7;i++) {
myImages[i] = (ImageView)findViewById(initialImageViewIds[i]);
}
If that's not enough and you really want to get the IDs dynamically, I suppose you can use reflection on the R.id class, possibly with something like R.id.getClass().getFields() and iterate on the fields to check if their names interest you. Check reference for the Class class, too.

Categories

Resources