This question already has answers here:
Access resource string by string name in array
(2 answers)
Closed 7 years ago.
I have an Array of countries (Strings) - (Comes from a webservice) as well as a corresponding list of Drawables which are their flags - (In the drawables folder)
The Drawables are labelled "cape_verde" or "canada" but when the names come down from the webservice they come down as "Cape Verde" or "Canada".
When I call the webservice I do a lowercase conversion and replace some characters as seen in the code below:
String lowerCaseName = countryNameInArray.countryName.toLowerCase();
String replacedCountryName = lowerCaseName.replaceAll(" ", "_");
My thought was that I can some how set the
R.drawable.replacedCountryName
but obviously it cant take Strings as its requires an int.
EDIT:
public View getCustomView(int position, View convertView, ViewGroup parent) {
countries = res.getStringArray(R.array.countries);
/********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
View row = inflater.inflate(R.layout.country_drop_down_rows, parent, false);
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (countryDropDownItem) data.get(position);
TextView label = (TextView) row.findViewById(R.id.spinner_country_textview);
ImageView country = (ImageView) row.findViewById(R.id.spinner_county_flag_imageview);
if (position == 0) {
// Default selected Spinner item
label.setText("South Africa"); //get the country text
country.setImageResource(R.drawable.south_africa);
} else {
String lowerCaseName = countries.toString().toLowerCase();
String replacedCountryName = lowerCaseName.replaceAll(" ", "_");
// Set values for spinner each row
label.setText(tempValues.countryName); //get the country text
country.setImageResource(res.getIdentifier(replacedCountryName, "drawable", "com.app.app" ));
}
return row;
}
Has anyone got an idea how I can go around this?
Thanks
Try this:
ImageView iw= (ImageView)findViewById(R.id.imageView1);
int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
iw.setImageResource(resID);
drawableName is your file/image name, try to store in /src/asset/image.png
getResources().getIdentifier(
"imagename", "drawable", "com.package.application")
Related
When exporting my array list item, Im getting this error. In the first place it works but when updating my code adding data on my array it crashed my app and this error appear, do you have any idea why this happening?
java.lang.ClassCastException: android.text.SpannableStringBuilder
cannot be cast to java.lang.String
I'm getting error in this line 312 after if statement -
mEdit1.putString("Status_" + i,list_items.get(i));
I've already tried put empty string on my list like this
""+list_items.get(i));
but it's not working :(
ArrayList<String> list_items = new ArrayList<String>(); //declared global
ArrayAdapter arrayAdapter; //declared global
public boolean export_data()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putString("Status_","");
mEdit1.apply();
mEdit1.putInt("Status_size", list_items.size());
for(int i=0;i<list_items.size();i++)
{
mEdit1.remove("Status_" + i);
if (list_items.get(i) !=null){
mEdit1.putString("Status_" + i,list_items.get(i));
String[] separated = list_items.get(i).split(":");
mEdit1.putString("Status_" + i, separated[0]);
}
else{
Toast.makeText(getApplicationContext(), "List is Empty", Toast.LENGTH_SHORT).show();
}
}
return mEdit1.commit();
}
Adding item on ArrayAdapter
public void refreshInbox(){
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
ContentResolver cResolver = getContentResolver();
Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
int indexBody = smsInboxCursor.getColumnIndex("body");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
do{
String strbody = smsInboxCursor.getString( smsInboxCursor.getColumnIndex("body") );
if(strbody.contains("Notifier,") && strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
String[] sep = separate.split(" : ");
String sep1 = sep[1];
String finals = separate.replace(sep1, "<u>"+"<b>" + sep1 +"<b>"+ "</u>");
arrayAdapter.add(Html.fromHtml(finals));
}
else if(strbody.contains("Notifier,") && !strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
arrayAdapter.add(separate);
}
}while (smsInboxCursor.moveToNext());
}
Assuming you want to keep displaying HTML in your list view, the problem is that the objects that ArrayAdapter is adding list_items are not Strings. That means, you have to change how you define the list_items variable from String to a more generic character sequence type:
ArrayList<CharSequence> list_items = new ArrayList<>();
The CharSequence interface does not have a "split" method though. To be able to use "split", you'll need to call toString to get a regular string:
String[] separated = list_items.get(i).toString().split(":");
It would also help if you used the type parameter with your ArrayAdapter. Using the type parameter would have made it harder (if not impossible) to make this mistake.
ArrayAdapter<CharSequence> arrayAdapter;
... inside the method ...
arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, list_items);
list_items.get(i));
Looks like you might be attempting to put an unusual type of string into the list...
see: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
I'm not an android dev but I suspect there are some "useful" shortcuts it provides in an attempt to make your life easier, that would probably trip you up.
Groovy's default string was a GString rather than a String. That tripped me up a number of times before I got used to it.
The error is with this line in refreshInbox()
arrayAdapter.add(Html.fromHtml(finals));
Html.fromHtml does't return String but instead it retuns Spanned
But you need to pass String to add() on adapter
To fix this convert it to String
adapter.add(Html.fromHtml(finals).toString()); // this will return plain text without html tags
or
adapter.add(finals); // this will be having HTML tags from this you can set text on views later
I have the following for-each loop:
for(DataSnapshot data: dataSnapshot.getChildren()){
TextView textview = (TextView) findViewById(R.id.textview);
String message = data.getKey().toString();
textview.setText(message);
}
Now there are different textviews with ids textview1 textview2 textview3..etc (can grow and shrink). How do I do that in the for-each loop though? Using some counter and somehow concat it to the variable?
I want the different messages to display in the different textviews
You will have to modify your code like this:
int i = 1;
for(DataSnapshot data: dataSnapshot.getChildren()){
int id = getResources().getIdentifier("textview" + i, "id", getPackageName());
TextView textview = (TextView) findViewById(id);
String message = data.getKey().toString();
textview.setText(message);
i++;
}
with getResources().getIdentifier("textview" + i, "id", getPackageName()); you find the integer id of a View by using its name id.
You may have to supply a Context to getResources() like:
context.getResources().getIdentifier("textview" + i, "id", context.getPackageName());
if this code is not inside an activity.
I have a listView with custom adapter, where I have an checkBox and TextView, and when I select some CheckBoxes, I'm adding them into bundle and send into another fragment. In that fragment I have a simple TextView, where I need to get the value from bundle and show in that TextView. But the problem is, that when I'm getting the selected values from bundle and set in TextView, it shows only the last value. How can i solve this? Thank you.
Here the fragment where I'm adding the selected values into bundle.
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Profession> professionList = dataAdapter.getProfessionList();
ArrayList<String> getProfessions = new ArrayList<>();
personalInfoFragment = new PersonalInfoFragment();
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
}
}
replaceFragment();
}
});
Ok watch here. the PersonalInfoFragment is the fragment where i need to send the values. And the replaceFragment method replaces the fragment. I done debug and I'm adding the selected values into bundle successfully.
On nextButton click it saves the selected data into bundle and replaces the fragment.
Now here's the fragment where I need to get the bundle and show in textView.
Bundle bundle = getArguments();
if (bundle != null) {
ArrayList<String> getProfessionName = bundle.getStringArrayList("String");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
profession_text.setTextColor(Color.BLACK);
profession_text.setText(getProfessionName.get(i) + ",");
}
}
}
ProfessionText is my textView where I need to set the values. But in that textView shows only the last item from bundle. How to fix this? Thank you for reading.
You can change your code like,
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
}
}
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
replaceFragment();
And in next fragment,
profession_text.setTextColor(Color.BLACK);
profession_text.setText("");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
String txt = profession_text.getText().toString() + getProfessionName.get(i) + ", ";
profession_text.setText(txt);
}
}
From what i can see..u need a list of values to be displayed right..what is happening here is on each iteration you set a new value for professional text which overwrites the one that was there previously..thats why you are seeing the last value..i think if you want a list of textviews you have to create a new textview in the loop..which in this case you are better off using a listview or recycler view.
Hello i am building one app which will take google profile name and then it will be displayed in another activity as EditText.
ActivityGoogle
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
textView_name.setText(personName);
textView_email.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ 400;
new LoadProfileImage(imageView_profile_image).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
any idea how to take name from this and display it in EditText
ActivityUser
profilename = (EditText)findViewbyId(R.id.profilename);
(I posted it as a comment but I think it solved the issue, so I post it as answer and add some explanation)
Have a look at these links : 1 2 3. A Bundle is exactly what you need.
This code is taken from one of the links and it's what you need. It saves a value on the Bundle:
ActivityGoogle
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value); // <-- key is the same
Then, on your ActivityUser add the following (note that key variable must be the same in both Activity):
ActivityUser
String value = getIntent().getExtras().getString(key); // <-- as the key here
is it possible to set a value into a editable edittext like this?
LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
View promptView = layoutInflater.inflate(R.layout.prompt_dialog, null);
final EditText input = (EditText) promptView.findViewById(R.id.input_prompt);
TextView txt_prompt_mensaje = (TextView) promptView.findViewById(R.id.txt_prompt_mensaje);
Editable value = input.getText();
int suma_valor = Integer.parseInt(value.toString());
suma_valor = suma_valor + Integer.parseInt(value.toString());
Log.d("#### suma valor", Integer.toString(suma_valor));
input.setText(Integer.toString(suma_valor));
Using input.setText("Testing"); will give the editText the string of "Testing" in it's field. However you question seems vague when you say 'set a value'.
Another thing to add is that the editText will only take the values for when it is first instantiated.