How to clear Spinner 2 values by changing spinner 1 values - android

In my application i have two spinners, first spinner contains some values like (str1,str2,str3...) and my second spinner contains some value related to each value of first spinner. when i select one value from first spinner, the related values are comming in second spinner for this i done code perfectly as follows.
this is my first spinner code:
private HashMap<String,String>departmentMap=new HashMap<>();
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
uid = jsonobject.getString("ID");
Department.add(department);
departmentMap.put(department,uid);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
this is belongs to first spinner item selection:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l){
String department=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
String id=departmentMap.get(department);
loadSpinnerDeficiency(URL2,id);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView){
// DO Nothing here
}
});
And the following is for getting proper response from spinner2:
private void loadSpinnerDeficiency(String url2,String uid) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+uid);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here when change my first selection in spinner one the spinner2 selected values of first selection must be clear.
But it doesn't happening please help me to solve this.

used below code ..
/**
* remove second spinner value based on first spinner selected value
* it match then remove it.
*/
private void removeValue() {
List<String> itemvalue=new ArrayList<>();
itemvalue.add("Abc");
itemvalue.add("cde");
itemvalue.add("xyz");
List<String> itemvalue2=new ArrayList<>();
itemvalue2.add("Abc");
itemvalue2.add("cde");
itemvalue2.add("xyz");
itemvalue2.add("pqr");
itemvalue2.add("stu");
Spinner spinner=findViewById(R.id.sp);
Spinner spinner1=findViewById(R.id.sptwo);
ArrayAdapter<String> adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemvalue);
ArrayAdapter<String> adapter2=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,itemvalue2);
spinner.setAdapter(adapter);
spinner1.setAdapter(adapter2);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
itemvalue2.remove(spinner.getSelectedItem());
adapter2.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Related

how to set content in spinner dynamicly using async task?

I am new in android. I am trying to fetch data in spinner from database. But I don't know why my list is not set in spinner.
My code is
public class AddBasicDetail extends Fragment implements AdapterView.OnItemSelectedListener {
// array list for spinner adapter
private ArrayList<State> categoriesList;
ProgressDialog pDialog;
Spinner sp_state;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://mandirdekhoo.com/app/md_eng/state.php";
public AddBasicDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.add_basic_detail, container, false);
sp_state = (Spinner) v.findViewById(R.id.sp_state);
categoriesList = new ArrayList<State>();
// spinner item select listener
//sp_state.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) getActivity());
new GetCategories().execute();
return v;
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
//txtCategory.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp_state.setAdapter(spinnerAdapter);
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Fetching food categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_NEW_CATEGORY, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
Log.e("my response: ", "> " + jsonObj);
if (jsonObj != null) {
JSONArray categories = jsonObj .getJSONArray("result");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
State cat = new State(catObj.getInt("id"),
catObj.getString("state_name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
//populateSpinner();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(
getContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
my service handler class is
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
and
public class State {
private int id;
private String name;
public State(){}
public State(int id, String name){
this.id = id;
this.name = name;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
}
Please help
Hey after getting the correct response try to add this code
for e.g i am trying hardcoded values.replace this with your json.
final List<String> yourlist=new ArrayList<String>();
yourlist.add("Item 1");
yourlist.add("Item 2");
yourlist.add("Item 3");
yourlist.add("Item 4");
yourlist.add("Item 5");
final Spinner sp1= (Spinner) findViewById(R.id.spinner1);
final Spinner sp2= (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adp1=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,yourlist);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adp1);
Hope this helps.:)
Change your method like this
private void populateSpinner(List<String> categoriesList) {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
sp_state.setAdapter(spinnerAdapter);
}
And after calling this method notifydatasetchanged() call this method.
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner(categoriesList);
}
Hope this will help you

Update the second spinner based on first spinner item

i have created the two spinner in xml namely myspinner and myspinner1. The myspinner value is obtained from the json value.Based on myspinner item selected,we get the hotel id.That retrieved hotel id is used to call the another AsyncT1.In the AsyncT1 the myspinner1 value get listed out.My problem is,if i select the myspinner the myspinner1 value is not updated it remains same.I have tried the adapter.notifydatasetchanged() but till now not updated.`
class AsyncT extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/hotel");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "response -----" + responseServer);
//Get the instance of JSONArray that contains JSONObjects
// postData(responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("Hotel_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
movie.setHotelid1(jsonObject.optString("hotel_id").toString());
movie.setHotelname1(jsonObject.optString("hotel_name").toString());
hotelNames.add(jsonObject.optString("hotel_name").toString());
movieList.add(movie);
System.out.println("movie list" + movieList);
runOnUiThread(new Runnable() {
#Override
public void run() {
Adapter = (new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, hotelNames));
mySpinner.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
System.out.println("name--"+hotelid);
new AsyncT1().execute(hotelid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
class AsyncT1 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// http://airbnb.abservetech.com/demo/public/mobile/hotelroom/roomid?hotel_id=79
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/show");
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
/*hotel_id&room_type&room_prize&is_active&available_status&adults_count&room_count&room_images&
room_desc&room_name&room_footage&General&Services&Food_Beverages&Outdoors&Activities&
Dining&Media_Entertainment&Kitchen&Others*/
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("hotel_id", hotelid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "viewroomresponse -----" + responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("view_room_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
// movie.setViewRoomtype(jsonObject.optString("room_type").toString());
movie.setViewRoomprice(jsonObject.optString("room_prize").toString());
movie.setViewIsActive(jsonObject.optString("is_active").toString());
movie.setViewAvailablestatus(jsonObject.optString("available_status").toString());
movie.setViewAdultcount(jsonObject.optString("adults_count").toString());
movie.setViewRoomcount(jsonObject.optString("room_count").toString());
movie.setViewRoomdesc(jsonObject.optString("room_desc").toString());
movie.setViewRoomname(jsonObject.optString("room_name").toString());
movie.setViewRoomfootage(jsonObject.optString("room_footage").toString());
RoomNames.add(jsonObject.optString("room_type").toString());
movieList.add(movie);
runOnUiThread(new Runnable() {
#Override
public void run() {
// ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,RoomNames);
// Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Adapter.notifyDataSetChanged();
// mySpinner1.setAdapter(Adapter);
Adapter1 =(new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, RoomNames));
if(Adapter1!=null){
Adapter1.notifyDataSetChanged();
mySpinner1.setAdapter(Adapter1);
}
else{ mySpinner1.setAdapter(Adapter1);}
mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
room_price.setText(movieList.get(position).getViewRoomprice());
description.setText(movieList.get(position).getViewRoomdesc());
adult_count.setText(movieList.get(position).getViewAdultcount());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
`
Use this link, it might help you.
http://www.javaknowledge.info/populate-second-spinner-based-on-selection-of-first-spinner/

trouble with adding Spinner in CSipSimple

I'm trying to add spinner in my CSipSimple account registration form. but i'm having error at few lines.
first i'm having error at
accountUserName = (Spinner) findViewById("username");
findViewById is undefined.
Second is at
ArrayAdapter dataAdapter = new ArrayAdapter(this, R.layout.spinner_item, list);
saying Constructor ArrayAdapter is undefined.
this code was working fine in a saperate program but when i tried to put this code in CSipsimple Basic.java file it showed these two errors. can someone please help me?
public class Basic extends BaseImplementation {
protected static final String THIS_FILE = "Basic W";
InputStream is=null;
String result=null;
String line=null;
JSONObject json = null;
private Spinner accountUserName;
private EditTextPreference accountDisplayName;
//private EditTextPreference accountUserName;
private EditTextPreference accountServer;
private EditTextPreference accountPassword;
private void bindFields() {
accountDisplayName = (EditTextPreference) findPreference("display_name");
accountUserName = (Spinner) findViewById("username");
accountServer = (EditTextPreference) findPreference("server");
accountPassword = (EditTextPreference) findPreference("password");
}
public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
//fetching values fro mysql database
String serverFull = account.reg_uri;
if (serverFull == null) {
serverFull = "";
}else {
serverFull = serverFull.replaceFirst("sip:", "");
}
ParsedSipContactInfos parsedInfo = SipUri.parseSipContact(account.acc_id);
//accountUserName.setText(parsedInfo.userName);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.xx.xxx/conIds.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println(result);
Log.e("Pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//
try
{
JSONArray NJA=new JSONArray(result);
String arr=NJA.getString(1);
Log.d("My arry", ""+arr);
JSONArray JA=new JSONArray(arr);
final String[] str2 = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
str2[i] = JA.getString(i);
}
List<String> list = new ArrayList<String>();
for(int i=0;i<str2.length;i++)
{
list.add(str2[i]);
}
Collections.sort(list);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
accountUserName.setAdapter(dataAdapter);
accountUserName.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub
String Item=accountUserName.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), Item,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
accountServer.setText(serverFull);
accountPassword.setText(account.data);
}
Have you imported android.app.Activity (in which findViewById(int) is defined) and android.widget.ArrayAdapter?

Android custom adapter passing ArrayList of Objects

hopefully someone can point me in the right direction, i am creating a custom adapter to display 3 items in a listview image,id,text.
so i get my data from a webservice returning JSON objects which works fine. my problem is im not sure where im going wrong after the Asynctask because the list does not have any data, i have implemented this already when passing single field to a spinner but just can't figure it out. i know the custom adapter works as when i manually assign new CallOut objects and add to the Arraylist they list displays fine thanks for any help.
public class ListCallOuts extends Activity {
ArrayList<CallOut> callOutResults=new ArrayList<CallOut>(); //=GetCallOuts();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
GetCallOuts();
//ArrayList<CallOut> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
//lv1.setAdapter(new CallOutAdapter(this, searchResults));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
CallOut fullObject = (CallOut)o;
Toast.makeText(ListCallOuts.this, "You have chosen: " + " " +
fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
private void GetCallOuts() {
new DownloadCallouts().execute(new String[]
{"http://192.168.0.16:8080/return_callouts.json"});
}
private class DownloadCallouts extends AsyncTask<String,Void,JSONArray> {
#Override
protected JSONArray doInBackground(String... urls) {
JSONArray array = null;
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
HttpEntity entity = execute.getEntity();
String data = EntityUtils.toString(entity);
array = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject row = jsonArray.getJSONObject(i);
CallOut callOut = new
CallOut(row.getString("id"),row.getString("customer_name")) ;
callOutResults.add(callOut);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Change this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
With this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
callOutAdapter = new CallOutAdapter(this,callOutResults);
lv1.setAdapter(callOutAdapter);
Note: you should define this as a property of your class to reach it at onPostExecute method.
CallOutAdapter callOutAdapter;
And after updating your arraylist at onPostExecute add this line:
callOutAdapter.notifyDataSetChanged();

How do I populate an Android spinner using a JSON web service?

How do I parse a JSON file like the one below containing school names and IDs and use the values in the "Name" field to populate the spinner lables?
I want the spinner to output the selected SchoolID to the next activity. E.g. So you see "Hill View Elementary" and if you select this the value "HVE" is output to the next activity to act on.
{
"schools": [
{
"Name": "Hill View Elementary",
"SchoolID": "HVE"},
{
"Name": "Mill View",
"SchoolID": "MVE"},
{
"Name": "Big School",
"SchoolID": "BSC"},
]
}
Here is the onCreate I'm using to attempt to read the feed...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String readFeed = readFeed();
try {
JSONArray jsonArray = new
JSONArray(readFeed);
Log.i(MainActivity.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here instead of Logging I want to use each schools "Name" to
// be put into an array that I can use to populate the strings
// for the spinner
Log.i(MainActivity.class.getName(), jsonObject.getString("schools"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm still coming up to speed on Android so clarity appreciated.
Here is readfeed:
public String readFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
// domain intentionally obfuscated for security reasons
HttpGet httpGet = new HttpGet("http://www.domain.com/schools.php");
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String
line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(MainActivity.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return builder.toString();
}
I would do something like this:
public class School {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
On create:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String readFeed = readFeed();
// you can use this array to find the school ID based on name
ArrayList<School> schools = new ArrayList<School>();
// you can use this array to populate your spinner
ArrayList<String> schoolNames = new ArrayList<String>();
try {
JSONObject json = new JSONObject(readFeed);
JSONArray jsonArray = new JSONArray(json.optString("schools"));
Log.i(MainActivity.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
School school = new School();
school.setName(jsonObject.optString("Name"));
school.setId(jsonObject.optString("SchoolID"));
schools.add(school);
schoolNames.add(jsonObject.optString("Name"));
}
} catch (Exception e) {
e.printStackTrace();
}
Spinner mySpinner = (Spinner)findViewById(R.id.my_spinner);
mySpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, schoolNames));
}
In your main_activity.xml you need a Spinner. The code above would work with a Spinner named like below:
<Spinner
android:id="#+id/my_spinner"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>

Categories

Resources