Have code like this:
case R.id.button:
int id=randImage();
imgView1.setImageResource(id);
public int randImage() {
Random rand= new Random();
int randomNumber=rand.nextInt(24)+1;
String randomImage="img"+randomNumber;
int id = getResources().getIdentifier(randomImage, "drawable", getPackageName());
return id;
}
case R.id.imgView1:
Intent i= new Intent();
i.putExtra("imgId", id); //IS UNREACHABLE
How i can get drawable id after set ?
Not sure if you can recover it after setting, but you can associate a tag with the component:
int id = randImage();
imgView1.setImageResource(id);
imgView1.setTag(id);
And when you need to get the id you simply:
int id = imgView1.getTag();
Save it first:
int Id=randImage();
imgView1.setImageResource(Id);
Related
So I have more imageView looking like this:
imageView1
...
imageView8
int defendPosition = defend(); // This is random generated number from 1-8;
String imageID = "imageView" + defendPosition;
int resID = getResources().getIdentifier(imageID, "id", getPackageName());
Log.i("resID", " "+ resID); // it logs value is 0
secondMove = findViewById(resID);
secondMove.setTranslationY(-1500); // When I try to run this, it says null refference;
I need to get the correct id
try
int resID=this.getResources().getIdentifier(imageID,"id",getActivity().getPackageName())
I have some xml data I am looping through. I would like to store each "entry" in an array spot in order to see it with an intent.putExtras(). My data has 3 elements: latlon,name,description. I would like to put each in my array. So I am setting it up like so: markerInfo[i][0] = Loc; etc... like so:
final List<XmlDom> entries = xml.tags("Placemark");
int i = entries.size();
int j=0;
for (XmlDom entry : entries) {
XmlDom lon = entry.tag("longitude");
XmlDom lat = entry.tag("latitude");
XmlDom name = entry.tag("name");
XmlDom desc = entry.tag("description");
String cdatareplace = desc.toString();
String description = cdatareplace.replace("<![CDATA[", "");
description = description.replace("]]>", "");
final String firename = name.text();
final String firedesc = description;
String geoLon = lon.text();
String geoLat = lat.text();
String coor = lat + "," + lon;
// Log.e("COORS: ", coor);
double lati = Double.parseDouble(geoLat);
double lngi = Double.parseDouble(geoLon);
LOCATION = new LatLng(lati, lngi);
String Loc = LOCATION.toString();
String[][] markerInfo = new String[i][3];
markerInfo[j][0] = Loc;
markerInfo[j][1] = firename;
markerInfo[j][2] = firedesc;
Log.e("MARKERINFO",markerInfo[j][0]);
Log.e("MARKERINFO",markerInfo[j][1]);
Log.e("MARKERINFO",markerInfo[j][2]);
map.addMarker(new MarkerOptions()
.position(LOCATION)
.title(markerInfo[j][1])
.snippet(markerInfo[j][2])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.wfmi_icon48)));
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// Show full description in new activity.
// fireDesc(arg0.getTitle(), arg0.getSnippet());
Intent i = new Intent(Map.this, MapSingleActivity.class);
i.putExtra("name", arg0.getTitle())
.putExtra("description", arg0.getSnippet())
.putExtra("lat", arg0.getPosition().latitude)
.putExtra("lon", arg0.getPosition().longitude);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
j++;
}
I am getting array index out of bounds. I figured if I filled it with the entries.size() that would not be the problem, so maybe i am not telling it how big correctly?
Thanks for any help
You need to make sure that the second dimension is also big enough
Fix it by changing the declaration of markerInfo to:
String[][] markerInfo = new String[i][3];
At the moment you are only creating i empty String arrays. With the above code you will create i arrays that can hold three String objects each.
Also, at the moment you are writing to the last location which is outside of the array bounds.
You need to change it to write to an available location. If you are trying to write to the last available location that would be i-1.
markerInfo[i-1][0] = Loc;
markerInfo[i-1][1] = firename;
markerInfo[i-1][2] = firedesc;
Looking at your code however, it seems like you may want to declare markerInfo outside of the loop and create a counter variable that you increment at each step of the loop.
Second size of the array is 0 - new String[i][0]. Then you try to insert something on position 0,1,2, which are not available.
Even if you write new String[i][3], then the maximum index is i-1.
So, I have code that's generating ID's for a number of elements using an AtomicInteger that's set by default at Integer.MAX_VALUE and is decremented from there with each view that gets assigned an ID. So the first view with a generated ID would be Integer.MAX_VALUE - 1, the second would be Integer.MAX_VALUE - 2, etc. The problem I'm afraid of is a collision with IDs generated by Android in R.java.
So my question is how can I detect if an ID is already in use and skip it when I'm generating the IDs. I'm only generating at most 30 IDs so this isn't a huge priority nut I'ld like to make this as bug free as possible.
The following code will tell you if the identifier is an id or not.
static final String PACKAGE_ID = "com.your.package.here:id/"
...
...
int id = <your random id here>
String name = getResources().getResourceName(id);
if (name == null || !name.startsWith(PACKAGE_ID)) {
// id is not an id used by a layout element.
}
I modified Jens answer from above since, as stated in comments, name will never be null and exception is thrown instead.
private boolean isResourceIdInPackage(String packageName, int resId){
if(packageName == null || resId == 0){
return false;
}
Resources res = null;
if(packageName.equals(getPackageName())){
res = getResources();
}else{
try{
res = getPackageManager().getResourcesForApplication(packageName);
}catch(PackageManager.NameNotFoundException e){
Log.w(TAG, packageName + "does not contain " + resId + " ... " + e.getMessage());
}
}
if(res == null){
return false;
}
return isResourceIdInResources(res, resId);
}
private boolean isResourceIdInResources(Resources res, int resId){
try{
getResources().getResourceName(resId);
//Didn't catch so id is in res
return true;
}catch (Resources.NotFoundException e){
return false;
}
}
You can use Java Reflection API to access whatever elements are present in an object of R.id Class.
The code is like this:
Class<R.id> c = R.id.class;
R.id object = new R.id();
Field[] fields = c.getDeclaredFields();
// Iterate through whatever fields R.id has
for (Field field : fields)
{
field.setAccessible(true);
// I am just printing field name and value, you can place your checks here
System.out.println("Value of " + field.getName() + " : " + field.get(object));
}
You can use View.generateViewId() which requires min API 17.
From sdk
Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.
Just an idea ... you could use the findViewById (int id) to check if the id is already in use.
I am trying to get the content of a single array item.
In my code, I want the value of String suitId to have the content of suitIdArray[getSuitId];, but it doesn't get the content.
Could you please help me to see what is wrong. Here is my code...
Object item1 = spinner1.getSelectedItem();
int getDragId = spinner1.getSelectedItemPosition();
String suitId;
if(!item1.equals("Choose size")) {
suitId = suitIdArray[getSuitId];
}
else {
pSuit = null;
}
Is is not working because you have a variable getdragid but you're using getsuitid in the array? ie, should it be the following...
Object item1 = spinner1.getSelectedItem();
int getdragtid = spinner1.getSelectedItemPosition();
if(!item1.equals("Choose size"))
{
suitid = suitidarray[getdragtid]; // I changed this line
}
else if(item1.equals("Choose size"))
{
psuit = null;
}
Otherwise, I'm not really sure what you're trying to do?
I would like to change the imageview src based on my string, I have something like this:
ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);
Of course it doesnt work. How can I change the image programmatically?
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
use:
imageView1.setImageResource(getImageId(this, correctAnswer);
Note: leave off the extension (eg, ".jpg").
Example: image is "abcd_36.jpg"
Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);
I don't know if this is what you had in mind at all, but you could set up a HashMap of image id's (which are ints) and Strings of correct answers.
HashMap<String, Integer> images = new HashMap<String, Integer>();
images.put( "poland", Integer.valueOf( R.drawable.poland ) );
images.put( "germany", Integer.valueOf( R.drawable.germany ) );
String correctAnswer = "poland";
imageView1.setImageResource( images.get( correctAnswer ).intValue() );