How to dynamically define name of R.drawable [duplicate] - android

This question already has answers here:
How to get the image from drawable folder in android?
(4 answers)
Closed 9 years ago.
Is there a way to generate R.drawable.... name on the fly? I want to set a background image with a dynamically generated name ( which is already usable as R.drawable.example_graphic)
So i want to find a way to assign a String to $ABC -> btn.setBackgroundImage(R.drawable.$ABC);
I don't want to create a new drawable, i want to use the existing one.

Yes. Drawables are constants at compile time: you know exactly what exists. So, in your Application object, create a map:
public static final Map<String, Integer> NAMED_RESOURCES;
static {
Map<String, Integer> m = new HashMap<String, Integer>();
m.put(KEY1, R.drawable.ABC);
m.put(KEY2, R.drawable.DEF);
// ...
NAMED_RESOURCES = Collections.unmodifiableMap(m);
}
now you can:
btn.setBackgroundImage(Application.NAMED_RESOURCES.get($ABC));

i have found the solution, as #CommonsWare has shared.
getContext().getResources().getIdentifier("flags_"+country, "drawable","mypackage")
However, it may require cacheing as it uses reflection.
So, creating a static HashMap to keep the ResourceName and it's result from getIdentifier function (integer) seems to be a good idea; further usages for the same ResourceName will just get the value from HashMap instead of using the reflection again.

Related

Trying to store mutableListOf<String> to SharedPreferences but cannot set default value

Ultimately I am trying to store an Int Array in Shared Preferences but I know Kotlin doesn't support that. So I am converting my Int Array to a String Array using the method here:
How can I store an integer array in SharedPreferences?
My issue is that I am struggling to put in a default value for the getStringSet method:
private fun loadIntScoreArray() {
val prefs = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE)
//TODO: Load the String array
var default = emptyList<String>()
avgScoreArrayString = prefs.getStringSet(AVG_SCORE_ARRAY, default)
}
However default is not an acceptable object in the prefs.getStringSet(AVG_SCORE_ARRAY, default) line. The error is confusing because it seems contradictory:
Required: MutableList
Found: (Mutable)Set!
Required: (Mutable)Set!
Found: MutableList
There is few things you need to know. Since API 11 you can only store plain objects or sets to shared preferences. You can convert your list to set, but it can be lossy conversion in your list contain duplicates.
If you want to use sets you should call it like this:
//to get
prefs.getStringSet(AVG_SCORE_ARRAY, emptySet<String>()))
//to set
prefs.edit().putStringSet(key, AVG_SCORE_ARRAY)
The other way is to join array to a single string using join operation. Here is a doc for you https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to.html
To be honest both of these ways are not the perfect solutions. If it is production application and I recommend using persistance library like Room, Realm etc.
Hope it helps.
Edit.
If you are hundred percent sure you are going to have 5 ints stored (and it is not gonna change in a near or distant future), using database could be overkill. I recommend using joining to single string and storing it as single string or just store 5 independent int values. There is no point in complicating simple things.

Android: how to parameterize which resource to use at runtime? [duplicate]

This question already has answers here:
Access resource string by string name in array
(2 answers)
Closed 7 years ago.
Think about a list of parameters and their respective intervals of discrete integer values:
a[1-N], b[1-M], c[1-K], d[1-J]
a, b, c, d are the variables while between square brackets there are intervals of their possible values.
At runtime if they are
a=1, b=2, c=3, d=5
then I'd like to get the resource with
name = R.string.string_1_2_3_5
Is it possible?
I wouldn't want to make a series of cascade switches for each variable to finally pick a resource. I know this could work but is there another way?
You can use Java reflection like in here.
If you need to retrieve strings like that more than once, in order to get fast access, you should first construct a hashtable with the field names of R.string as keys (maybe when you launch the app).

Storing and retrieving values from hashmap [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i'm a beginner to Android development .... can u please tell me if this is this the correct way to declare an hashmap and add it to the arraylist?
Button createagendaButton = (Button) dialog.findViewById(R.id.button2);
createagendaButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("agendaTitle", edit_agendaTitle.getText().toString());
map.put("presenterName", edit_presenterName.getText().toString());
mylist.add(map);
}
});
It seems you are new to android
For starters why dont you go through samples in android sdk
sdk-path/samples/api-version/
and this link
To cheer you up try these that will solve your problems
1. get value from edittext edittext.getText();
2. store values in hashmap as hashmap.put(key,value)
3. instead of going for hashmaps, reconsider the type of data you are storing and try SparseArray if it suits your needs. Sparse arrays are well optimized and good at performance though they are very different in comparison
4. sqlite can store only some types of data. For sqlite on android try this
5. For ensuring proper functioning of your app across devices and resolutions, refer best practices and life cycles of different components used in your app. Also since you are using sqlite, prefer singleton pattern
The following code will allow you to store the values into the hashmap by using the key => value convention.
Map mMap = new HashMap();
mMap.put("FirstName", firstNameInput.getText().toString());
mMap.put("Surname", surnameInput.getText().toString());
mMap.put("Gender", genderInput.getText().toString());
Note, you will need to change the variable name before .getText() to that of your EditText variable names
http://developer.android.com/reference/java/util/HashMap.html might be of some use!

How to clear a hashmap in Android [duplicate]

This question already has answers here:
Map.clear() vs new Map : Which one will be better? [duplicate]
(7 answers)
Closed 9 years ago.
Below is the reference code
public static Map<String, Long > map1 = new HashMap<String, Long >();
if i call map1.clear() , will all elements of hashmap become eligible for GC or do i need to set every element of the map explicitly to null ?
hashmap.clear() just clears all the data of the HashMap to make it reusable again.Here reusable means the same object can be reused again.So I dont think there is any role of GC here.

How to extract the string variable in android? [duplicate]

This question already has an answer here:
How to extract this string variable in android?
(1 answer)
Closed 9 years ago.
String test=["1","Low-level programming language",true]
Here i want to extract this string value and as i need to get only second value like "Low-level programming language".How to get this value using string functions in android?
Per your comment, I'm assuming that you have a single string that contains the entire text (including the brackets). In general, splitting comma-separated values is a fairly tricky process. For your specific string, though, it's kind of easy:
String test = "[\"1\",\"Low-level programming language\",true]";
String[] pieces = test.split(",");
String middle = pieces[1];
// now strip out the quotes:
middle = middle.substring(1, middle.length() - 1);
In general, you might want to look at using a general CSV parser like Apache Commons CSV or openCSV.
Alternatively, if this is JSON data (which looks more likely than CSV), take a look at using one of the Java JSON libraries listed here (scroll down the page to see the list).

Categories

Resources