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);
Related
i have a problem here in using spinner, i want to add value to each array item in my string.xml
this is my code:
<string-array name="hubungan">
<item>Choice</item>
<item>CHILD</item>
<item>PARENT</item>
<item>HUSBAND</item>
<item>WIFE</item>
</string-array>
I mean is:
<string-array name="hubungan">
<item>Choice value="1"</item>
<item>CHILD value="2"</item>
<item>PARENT value="3"</item>
<item>HUSBAND value="4"</item>
<item>WIFE value="5"</item>
</string-array>
try this
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:entries="#array/hubungan"
/>
Well if you insist doing in this way try this example. The example will be as minimal as possible since you don't provide enough code.
Your string array values as you defined but I modified the way of storing by convenince.
<string-array name="hubungan">
<item>Choice,1</item>
<item>CHILD,2</item>
<item>PARENT,3</item>
<item>HUSBAND,4</item>
<item>WIFE,5</item>
</string-array>
I will assume that you have a spinner and a textview in your activity / fragment. You can set this data and process it as needed like following:
Spinner definition in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This code must be located in your onCreate method if you use an activity, or onViewCreated method if you use a fragment.
// I assume that you've already instantiated the spinner and textview
// Setup for spinner
String[] hubungans = getResources().getStringArray(R.array.hubungan);
if(hubungans != null && hubungans.length > 0) {
String[] names = new String[hubungans.length];
String[] values = new String[hubungans.length];
// Now we will parse the records and split them into name and value
for(int i = 0; i < hubungans.length; i++) {
String hubungan = hubungans[i];
if(hubungan == null || hubungan.isEmpty()) {
Log.d(TAG, "onViewCreated: couldn't get record for index "+i);
continue;
}
// Split the record by "," seperator for example for choice "Choice,1"
String[] nameValue = hubungan.split(",");
if(nameValue.length < 2) {
Log.d(TAG, "onViewCreated: couldn't get split record for index "+i);
continue;
}
names[i] = nameValue[0]; // first index will have the names
values[i] = nameValue[1]; // second will have its value
}
Log.d(TAG, "onViewCreated: names and values: "+ Arrays.toString(names)+" - "+Arrays.toString(values));
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, names);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int val = 0;
try {
val = Integer.parseInt(values[position]); // Here you have value as numeric type
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
textView.setText(String.format("Value for %s is %d", names[position], val));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
Log.d(TAG, "onViewCreated: Hubungans cannot be read!");
}
There you go! Hope this helps you with your unique problem.
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>
I am storing the selected item of the spinner, in an array "selectedPayment[]" which is storing lots of null values as well, so I've converted that array into a List "payMode". The problem is when i store the elements, the List is storing elements at wrong indexes. There is problem when I'm converting Array to List because an Array is storing items at correct indexes.
For example: I am getting [Cash, Paypal, Gift Card, Coupans] in a List which is not correct as I need to store elements in [Paypal, Coupans,Cash, Gift Card] order.
Please let me know where is the mistake.
Code:
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if (parent == spinner_paymentOption) {
selectedPayment[position] = paymentOptionList.get(position);
System.out.println("=====selll "+selectedPayment[position]);
payMode = new ArrayList<String>(Arrays.asList(selectedPayment));
payMode.remove(0);
payMode.removeAll(Collections.singleton(null));
System.out.println("====paymode==="+payMode);
if (!(spinner_paymentOption.getSelectedItemPosition() == 0)) {
isTrue = true;
if (items.contains(position)) {
Toast.makeText(
mActivity,
"You have already selected "
+ selectedPayment[position],
Toast.LENGTH_LONG).show();
} else {
counter++;
createDynamicPaymentLayout(position);
}
}
}
}
Make payMode arraylist outside the listener as:
payMode = new ArrayList<String>();
and add the selected item as:
(You can put the below lines just after
selectedPayment[position] = paymentOptionList.get(position); )
payMode.add(paymentOptionList.get(position));
and remove this:
payMode = new ArrayList<String>(Arrays.asList(selectedPayment));
payMode.remove(0);
payMode.removeAll(Collections.singleton(null));
I have a listView and I want to print the arrrayList which contains the selected items.
I can show the choice that I choose every time. i.e. if I select a choice, I can print it in a toast (I mark it in my code as a comment), but I want to print the whole choices together.
Any help please?
Thanks..
If I understand correctly, you want to display the contents of your arrayList in a Toast.
Like donfuxx said, you need to create your arrayList outside of your onclicklistener.
As the user clicks an item, it will be added to your arrayList.
Then loop over the list to fill a string called allItems, then show allItems in a toast.
ArrayList<String> checked = new ArrayList<String>();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String listItem = (String) listView.getItemAtPosition(position);
if(!checked.contains(listItem)){ //optional: avoids duplicate Strings in your list
checked.add((position+1), listItem);
}
String allItems = ""; //used to display in the toast
for(String str : checked){
allItems = allItems + "\n" + str; //adds a new line between items
}
Toast.makeText(getApplicationContext(),allItems, Toast.LENGTH_LONG).show();
}
});
Well you have the right concept, jsut wrong execution here is the part you missed out on:`
ArrayList<String> checked = new ArrayList<String>();
checked.add((position+1), listItem);
Toast.makeText(getApplicationContext(),checked.get((position+1)), Toast.LENGTH_LONG).show();`
You have to get the position of the element in the ArrayList which you require to fetch, hence
checked.get(array position of element here)
If you want to show every item that is in the ArrayList you can use a simple loop and add them to a string like this:
...
checked.add((position+1), listItem);
String tempString = "";
for(int x = 0; x < checked.length(); x++) {
tempString = tempString + ", " + checked.get(x);
}
tempString = tempString.substring(2);
Toast.makeText(getApplicationContext(),tempString, Toast.LENGTH_LONG).show();
EDIT modified it a bit to only put commas between items
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.