Class cast exception on spinner item selection - android

I have a spinner populated with custom adapter.
My code used to bind data to spinner is
private void setOperatorSpinnerAdapter(Spinner spinner, String data) {
listOperator = new ArrayList<>();
try {
jsonObject = new JSONObject(data);
jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
model2 = new LiabModel();
model2.setName(jsonObject.optString("name"));
listOperator.add(model2);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter_liab = new CustomListAdapter_liab(LiabilitiesActivity.this, listOperator);
spinner.setAdapter(adapter_liab);
}
My issue is with item selection. I am getting error as
java.lang.ClassCastException: java.lang.Integer cannot be cast to Model.LiabModel
My spinner item click code is
spnr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);
liab_type = model2.getName();
}
catch (Exception e){
Log.e("exc",""+e);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Im getting Class Cast exception in
"LiabModel model2 = (LiabModel) parent.getItemAtPosition(position);" this line. Why is that happening?

you can get selected value either by this
LiabModel model2 = (LiabModel) spnr.getItemAtPosition(position);
or by if listOperator is accessable
LiabModel model2 = listOperator.get(position);

Related

ListView and selection a location

I have locations save in the database and I am trying to retrieve them into a ListView. Each location has a name, a latitude and a longitude but the only thing that I am trying to display on the list in the name of the location and leave the latitude and longitude in the background so I can save them to the database based on what the location name selected by the user in the ListView.
Here is my current code:
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
JSONObject object = null;
try {
object = response.getJSONObject(i);
items.add(object.getString("locationName")); items.add(object.getString("latitude")); items.add(object.getString("longitude"));
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.location, items);
listView.setAdapter(adapter);
FuturaTextViewBold listviewHearder = (FuturaTextViewBold) customView.findViewById(R.id.tv_header);
listviewHearder.setBackgroundColor(Color.GREEN);
listviewHearder.setText("SELECT A LOCATION");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String SelectedItem = (String) listView.getItemAtPosition(position);
startLocation.setText(SelectedItem);
}
});
}
Create a POJO class
class Pojo {
double latitude;
double longitude;
String name;
}
Now create objects of this class in your for loop for items.
So, instead of the items.add(), you'll create new objects.
List<Pojo> pojos = new ArrayList<>():
for (int i = 0; i < response.length(); i++) {
JSONObject object = null;
try {
object = response.getJSONObject(i);
Pojo obj = new Pojo(); // use suitable name for the class
obj.name = object.getString("locationName");
obj.latitude = object.getString("latitude");
obj.longitude = object.getString("longitude");
pojos.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
Now pass these objects into your adapter.
For that, you need to use a custom implementation of ArrayAdapter.java. For this check : How to use ArrayAdapter<myClass>
ok use this code
public void onResponse(JSONArray response) {
List<String> locationName = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject object = null;
try {
object = response.getJSONObject(i);
locationName.add(object.getString("locationName"));
items.add(object.getString("locationName")); items.add(object.getString("latitude")); items.add(object.getString("longitude"));
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.location, locationName);
listView.setAdapter(adapter);
FuturaTextViewBold listviewHearder = (FuturaTextViewBold) customView.findViewById(R.id.tv_header);
listviewHearder.setBackgroundColor(Color.GREEN);
listviewHearder.setText("SELECT A LOCATION");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String SelectedItem = (String) listView.getItemAtPosition(position);
startLocation.setText(SelectedItem);
}
});
}
just add new List locationName and put it to ListView Adapter

How to set Assets json file data in two spinner + android?

Json File:
{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],
"Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}
I need to display country name in first spinner and city name in second spinner as per selected countries of spinner.
How to code it android?
My Code:
public class Search_for_room extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li = new HashMap<String, String>();
public ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_for_room);
activity = this;
ArrayList<String> items=getCountries("countriesToCities.json");
spinner=(Spinner)findViewById(R.id.spCountry);
spinnerCity=(Spinner)findViewById(R.id.spCity);
}
private ArrayList<String> getCountries(String fileName){
JSONArray jsonArray=null;
ArrayList<String> cList=new ArrayList<String>();
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
JSONObject jsonObj = new JSONObject(json);
// JSONObject resultObject = jsonObj.getJSONObject("result");
System.out.print("======Key: "+jsonObj);
Iterator<String> stringIterator = jsonObj.keys();
while(stringIterator.hasNext()) {
key = stringIterator.next();
value = jsonObj.getString(key);
System.out.println("------------"+key);
m_li.put(key,value);
al = new ArrayList<String>(m_li.keySet());
final SpinnerModel sched = new SpinnerModel();
/******* Firstly take data in model object ******/
sched.setCountryName(value);
// sched.setImage(key);
sched.setStates(key);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
Resources res = getResources();
customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
spinner.setAdapter(adapter);
}
}catch (JSONException ex){
ex.printStackTrace();
/*jsonArray=new JSONArray(json);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
System.out.pri
//cList.add(String.valueOf(jobj.keys()));
}
}*/
}catch (IOException e){
e.printStackTrace();
}
return cList;
}
}
try this code it can help you
try {
// load json from assets
JSONObject obj = new JSONObject(loadJSONFromAsset());
// than get your both json array
JSONArray IraqArray = obj.getJSONArray("Iraq");
JSONArray LebanonArray = obj.getJSONArray("Lebanon");
// declare your array to store json array value
String Iraq[] = new String[IraqArray.length()];
String Lebanon[] = new String[LebanonArray.length()];
//get json array of Iraq
for (int i = 0; i < IraqArray.length(); i++) {
Iraq[i] = IraqArray.getString(i);
}
//get json array of Lebanon
for (int i = 0; i < LebanonArray.length(); i++) {
Lebanon[i] = LebanonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
ask me in case of any query
add menu item in spinner
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/spinner"
android:title="Select Week"
app:actionViewClass="android.widget.Spinner"
android:textColor="#android:color/white"
android:textSize="11dp"
app:showAsAction="always" />
</menu>
add your json to array list
public void onPostExecute(String response) {
try {
list.clear();
MatchData vid = null;
Gson gson = new Gson();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("items");
for (int i = 0; i < array.length(); i++) {
vid = gson.fromJson(array.getJSONObject(i).toString(), MatchData.class);
list.add(vid);
}
matchDataAdapter = new MatchDataAdapter(MainActivity.this, list);
mRecyclerView.setAdapter(matchDataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
finally set adapter to spinner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
**ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lists);**
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
week = Integer.parseInt(selected);
requestforinfo();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return true;
}
You had done everything correct uptil now. Just make my suggestion and you are good to go with long list of JSON data.
First make the JSON Response of file accessible to whole activity/fragment by declaring at top.
Added following function to retrieve cityList of particular country:
private ArrayList<String> getCityList(String countryName){
ArrayList<String> cityList = new ArrayList<>();
//Here jsonObj is the your JSON response from the file.
try {
JSONArray jArray =jsonObj.getJSONArray(countryName);
for(int i=0;i<jArray.length();i++){
cityList.add(jArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return cityList;
}
Then add on spinnerItemSelected call the below function:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = ((SpinnerModel) parent.getSelectedItem()).getCountryName();
//For sake of your answer I had used String Array and ArrayAdapter. You can modify as you want.
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(YourActivity.this, R.layout.single_textview,getCityList(selected));
spinnerCity.setAdapter(cityAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Spinner not working properly while selecting data from it in android

There are lot of questions asked related to it, i searched them and tried to use the provided solution but unable to resolve my issue, that's why i am posting a new one.
I am working on android studio. In my app i am using a spinner as a dropdown. All the data is generated from a local JSON file which is in my assets folder. Below is my JSON file
ref.json
{"reference":
[
{"ref_no":"11111111111111","Name":"Faisal"},
{"ref_no":"22222222222222","Name":"Salman"},
{"ref_no":"33333333333333","Name":"Asim"},
{"ref_no":"44444444444444","Name":"Asad"},
{"ref_no":"55555555555555","Name":"Mateen"},
{"ref_no":"66666666666666","Name":"Omar"},
{"ref_no":"77777777777777","Name":"Usama"}
]}
MainActivity.java
Spinner dd_ref, dd_m_type,dd_site_status, dd_pole_type;
String refr_no, meter_type, latitude, longitude, site_status, comm_status, pole_type;
ArrayList<String> refList, m_type_List, site_status_List, pole_type_List;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
loadData();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void loadData() throws JSONException {
//////////////// Below method is for reference number call
JSONArray RefjsonArray;
JSONObject Ref_obj;
refList = new ArrayList<String>();
try
{
Ref_obj = new JSONObject(loadRefJSONFromAssest());
RefjsonArray = Ref_obj.getJSONArray("reference");
for(int i = 0; i<RefjsonArray.length();i++)
{
Ref_obj = RefjsonArray.getJSONObject(i);
Log.d("Details-->", Ref_obj.getString("ref_no"));
String ref = Ref_obj.getString("ref_no");
refList.add(ref);
}
refList.add(0,"Select a reference number");
} catch (JSONException e)
{
e.printStackTrace();
}
dd_ref = (Spinner)findViewById(R.id.dd_ref);
dd_ref.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, refList));
dd_ref.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
refr_no = String.valueOf(refList.get(position));
//text_pos.setText("Hi " + refr_no);
// Log.d(" out ",refr_no);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});//// end reference spinner
///////// start of method meter type dropdown
JSONArray m_type_Array;
JSONObject m_type_obj;
m_type_List = new ArrayList<String>();
try{
m_type_obj = new JSONObject(loadMeterTypeJSONFromAssest());
m_type_Array = m_type_obj.getJSONArray("meter");
for(int i = 0; i<m_type_Array.length(); i++)
{
m_type_obj = m_type_Array.getJSONObject(i);
Log.d("Details-->", m_type_obj.getString("m_type"));
String m_type = m_type_obj.getString("m_type");
m_type_List.add(m_type);
}
m_type_List.add(0,"Select Meter Type");
}catch (JSONException e)
{
e.printStackTrace();
}
dd_m_type = (Spinner)findViewById(R.id.dd_m_type);
dd_m_type.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, m_type_List));
dd_ref.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
meter_type = String.valueOf(m_type_List.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});// end dropdown meter type
}
////// method for loading meter type data
public String loadMeterTypeJSONFromAssest() {
String json = " ";
try{
InputStream is = getAssets().open("meter.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
//// load reference # data
public String loadRefJSONFromAssest() {
String json = " ";
try{
InputStream is = getAssets().open("ref.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
When i run my app it does load data into the spinner. I have 7 reference numbers in my list as shown in the JSON file. The app runs fine up to selecting reference number 33333333333333 and when i select 44444444444444 or more than it the app crashes while giving me below error in logcat
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.example.accurat.application.MainActivity$2.onItemSelected(MainActivity.java:131)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:931)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:920)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:890)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
It's hitting at point meter_type = String.valueOf(m_type_List.get(position)); and i don't know why it's going at this point as it doesn't have any link with the meter type.
I did a search and found a solution, but it couldn't solve my issue.
Any help would be highly appreciated.
You are adding wrong spinner item click listener,Change dd_ref to dd_m_type spinner.
dd_m_type = (Spinner)findViewById(R.id.dd_m_type);
dd_m_type.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, m_type_List));
dd_m_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
meter_type = String.valueOf(m_type_List.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});// end dropdown meter type
change
dd_ref.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
to
dd_m_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
In meter type dropdown method
I think there is issue in getting selected item from Spinner, Please try following approaches for getting selected items.
String Text = dd_m_type.getSelectedItem().toString();
OR
dd_m_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});

Android Spinner setOnItemSelectedListener not working

I have made a spinner dynamically during a login process. I'd like to be able to return the value of the spinner when I click on an option but it doesn't seem to work.
I make the spinner here:
public Spinner page_spinner;
protected void onCreate(Bundle savedInstanceState){
...
page_spinner = (Spinner) findViewById(R.id.page_spinner);
...
//MAKE ARRAY HERE
GraphRequest requestPage = GraphRequest.newGraphPathRequest(
currentAccessToken,
"/me/accounts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle pageParameters = new Bundle();
pageParameters.putString("fields", "name,access_token,picture{url}");
requestPage.setParameters(pageParameters);
requestPage.executeAsync();
...
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(StartPage.this, android.R.layout.simple_spinner_item, pages_array);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
page_spinner.setAdapter(spinnerArrayAdapter);
spinnerArrayAdapter.notifyDataSetChanged();
then I try to use the spinner here:
page_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("***********", "THIS ");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("***********", "THIS ");
}
});
I don't ever get the Log.d or even if I made Toast there, it doesn't fire. Not sure why this is stopping and I'm not getting any errors.
Any ideas?
Declare the spinner as a global variable and without final
and try this:
page_spinner = (Spinner) findViewById(R.id.page_spinner);
...
//MAKE ARRAY HERE
GraphRequest requestPage = GraphRequest.newGraphPathRequest(
currentAccessToken,
"/me/accounts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(StartPage.this, android.R.layout.simple_spinner_item, pages_array);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
page_spinner.setAdapter(spinnerArrayAdapter);
spinnerArrayAdapter.notifyDataSetChanged();
}
});
Your error seems somewhat correct. You are not notifying adapter about the changes in dataset.
Firstly, Your request is executed Async. So, your code execution will continue to next lines. So I guess, a blank array (size 0) is passed to ArrayAdapter<> and then the adapter is set to Spinner and then you are calling notifyDataSetChanged().
I think you should call spinnerArrayAdapter.notifyDataSetChanged();as below:
#Override
public void onCompleted(GraphResponse response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONObject().getJSONArray("data");
for(int i=0; i < jsonArray.length(); i++){
JSONObject page = jsonArray.getJSONObject(i);
String pageName = page.getString("name");
if(!pageName.equals("")) {
//Push names into the array
pages_array.add(pageName);
} else {
pages_array.clear();
}
}
spinnerArrayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
I've tested your codes and everything seems Right here. First I tried Adding 10 Items at spinner. Everything worked fine. And I tested adding List of String which contains only one Item.
List<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item 1");
My OnItemSelectedListener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
But what happened is the code everything worked fine before was not working after because there is only one item in spinnerArray. Toast was shown when Activity loads and not called when item is selected. You may have the same issue there. So my suggestion is give priority to your Array which may contain only one item.

Having trouble adding string array to spinner entries

What I'd like to accomplish is the String array names[] be what you see in the spinner, but I cannot seem to figure out how to do this. I have tried looking off of other similar questions, but everything I try results in a crash in my app, saying that it is unable to instantiate the activity. Below, I have included the onPostExecute, where I am generating the string array, and also my addListenerOnSpinnerSelection() method. Any guidance would be great.
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Categories

Resources