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
Related
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);
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) {
}
});
I have a map which shows markers from json file from web.
I made a search listview from the same file.
What I want to do is after click on any result map zooms on the marker associated with that result.
But now when I click on any result it only zoom on ONE marker which is the last item in my json file.
Here's my code:
public class MapAcWithMarker extends FragmentActivity
implements OnMapReadyCallback {
static final LatLng TEHRAN = new LatLng(35.697291, 51.392378);
private GoogleMap mMap;
public ArrayList<Locations> locationsList;
public ListView listView;
private View parentView;
public DataAdapter adapter;
ArrayList<Locations> arrayListTemp=new ArrayList<>();
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recyc);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// AsyncTaskGetMarker asyncTaskGetMareker= new AsyncTaskGetMarker();
new AsyncTaskGetMarker().execute();
locationsList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
inputSearch = (EditText) findViewById(R.id.inputSearch);
listView = (ListView) findViewById(R.id.listView);
listView.setVisibility(View.INVISIBLE);
inputSearch.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(keyCode== KeyEvent.KEYCODE_DEL){
listView.setVisibility(View.GONE);
}
return true;
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int count) {
listView.setVisibility(View.VISIBLE);
if(count==0){
listView.setVisibility(View.INVISIBLE);
}
String searchString= inputSearch.getText()
.toString().toLowerCase(Locale.getDefault());
int realText= searchString.length();
arrayListTemp.clear();
for (int i =0 ; i <locationsList.size(); i++){
try {
String pname= locationsList.get(i).getPname()
.toString();
String bicycleno= locationsList.get(i).getBicycleno()
.toString();
if(realText<=pname.length() && realText<= bicycleno.length())
if (searchString.equalsIgnoreCase(pname.substring(0,
realText)) ||
searchString.equalsIgnoreCase(bicycleno.substring(0, realText))
) {
arrayListTemp.add(locationsList.get(i));
} else {
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d("#w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
RequestInterface api = JsonClient.getApiService();
/**
* Calling JSON
*/
Call<StopList> call = api.getJSON();
/**
* Enqueue Callback will be call when get response...
*/
call.enqueue(new Callback<StopList>() {
#Override
public void onResponse(Call<StopList> call, Response<StopList> response) {
//Dismiss Dialog
// dialog.dismiss();
if (response.isSuccessful()) {
/**
* Got Successfully
*/
locationsList = response.body().getLocations();
/**
* Binding that List to Adapter
*/
adapter = new DataAdapter(MapAcWithMarker.this,
locationsList);
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<StopList> call, Throwable t) {
Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(TEHRAN, 10));
new AsyncTaskGetMarker().execute();
}
class AsyncTaskGetMarker extends
AsyncTask<String, String, JSONArray> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONArray doInBackground(String... params) {
String json = null;
JSONArray jsonarray = null;
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL("https://api.myjson.com/bins/1879ab.json");
conn = (HttpsURLConnection) url.openConnection();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader
(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
String response = builder.toString();
JSONObject jsonObject = new JSONObject(response);
jsonarray = jsonObject.getJSONArray("stops");
// jsonarray = new JSONArray(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonarray;
}
protected void onPostExecute(final JSONArray jsonarray) {
try {
final SparseArray<LatLng> positions =
new SparseArray<>();
mMap.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String pname = obj.getString("pname");
String bicycleno = obj.getString("bicycleno");
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
final LatLng position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
positions.put(i, position);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (positions.get(position) != null)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position), 15));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
inside onPostExecute you have:
position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position,15));
}
});
so under position you have always last called position. This variable is used by every onClick set (in line: newLatLngZoom(position,15))
for fix this create position only locally inside method, you dont need globalLatLng position` variable declared on top of file
final LatLng position = new LatLng(lat, lang);
//rest of code as above
edit: also these
lat = obj.getDouble("lat");
lang = obj.getDouble("lang");
keep them local only inside one loop of for inside onPostExecute
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
you should remove these declarations inside MapAcWithMarker class (on top)
//below to remove
public Double lat;
public Double lang;
public LatLng position;
//these are not used anywhere
public int selectionId= -1;
Marker markers;
next edit:
whole code of postExecute method
protected void onPostExecute(final JSONArray jsonarray) {
try{
final SparseArray<LatLng> positions = new SparseArray<>();
mMap.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String pname = obj.getString("pname");
String bicycleno = obj.getString("bicycleno");
Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
final LatLng position = new LatLng(lat, lang);
String title = "name: " + name;
mMap.addMarker(new MarkerOptions()
.position(position).title(title));
positions.put(i, position);
}
// set once, outside for loop
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if(positions.get(position)!=null)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position),15));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
I've inspected your code more carefully and... is a mess. you are not notifying adapter about new data/json (even if data in adapter matching parsed json on positions, titles etc. you should refresh layout). also every objects parsed from JSON are added to map as a Marker with mMap.addMarker(...) method, but I don't see any mMap.clear(); method called, so points may duplicate, when JSON is downloaded again (added this line above)
another edit - you have only one item drawn on list because you have inside onTextChanged method
for (int i =0 ; i <locationsList.size(); i++){
...
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
...
}
creation of adapter should be done once, outside for loop. check after loop but before initiation that arrayListTemp have more items
for (int i =0 ; i <locationsList.size(); i++){
...
}
Log.d("#w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);
lot of bugs...
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.
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) {
}
});
}