Calling a Resource by a string? - android

Here's the setup. I have a spinner, and each item in the spinner is associated with their own StringArray. I want to streamline the process of loading the StringArray when an item is selected in the spinner without using a bunch of if statements for each item.
The StringArray has the same name as the spinner item's text
Drawn out it would look like this:
String cat = parent.getItemAtPosition(pos).toString(); //Selected Spinner item (Category)
...
String catStringArray = "R.array." + cat;
listdata = getResources().getStringArray(catArray); //Get the StringArray
is there a way to do this correctly?
--Edit--
#EboMike
Your answer sent me on a hunt and ran into this which I'm now using:
Class res = R.array.class;
Field field = res.getField(selectedCategory);
int saId = field.getInt(null);
String[] myList = getResources().getStringArray(saId);

That's not a great approach. It's slow. It'd be better to have an internal integer array with all the R.string IDs or something similar.
If you really insist on using a string-based approach, use Resources.getIdentifier(). It's technically not a big deal if you only do it once.

Related

ListView with Strings: Cannot get it to update the text of a button

So I'm wanting to create a ListView of buttons in Kotlin. When the view is created, it makes an API request and gets the names of the devices registered to the account and puts it into an array of strings called deviceNames.
Below is my code for trying to get the button to work. I used the tutorial that is found here, but when I try to compile it I get an error that the ArrayAdapter function doesn't have an input with the types that they gave. I have a button with the id of deviceButton in the view, but it can't find it for some reason.
val adapter = ArrayAdapter(this, R.layout.deviceButton, deviceNames)
val listView: ListView = findViewById(R.id.deviceList)
listView.setAdapter(adapter)
The declaration of deviceNames is below. Inside of the for loop, the JSON array that was received from the API request is separated into its different objects and the property name is put into the deviceNames array.
var deviceNames = Array<String>(6) {""}
for (i in 0 until jsonArray.length()) {
val device = jsonArray.getJSONObject(i)
deviceNames[i] = device.get("name") as String
println(deviceNames[I])
}
Sorry if this is a simple problem, I'm really new to Kotlin and Android.
Thanks!

how to remove a string from arraylist of strings, ANDROID

I created an arraylist of strings
List<String> textArray = new ArrayList<String>();
and then I added the strings(which I am getting from edittext) to textArray as follows
String text = editText1.getText().toString();
textArray.add(text);
Now I created a button and need to remove the string from the array when the button is clicked.But i dont know what to do.
I know for arrays of bitmaps we clear a bitmap from array using recycle but Please suggest me how to remove or clear the string from arraylist.
You can call one of:
to remove all entries
textArray.clear();
to remove from a specific position (e.g. first item)
textArray.remove(0);
to remove a specific string (that equals yours)
textArray.remove("myString");
Try this..
Getting position from the textArray array list
int pos = textArray.indexOf(text);
and then remove from the string position
textArray.remove(pos);
because we cannot directly remove the string. we can remove the string contains position.
You can do it with more then one way as per your need.
textArray.clear();
It will clear whole ArrayList.
If you want to remove only some specifis data from index then,
textArray.remove(INDEX TO REMOVE);
Try This
String text = editText1.getText().toString();
textArray.add(text);
to remove
textArray.remove(text);

Getting value of choosed option in Spinner

I want to get value of choosed option in Spinner.
I know, I can get this from setOnItemSelectedListener, but I don't want to use this.
I have this:
String spinner1odp = spinnerSubject.getSelectedItem().toString();
But result of this code is: android.database.sqlite.SQLiteCursor#40f828e8. I want to get String, not something like that :/
I think you are popping up Spinner from database.
So considering that you will have to get the selected index first and fetch the required data from the Cursor:
Code Snippet :
int position = mySpinner.getSelectedItemPosition();
Cursor cursor = (Cursor) myAdapter.getItem(position);
String myText = cursor.getString(cursor.getColumnIndex(KEY_NAME));
Further Reference : Android Spinner Selected Item
By using this code you can get...
String value= (String)spinnerSubject.getItemAtPosition(spinnerSubject.getSelectedItemPosition());

update My Spinner from SQlite Database

I FOUND A SOLUTION FOR RESTORING MY VALUES, SEE MY NEW VERSION of populateFields()
Okay so I have been reading through all the Spinner and SQlite posts on here and cannot seem to find a good answer for what I am looking for so I am posting this scenario.
My app has two screens and uses the sqlite database on my device saving a name and weight fields from editTexts as strings like so
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
and I have two spinners as follows
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
Then I call this to add to the database
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
Here is where my issue is, upon someone selecting to create a new exercise my app crashes because it is trying to populate a spinner incorrectly. Here is what I have currently.
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate()
and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}
The way to set a Spinner to a value, not a position, depends on what adapter you are using.
ArrayAdapter, this one is easy:
int position = adapter.getPosition(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinReps.setSelection(position);
SimpleCursorAdapter, this one is a little harder:
String match = exercise.getString(exercise.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(-1);
int columnIndex = cursor.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS);
while(cursor.moveToNext()) {
if(cursor.getString(columnIndex).equals(match))
break;
}
spinReps.setSelection(cursor.getPosition());
If you are using a different type of adapter and can't modify the code above to fit it, let me know. Hope that helps!

dynamic autocomplete textview displayes slowly,how to display faster?

I have written some code for autocompletetextview in custom dialog box.When typing some text that text dynamically search into the hashmap.This hashmap is with large lines of text.It works.But slowly giving me result.
AutoCompleteTextView searchText = (AutoCompleteTextView)searchDialog.findViewById(R.id.searchText);
if(searchText.getText()!=null){
// searchString = searchText.getText().toString().trim();
String[] autoList = getAutoCompletWords(searchText.getText().toString().trim());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx,android.R.layout.simple_dropdown_item_1line,autoList);
searchText.setAdapter(adapter);
}
private String[] getAutoCompletWords(String text){
Set<String> wordsSet = new TreeSet<String>();
Pattern wordPattern = Pattern.compile("\\b"+text+"\\w+",Pattern.CASE_INSENSITIVE);
Matcher matcher = wordPattern.matcher(bookContentMap.values().toString());
while(matcher.find()){
wordsSet.add(matcher.group());
}
String[] wordsArray = wordsSet.toArray(new String[0]);
return wordsArray;
}
If I take thread for above code it is giving me thread handler exception.Please give me an idea for quick response of list on autocomplettext.
Rajendar Are
To know for sure which bits are fast and which are slow, you need to use Android's profiler. Here are two things worth investigating, they're probably the largest resource drain:
You're compiling a regular expression each time a key is pressed, this is very slow. A better option would be to populate a database and query it instead.
You're creating both a TreeSet and an Array each time a key is pressed, which probably hurts.
Converting bookContentMap's values to a String is probably quite processor intensive. Consider caching this value.

Categories

Resources