I create on Setting page With Spinner in spinner have a hospital name to select
and when selected hospital in hospital have a phone number to save setting to button clicked call to that hospital
This my String-Array
I have two string - array first is a phone number of hospital
and second is hospital name I need to storing number to hospital name same as line when I selected in spinner
<string-array name ="number">
<item>055270300</item>
<item>055909000</item>
<item>055212222</item>
</string-array>
<string-array name="hospital">
<item>hospital 1</item>
<item>hospital 2</item>
<item>hospital 3</item>
</string-array>
And Here is my Activity:
TextView title = (TextView) findViewById(R.id.toolbar_title);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title.setText(toolbar.getTitle());
title.setText("การแจ้งเหตุฉุกเฉิน");
phonenum = (EditText)findViewById(R.id.input_phonenum);
message = (EditText)findViewById(R.id.put_message);
preferences = getSharedPreferences(shared_preferences,Context.MODE_PRIVATE);
editor = preferences.edit();
spinner = (Spinner)findViewById(R.id.sos_spinner);
String[] hospital = getResources().getStringArray(R.array.hospital);
ArrayAdapter<String> adapterhospital = new ArrayAdapter<String>(this ,android.R.layout.simple_list_item_1, hospital);
spinner.setAdapter(adapterhospital);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
editor.putInt(String.valueOf(getResources().getStringArray(R.array.number)), R.array.hospital);
editor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
button = (Button)findViewById(R.id.save_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getMessage = message.getText().toString();
int getPhonenum = Integer.parseInt(phonenum.toString());
editor.putInt(stored_phonenum, getPhonenum);
editor.putString(stored_message , getMessage);
editor.commit();
Toast.makeText(HowtoActivity.this, "Data Saved.",
Toast.LENGTH_SHORT).show();
}
});
}
I would recommend creating the array using java as opposed to xml.
Its quite simple,
ArrayList<String> hospitals= new ArrayList<>();
then add the hospitals to this array list this way :
hospitals.add("Hospital 1");
hospitals.add("Hospital 2");
hospitals.add("Hospital 3");
Note that this(hospitals array) is the array you will be storing in your spinner.
For the task you want to achieve, this is how i would proceed to do it :
You can have one more arraylist to store both hospital and its respective number seperated by a comma(,):
So create another arrayist, lets call it numbers.
ArrayList<String> numbers = new ArrayList<>();
numbers.add("Hospital 1,71955555");
numbers.add("Hospital 2,71955556");
numbers.add("Hospital 3,71955557");
Now once the user selects an item on the spinner, use the onItemSelected to get the value and store it in shared preferences.
Now just loop through the number arrayList and collect the number if your selected value is equal to the hospital name. You can split the value where the comma is. This way :
for(int i=0;i<numbers.size();i++){
String value = numbers.get(i);
String names[]= value.split(",");
String name = names[0];
if(name.equalsIgnoreCase("Value stored from spinner"){
String number = names[1];
//Store this number in shared preferences as the value for the hospital //selected
}
}
From here you can call the hospital number from your shared preferences in any activity where it is needed.
You can use xml pull Parser for this purpose.
Create an xml like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
<hospital>
<a_name>hospital 1</a_name>
<a_number>71955555</a_number>
</hospital>
</hospitalprovider>
Related
I want to give users option to select Currency display format like in this example:
Couple of challenges I face. First I do not know how to pass the values of
Currency.getAvailableCurrencies();
to the ListPreference entries and values set. Below is my attempt.
First the xml
<ListPreference
android:key="currency"
android:title="Currency"
android:defaultValue="$"
android:negativeButtonText="#null"
android:positiveButtonText="#null" />
Then this is how I try to populate the listPreference from code
public static class SettingsFragment extends PreferenceFragment {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add preference xml
addPreferencesFromResource(R.xml.pref_general);
//Get root PreferenceScreen
PreferenceScreen mPreferenceScreen = getPreferenceManager().createPreferenceScreen(getActivity());
//Get the currency list preference
ListPreference listPref = (ListPreference) mPreferenceScreen.findPreference("currency");
//Get available currency set
Set<Currency> currencySet = Currency.getAvailableCurrencies();
//Convert the currency Set<E> to String[] so I can get Array contents
String[] currencyArray = currencySet.toArray(new String[currencySet.size()]);
CharSequence[] entries = new CharSequence[currencyArray.length];
CharSequence[] values = new CharSequence[currencyArray.length];
for (int i = 0; i < entries.length; i++){
entries[i] = currencyArray[i].toString();
values[i] = currencyArray[i].toString();
}
listPref.setEntries(entries);
listPref.setEntryValues(values);
}
}
The above failed with the following exceptions
Caused by: java.lang.ArrayStoreException: source[0] of type java.util.Currency cannot be stored in destination array of type java.lang.String[]
So how can I present a human readable list of available currencies in a ListPreference>
UPDATE - WORKING CODE
For anyone reading, here is the updated working code per the answer below, not sure what I will do with Pre KitKat devices at this time
public static class SettingsFragment extends PreferenceFragment {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add preference xml
addPreferencesFromResource(R.xml.pref_general);
//Get root PreferenceScreen
PreferenceScreen mPreferenceScreen = (PreferenceScreen)getPreferenceScreen();
//Get the currency list preference
ListPreference listPref = (ListPreference) mPreferenceScreen.findPreference("currency");
if (listPref != null) {
//Get available currency set
Set<Currency> currencies = Currency.getAvailableCurrencies();
CharSequence[] entries = new CharSequence[currencies.size()];
CharSequence[] values = new CharSequence[currencies.size()];
int i = 0;
for (Currency currency: currencies){
String tempCurrency = String.format("%s\t%s\t%s",currency.getDisplayName(), currency.getSymbol(), currency.toString());
if (!tempCurrency.trim().isEmpty()){
entries[i] = tempCurrency;
values[i] = currency.getSymbol();
}
i++;
}
listPref.setEntries(entries);
listPref.setDefaultValue("$");
listPref.setEntryValues(values);
} else {
Toast.makeText(getActivity(), "ListPreference is null", Toast.LENGTH_SHORT).show();
}
}
}
This line seems like the problem, I dont know why you think it would automatically cast the Currency object to a string
//Convert the currency Set<E> to String[] so I can get Array contents
String[] currencyArray = currencySet.toArray(new String[currencySet.size()]);
You want to replace that with something like:
Set<Currency> currencies = Currency.getAvailableCurrencies();
for (Currency currency: currencies) {
System.out.printf("%s\t%s\t%s\n",currency.getDisplayName(), currency.getSymbol(), currency.toString());
// your code to check whether the symbol is not empty here
// add it to your String array or just directly use the
// CharSequences arrays for entries and values here.
}
I have a array of strings which is a resultant of options selected from a MultiAutoCompleteTextView using the comma tokenizer. The string appears as below:
"India, China, Japan, America, Australia"
I need to seperate this values based on the coma positiona and set those values to different textview's. Also I need to restrict the users to select only 5 values and those values should not be repeated.
You can use String.split() like this:
String[] array = yourString.split(",");
And iterate through that array.
EDIT:
To check if the user already selected the item, you can add an OnItemClickListener to your multiAutoCompleteTextView and have a HashSet or a Set where your items clicked are stored and check if this item already exists in the set
Example:
Initialize your HashSet first: HashSet<String> hashset = new HashSet<String>();
And later:
youMultiAutoCompleteTv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemClicked = parent.getAdapter().getItem(position).toString();
if(hashset.contains(itemClicked)){
Toast.makeText(getApplicationContext(), "Item exists", Toast.LENGTH_SHORT).show();
}
else {
hashset.add(itemClicked);
}
}
});
Use something like this:
String myListAsString = "India, China, Japan, America, Australia";
String[] countries = myListAsString.split(",");
TextView t1 = (TextView)findViewById(R.id.t1);
TextView t2 = (TextView)findViewById(R.id.t2);
TextView t3 = (TextView)findViewById(R.id.t3);
TextView t4 = (TextView)findViewById(R.id.t4);
TextView t5 = (TextView)findViewById(R.id.t5);
t1.setText(countries[0]);
t2.setText(countries[1]);
t3.setText(countries[2]);
t4.setText(countries[3]);
t5.setText(countries[4]);
You can use this :
String input = editText.getText().toString().trim(); //Getting String from view.
String[] singleInputs = input.split("\\s*,\\s*"); //Splitting in proper way.
I have a spinner in my app where the user chooses whether he wants to search by "Contains" "Starts with" "Ends with" or "Equals", The option user selects is stored into a json with other information and sent to server to retrieve results. Now I'm using:
String searchtypeval=searchtype.getSelectedItem().toString();
and adding searchtypeval into my json.
The String-array in the spinner is
<string-array name="search_options">
<item>Starts With</item>
<item>Equals</item>
<item>Ends With</item>
<item>Contains</item>
</string-array>
But now I'm adding language support so in values-fr/strings.xml the string array for that spinner is
<string-array name="search_options">
<item>Commence par </item>
<item>Égal </item>
<item>Se termine par </item>
<item>Contient </item>
</string-array>
Now if the user selects equals in french , Egal is stored into the JSON which of course the server doesn't accept. Is there any way I can make a connection between the french and the english strings.xml? All I can think of now is to use searchtype.getSelectedItemPosition()
and hard code the value into String searchtypeval since I know which option is which position, but this seems very cumbersome, is there any method to solve this issue that is more elegant?
You can send to the server index of a selected element, but this isn't a good way, cause of index is not informated. The better way is sending readable string key to the server. See the following code:
1) create file nontranslatable_string.xml in res/values
<resources>
<string-array name="search_options_keys">
<item>Starts With</item>
<item>Equals</item>
<item>Ends With</item>
<item>Contains</item>
</string-array>
</resources>
2) create your Item class like SpinnerItem
public class SpinnerItem {
public final String key;
public final String value;
private SpinnerItem(String key, String value) {
this.key = key;
this.value = value;
}
public static SpinnerItem create(String key, String value) {
return new SpinnerItem(key, value);
}
#Override
public String toString() {
return value;
}
}
3) fill your adapter with values
String[] keys = context.getResources().getStringArray(R.id.search_options_keys);
String[] values = context.getResources().getStringArray(R.id.search_options);
List<SpinnerItem> items = new ArrayList<SpinnerItem>();
for (int i = 0; i < keys.length; i++) {
items.add(SpinnerItem.create(keys[i], values[i]));
}
spinner.setAdapter(new ArrayAdapter<SpinnerItem>(context, android.R.layout.simple_spinner_item, android.R.id.text1, items));
4) select your value
String valueForSendingToServer = ((SpinnerItem) spinner.getSelectedItem()).key;
UPDATE
Or you can use another way and get neccessary value for any location you use:
Configuration config = context.getResources().getConfiguration();
// Save originla location
Locale originalLocal = config.locale;
// Set new one for single using
config.locale = new Locale("en");
context.getResources().updateConfiguration(config, null);
// Get search_options array for english values
String[] searchOptionsEn = getResources().getStringArray(R.array.search_options);
// Set previous location back
config.locale = originalLocal;
getResources().updateConfiguration(config, null);
String valueForSendingToServer = searchOptionsEn[spinner.getSelectedItemPosition()];
You can reference string resources in the string-array for localization.
<string-array name="search_options">
<item>#string/starts_with</item>
<item>#string/equals</item>
<item>#string/ends_with</item>
</string-array>
and then in res/values/strings.xml:
<string name="starts_with">Starts with </string>
and in res/values-fr/string.xml:
<string name="starts_with">Commence par </string>
I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.
i have an array which is populated in the spinner adapter.
now i wanna change the size of the array! is it possible?
help!
thank u
`public void classpopulate() {
if (PEP.getUser() == null) {
return;
}
classdetails = masterDataManager.getClassSections(PEP.getUser()
.getUsername(), getApplicationContext());
spnrClass = (Spinner) findViewById(R.id.spnrClass);
spnrSubject = (Spinner) findViewById(R.id.spnrSubject);
classname = new String[classdetails.size() + 1];
classname[0] = "SELECET CLASS";
for (int i = 1; i < classdetails.size() + 1; i++) {
classname[i] = classdetails.get(i - 1).getClass_name() + " "
+ classdetails.get(i - 1).getSection_name().toString();
}
ArrayAdapter<CharSequence> adapterClasses = new ArrayAdapter<CharSequence>(
getApplicationContext(), R.layout.spinner_item_class,
R.id.spinnerclasstxt, classname);
spnrClass.setAdapter(adapterClasses);
spnrClass.setSelection(0);
spnrClass
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// LinearLayout layoutSpinnersubj = (LinearLayout)
// findViewById(R.id.layout_spinner);
// RelativeLayout subject_Text
// =(RelativeLayout)findViewById(R.id.layoutsubjecttext);
int selectedindex = pos;
if (selectedindex == 0) {
spnrSubject.setVisibility(View.INVISIBLE);
} else {
spnrSubject.setVisibility(View.VISIBLE);
selectedClass = classdetails.get(selectedindex - 1);
subjectpopulate(selectedClass);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
`
You can use the ArrayAdapter methods clear, add, insert and/or remove to manipulate the adapter's data.
EDIT: From your comments, it sounds like you are eventually going to need to write your own custom adapter (probably by extending BaseAdapter), particularly if you want to have disabled (separator) rows, etc. You will have much more control over what gets displayed and how it looks. Search the web for "android custom list adapter" to find lots of examples of how to write one. It's not too difficult.
Nevertheless, if you want to keep using an ArrayAdapter, here's an example of removing the first element of the list (it assumes that the adapter has been saved in a member field adapter):
adapter.remove(adapter.getItem(0));
For more complicated changes (like loading a completely different set of data), you might do something like this:
String[] newData = . . .
adapter.setNotifyOnChange(false); // temporarily turn off auto-notification
adapter.clear();
adapter.addAll(newData);
adapter.notifyDataSetChanged(); // notifies and turns auto-notifications back on
It's good practice to suspend auto-notification when you are making several changes in sequence.
I hope this helps you.
In your activity get references from your layout file like,
Spinner spinner = (Spinner)findViewById(R.id.spinner);
Then, make adapter for that
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,YOUR_STRING_ARRAY);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Then make one arrays.xml it is contains your string array.
for example,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="string_array">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
</string-array>
</resources>
You could have an ArrayList in place of an array
ArrayList<String> classname = new ArrayList<String>;
classname.add("SELECET CLASS");
for (int i = 1; i < classdetails.size() + 1; i++) {
classname[i].add(classdetails.get(i - 1).getClass_name() + " "
+ classdetails.get(i - 1).getSection_name().toString());
}
ArrayAdapter<CharSequence> adapterClasses = new ArrayAdapter<CharSequence>(
getApplicationContext(), R.layout.spinner_item_class,
R.id.spinnerclasstxt, classname);
spnrClass.setAdapter(adapterClasses);
spnrClass.setSelection(0);