getIdentifier doesn't give the correct id - java

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())

Related

Image of an ImageView to int Android Studio

Good friends, how can I pass the image of an ImageView to int in andrid studio to be able to save it in a BD, I load the image from a database in this way:
Intent intent = getIntent ();
Bundle b = intent.getExtras ();
AdminSQLiteOpenHelper adminPlants = new AdminSQLiteOpenHelper (this, "Plants", null, 1);
SQLiteDatabasePlantsDatabase = PlantsPlants.getWritableDatabase ();
Cursor file_plants = BaseDeDatosPlantas.rawQuery
("SELECT * from species where commonname = '" + b.getString ("name") + "'", null);
if (file_plantas.moveToFirst ()) {
tvNameE.setText (b.getString ("name"));
tvSpeciesE.setText (file_plants.getString (2));
tvDescripcionE.setText (file_plantas.getString (4));
imgFotoE.setImageResource (file_plantas.getInt (5)); // Here I send the image to the ImageView
}
PlantsDatabase.close ();
In the app, the image is changed for another on the device, now as I do the opposite, get the image from the ImageView and pass it to an int and thus be able to save it in BD again.
public void SaveE (View view) {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper (this, "Plants", null, 1);
SQLiteDatabase DataBase = admin.getWritableDatabase ();
Database.execSQL ("update species set description = '" + tvDescripcionE.getText () + "', photo =" + imageResource
+ "where CommonName = '" + tvNameE.getText () + "';"); // This is where I need the int of the image
Database.close ();
}
As ImageView can host any type of Drawable, not just one specified by a resource id, there's no API to get the resource id back out of the ImageView.
That said, you could always save the resource id to the ImageView as a tag when you assign it:
int resourceId = file_plantas.getInt (5);
imgFotoE.setImageResource (resourceId);
imgFotoE.setTag(resourceId);
And then you could retrieve it later:
int resourceId = (int) imgFotoE.getTag();

How to find and prefix all phone number in Contacts Android?

Sorry for the bad english!
I want to scan all contacts 's phone number and prefix them. However my code is not useful. It missed a lot of phone numbers when reading contacts. Help me plz!
`
String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
ContentResolver cr =getContentResolver();
Cursor cursor=cr.query(ContactsContract.Contacts.CONTENT_URI, columns,null,null,null);
cursor.moveToFirst();
while(cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(!(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)).endsWith("0")) )
{
Cursor phones = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
if(phones.getCount() > 0)
while (phones.moveToNext())
{
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[ \\-().]", ""); //this is phone number
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
String idIndex = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
switch (type)
{
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
//prefix number function and write contacts here.
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
//prefix number function and write contacts here.
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
//prefix number function and write contacts here.
break;
//some other type here...
}
}
phones.close();
}
}
cursor.close();`
No need for a loop-within-loop here, just one query that goes over all numbers in the Contacts DB:
String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, Phone._ID };
Cursor phones = cr.query(Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String number = phones.getString(0).replaceAll("[ \\-().]", ""); //you can instead use Phone.NORMALIZED_NUMBER if you're using a high-enough API level
int type = phones.getInt(1);
long id = cursor.getLong(2);
Log.v("LOG", "got phone: " + id + ", " + number + ", " + type);
prefixNumber(id, number, type);
}
phones.close();
`sssss
public void updatePhoneNumber(ContentResolver contentResolver, long rawContactId, int phoneType, String PhoneNumber) {
// Create content values object.
ContentValues contentValues = new ContentValues();
// Put new phone number value.
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, PhoneNumber);
// Create query condition, query with the raw contact id.
StringBuffer whereClauseBuf = new StringBuffer();
// Specify the update contact id.
whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
whereClauseBuf.append("=");
whereClauseBuf.append(rawContactId);
// Specify the row data mimetype to phone mimetype( vnd.android.cursor.item/phone_v2 )
whereClauseBuf.append(" and ");
whereClauseBuf.append(ContactsContract.Data.MIMETYPE);
whereClauseBuf.append(" = '");
String mimetype = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
whereClauseBuf.append(mimetype);
whereClauseBuf.append("'");
// Specify phone type.
whereClauseBuf.append(" and ");
whereClauseBuf.append(ContactsContract.CommonDataKinds.Phone.TYPE);
whereClauseBuf.append(" = ");
whereClauseBuf.append(phoneType);
// Update phone info through Data uri.Otherwise it may throw java.lang.UnsupportedOperationException.
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Get update data count.
int updateCount = contentResolver.update(dataUri, contentValues, whereClauseBuf.toString(), null);
}`

How i can get image id from ImageView?

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);

Initializing variable in for-loop

I have code like this:
TextView wyniszczenie_zakres_bmi = (TextView)t.findViewById(R.id.wyniszczenie_zakres_bmi);
TextView wychudzenie_zakres_bmi = (TextView)t.findViewById(R.id.wychudzenie_zakres_bmi);
TextView niedowaga_zakres_bmi = (TextView)t.findViewById(R.id.niedowaga_zakres_bmi);
Can I do something like this?
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan){
TextView s + _zakres_bmi = (TextView)t.findViewById(R.id. + s + _zakres_bmi);
}
I know it's not work but is there any solution for this?
Try this:
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
// Do something with myTextView
}
If you need to save the textView references for later rather than acting on them immediately, then put myTextView into an array or hashtable after it's assigned.
Hashtable textViews = new Hashtable<String, TextView>();
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
textViews.put(s + "_zakres.bmi", myTextView);
}
// When you need to get one of the TextViews:
TextView tv = textViews.get("niedowaga_zakres.bmi");
// Do something with tv.

setImageResource from a string

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() );

Categories