_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
} catch (JSONException e) {
}
}
});
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the above code i am getting a list of strings from server and populating in the spinner. When the activity is loaded i am unable to see the first item in the list("Select a doctor"). But when i click on spinner, i could see the items and select. Again then selected item is not visible as selected. Could anybody help me?
Thanks in advance.
_doctorSpinner = (Spinner) findViewById(R.id.input_doctor);
final ArrayList<String> docList = new ArrayList<String>();
DataUtil.getDoctorList(this.getApplicationContext(), new ServerCallBack() {
#Override
public void onSuccess(JSONObject result) {
}
#Override
public void onSuccess(String result) {
}
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
final ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, docList);
docAdapter.notifyDataSetChanged();
docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
_doctorSpinner.setAdapter(docAdapter);
_doctorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (JSONException e) {
}
}
});
webservice call work in background thread so ypou get list size zero when u set adapter so inialize and setadapter when call finish
Call notifyDataSetChanged(); after your data is added to the list.
#Override
public void onSuccess(JSONArray result) {
ArrayList<String> list = new ArrayList<String>();
list.add("Select Doctor");
try {
for (int i = 0; i < result.length(); i++) {
list.add(result.getString(i));
}
docList.addAll(list);
if (null != docAdapter)
docAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
EDIT :
My bad I read the question incorrectly.
If you cannot see the text inside your spinner try this:
ArrayAdapter<String> docAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, docList);
And I don't believe you need to use docAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
Related
There are 2 autocomplete textview one for the city and one for the state. I want that when a user enters the state in autocomplete textview then based on state selection, city autocomplete text view should be automatically filled. Like the ecommerce app whenever someone enters the postal code in the address section then the city and state get automatically filled and also the user has the option to select.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText edtxt_name_address, edtxt_email_address, edtxt_mobile_address, edtxt_alt_mob_address, edtxt_pincode, edtxt_addline1, edtxt_addline2;
Button buttonSaveAddress;
AutoCompleteTextView edtxt_city, edtxt_state;
private static final String KEY_STATE = "state";
private static final String KEY_CITIES = "cities";
private ProgressDialog pDialog;
private String cities_url = "http://api.androiddeft.com/cities/cities_array.json";
final List<State> statesList = new ArrayList<>();
final List<String> states = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtxt_city = findViewById(R.id.edtxt_city);
edtxt_state = findViewById(R.id.edtxt_state);
loadStateCityDetails();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
//edtxt_city.setTextColor(Color.BLACK)
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
buttonSaveAddress = findViewById(R.id.buttonSaveAddress);
buttonSaveAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAddress();
}
});
}
private void loadStateCityDetails() {
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, cities_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray responseArray) {
try {
//Parse the JSON response array by iterating over it
for (int i = 0; i < responseArray.length(); i++) {
JSONObject response = responseArray.getJSONObject(i);
String state = response.getString(KEY_STATE);
JSONArray cities = response.getJSONArray(KEY_CITIES);
List<String> citiesList = new ArrayList<>();
for (int j = 0; j < cities.length(); j++) {
citiesList.add(cities.getString(j));
}
statesList.add(new State(state, citiesList));
states.add(state);
Log.d("lskd", String.valueOf(statesList));
Log.d("lskd", String.valueOf(states));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
private void saveAddress() {
if (TextUtils.isEmpty(city)) {
edtxt_city.setError("Please enter your City");
edtxt_city.requestFocus();
return;
}
if (TextUtils.isEmpty(state)) {
edtxt_state.setError("Please enter your State");
edtxt_state.requestFocus();
return;
}
Intent profile_next = new Intent(MainActivity.this, ProfileNextActivity.class);
startActivity(profile_next);
}
}
State.java
public class State {
private String stateName;
private List<String> cities;
public State(String stateName, List<String> cities) {
this.stateName = stateName;
this.cities = cities;
}
public String getStateName() {
return stateName;
}
public List<String> getCities() {
return cities;
}
}
State and city has one to many relation, I didn't particularly understand what you meant by automatically filled. If you want to populate the related cities of the selected state do the following.
Inside your edtxt_state.setOnItemSelectedListener
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
statesList.get(position).getCities(); //get your cities from selected state
//set adapter or notify city list of your `edtxt_city` AutoCompleteTextView
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
try this...
edtxt_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
List<String> cityList = statesList.get(position).getCities();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, cityList);
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
set your adapter inside loadStateCityDetails(); after getting stateList
statesList.add(new State(state, citiesList));
states.add(state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, states);
edtxt_state.setThreshold(1);//will start working from first character
edtxt_state.setAdapter(adapter);
EDIT
edtxt_state.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < statesList.size(); i++) {
if (statesList.get(i).getStateName().equals(selection)) {
pos = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.select_dialog_item, statesList.get(pos).getCities());
edtxt_city.setThreshold(1);//will start working from first character
edtxt_city.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
}
});
you must get stateList
set city adapter as above
I'm trying to implement multiple spinners in the app, in which the data is populated after a volley call. It should work in such way that; based on the selection of the first spinner value "id", the second spinner should populate its value from another api call taking the selected "id" as parameter.
I'm able to show the "name"(s) in the spinner now. But not sure how to get the id of the selected item for the second api call. Right now when I select any item in the first spinner, it only returns the id of the last item in the array.
Json Array Response:
[
{
"id":1,
"name":"Roger Federer",
"country":"Switzerland",
"city":"Basel"
},
{
"id":2,
"name":"Rafael Nadal",
"country":"Spain",
"city":"Madrid"
},
{
"id":3,
"name":"Novak Djokovic",
"country":"Serbia",
"city":"Monaco"
},
{
"id":4,
"name":"Andy Murray",
"country":"United Kingdom",
"city":"London"
},
{
"id":5,
"name":"Maria Sharapova",
"country":"Russia",
"city":"Moscow"
},
{
"id":8,
"name":"Ana Ivanovic",
"country":"Serbia",
"city":"Belgrade"
}
]
FirstLevel (model)
public class FirstLevel {
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
private String title;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private int id;
}
Java code
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<FirstLevel> FirstLevelDataAdapterClassList;
private int selectedFirstLevel;
...
public void FIRST_LEVEL_WEB_CALL(final ViewHolder viewHolder) {
//showSimpleProgressDialog(context, "Loading...", "Fetching Json", false);
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
FIRST_PARSE_DATA_AFTER_WEBCALL(response,viewHolder);
Log.i("FL", "FL");
//removeSimpleProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}) {
};
requestQueue2 = Volley.newRequestQueue(context);
requestQueue2.add(jsArrRequest);
}
public void FIRST_PARSE_DATA_AFTER_WEBCALL(JSONArray array, final ViewHolder viewHolder) {
FirstLevelDataAdapterClassList = new ArrayList<>();
FirstLevel GetFirstLvDataModel = new FirstLevel();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetFirstLvDataModel.setId(json.getString("id"));
GetFirstLvDataModel.setName(json.getString("name"));
FirstLevelDataAdapterClassList.add(GetFirstLvDataModel);
names.add(FirstLevelDataAdapterClassList.get(i).getTitle().toString());
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
viewHolder.spinFirst.setAdapter(spinnerArrayAdapter);
viewHolder.spinFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedFirstLevel=FirstLevelDataAdapterClassList.get(position).getId();
Log.i("FLFL",selectedFirstLevel);
SECOND_LEVEL_WEB_CALL(viewHolder,selectedFirstLevel);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Your this line
selectedFirstLevel= //How to get the 'id' of the selected item here?
will be
selectedFirstLevel = FirstLevelDataAdapterClassList.get(position).getId();
Try this out. Thanks
FirstLevel GetFirstLvDataModel = new FirstLevel();
should be declare in forloop and adapter is outside of the loop.
try this method ->
public void FIRST_PARSE_DATA_AFTER_WEBCALL(JSONArray array, final ViewHolder viewHolder) {
FirstLevelDataAdapterClassList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
FirstLevel GetFirstLvDataModel = new FirstLevel(); // Define class object here
GetFirstLvDataModel.setId(json.getString("id"));
GetFirstLvDataModel.setName(json.getString("name"));
FirstLevelDataAdapterClassList.add(GetFirstLvDataModel);
names.add(FirstLevelDataAdapterClassList.get(i).getTitle().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
viewHolder.spinFirst.setAdapter(spinnerArrayAdapter);
viewHolder.spinFirst.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedFirstLevel=FirstLevelDataAdapterClassList.get(position).getId();
Log.i("FLFL",selectedFirstLevel);
SECOND_LEVEL_WEB_CALL(viewHolder,selectedFirstLevel);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I am putting my data in spinners.Data is coming from URL.How to make spinner so that when syllabus is ICSE is chosen it reflect only those grade, subject which has ICSE?
My JSON
{
"results":[
{
"syllabus":"CBSE",
"grade":"5",
"subject":"Kannada",
"topic":"Grammar Level 1",
"id":28
},
{
"syllabus":"CBSE",
"grade":"5",
"subject":"Science",
"topic":"The Natural Calamities",
"id":16
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Science",
"topic":"Movement in Animals",
"id":116
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Social Studies",
"topic":"Contact With Distant Lands",
"id":59
},
{
"syllabus":"CBSE",
"grade":"6",
"subject":"Social Studies",
"topic":"Gupta Empire",
"id":34
},
"id":148
},
{
"syllabus":"ICSE",
"grade":"6",
"subject":"Computers",
"topic":"Introduction to QBASIC Programming",
"id":44
},
{
"syllabus":"ICSE",
"grade":"6",
"subject":"Social Studies - History",
"topic":"The Vedic Age",
"id":42
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Mathematics",
"topic":"Previous Year Question Papers",
"id":121
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Biology",
"topic":"Previous Year Question Papers",
"id":117
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Chemistry",
"topic":"Previous Year Question Papers",
"id":110
},
{
"syllabus":"Entrance Exam - Karnataka CET",
"grade":"12",
"subject":"Science - Physics",
"topic":"Previous Year Question Papers",
"id":104
}
}
Any help will be great for me
MainActivity Class
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
JSONArray jsonarray2;
JSONObject jsonobject2;
ArrayList<String> worldlist;
ArrayList<String> worldlist2;
ArrayList<String> worldlist3;
ArrayList<Results> world;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.topic);
// Download JSON file AsyncTask
new DownloadJSON().execute();
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<Results>();
// Create an array to populate the spinner
worldlist = new ArrayList<String>();
worldlist2 = new ArrayList<String>();
worldlist3 = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("https://www.wonderslate.com/funlearn/topicsMap");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Results worldpop = new Results();
worldpop.setSyllabus(jsonobject.optString("syllabus"));
worldpop.setGrade(jsonobject.optString("grade"));
worldpop.setSubject(jsonobject.optString("subject"));
worldpop.setId(jsonobject.optString("id"));
world.add(worldpop);
worldlist.add(jsonobject.optString("syllabus"));
worldlist2.add(jsonobject.optString("grade"));
worldlist3.add(jsonobject.optString("subject"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
final Spinner mySpinner = (Spinner) findViewById(R.id.syllabus);
final Spinner mySpinner2 = (Spinner) findViewById(R.id.grade);
Spinner mySpinner3 = (Spinner) findViewById(R.id.subject);
// Spinner adapter
final LinkedHashSet<String>[] listToSet = new LinkedHashSet[]{new LinkedHashSet<String>(worldlist)};
//Creating Arraylist without duplicate values
final List<String> worldlistnew = new ArrayList<String>(listToSet[0]);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew));
//Creating ArrayList without duplicate values
listToSet[0] = new LinkedHashSet<String>(worldlist3);
//Creating Arraylist without duplicate values
final List<String> worldlistnew3 = new ArrayList<String>(listToSet[0]);
mySpinner3
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew3));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
if (mySpinner.getSelectedItem().toString().equals("CBSE")) {
// if (mySpinner.getId() == R.id.syllabus)
listToSet[0] = new LinkedHashSet<String>(worldlist2);
final List<String> worldlistnew2 = new ArrayList<String>(listToSet[0]);
mySpinner2
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlistnew2));
textView.setText("21");
} else if (mySpinner.getSelectedItem().toString().equals("ICSE")) {
textView.setText("31");
} else if (mySpinner.getSelectedItem().toString().equals("Entrance Exam - Karnataka CET"))
{
textView.setText("41");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private void resetGrade(String grade) {
}
}
Remove these lines first from doInBackground method. No need to create separate arraylist here..
worldlist.add(jsonobject.optString("syllabus"));
worldlist2.add(jsonobject.optString("grade"));
worldlist3.add(jsonobject.optString("subject"));
Declare these arraylist globally...
ArrayList<String> syllabuslist;
ArrayList<String> gradlist;
ArrayList<String> subjectlist;
and initialize these spinner in OnCreate method before calling Async task(DownloadJSON())
Spinner mySpinner = (Spinner) findViewById(R.id.syllabus);
Spinner mySpinner2 = (Spinner) findViewById(R.id.grade);
Spinner mySpinner3 = (Spinner) findViewById(R.id.subject);
Now set spinner in onPostExecute() method....remove extra code you have written in onPostExcute...just copy my code
#Override
protected void onPostExecute(Void args) {
// Spinner adapter
syllabuslist = new ArrayList<String>();
for (Results bean : world) {
syllabuslist.add(bean.getSyllabus());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, syllabuslist);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String syllabus_name = mySpinner.getItemAtPosition(arg2).toString();
gradlist = new ArrayList<String>();
for (int i = 0; i < world.size(); i++) {
if (world.get(i).getSyllabus().equals(syllabus_name)) {
gradlist.add(world.get(i).getGrade());
}
}
setGradeSpinner();//its a method to create grade spinner
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void setGradeSpinner(){
if(gradlist!=null && gradlist.size()>0)
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, gradlist);
adapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner2.setAdapter(adapter);
mySpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String grade_name = mySpinner2.getItemAtPosition(arg2).toString();
subjectlist = new ArrayList<String>();
for (int i = 0; i < world.size(); i++) {
if (world.get(i).getGrade().equals(grade_name)) {
subjectlist.add(world.get(i).getSubject());
}
}
// setSubjectSpinner();//its a method to create subject spinner like as I do for garde spinner
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Hope this will help you...
In your onitemclick listener of your first spinner, depending on the item selected change the list data of your second spinner and call.
spinner2Adapter.notifyDatasetChanged();
You dont have to create a new adapter and list every time you change selection in spinner1.
#Shwetabh Singh I cannt understand your question.But i have done one city select example. You can refere it. Here In first Spinner i list city name. and based on the city select second spinner area is refcted
{
"City": [
{
"name": "Ahmedabad",
"City_area1" : "Ghatlodia",
"City_area2" : "Chandlodia",
"City_area3" : "Other"
},
{
"name": "Hydarabad",
"City_area1" : "IIT",
"City_area2" : "Faridabad",
"City_area3" : "Other"
},
{
"name": "Noida",
"City_area1" : "Sector-50",
"City_area2" : "Sector-41",
"City_area3" : "Other"
}
]
}
MainActivity.java
public class MainActivity extends Activity {
Spinner selectcityspinner;
ArrayList<String> citylist;
ArrayList<city> cityandarealist;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectcityspinner = (Spinner)findViewById(R.id.selectcityspin);
citylist = new ArrayList<>();
new cityAsynTask().execute("Jason data url");//put your url over here
}
public class cityAsynTask extends AsyncTask<String,Void,Boolean>
{
#Override
protected Boolean doInBackground(String... params) {
cityandarealist = new ArrayList<city>();
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jobjcity = new JSONObject(data);
JSONArray jarray = jobjcity.getJSONArray("City");
for (int i = 0;i < jarray.length();i++){
city city = new city();
JSONObject jrealobject = jarray.getJSONObject(i);
city.setCity(jrealobject.getString("name"));
city.setArea1(jrealobject.getString("City_area1"));
city.setArea2(jrealobject.getString("City_area2"));
city.setArea3(jrealobject.getString("City_area3"));
cityandarealist.add(city);
citylist.add(jrealobject.getString("name"));
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if(aBoolean == false){
Toast.makeText(MainActivity.this,"data isnot recieved",Toast.LENGTH_SHORT).show();
} else {
ArrayAdapter<String> adapter = new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_spinner_item,citylist);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectcityspinner.setAdapter(adapter);
selectcityspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position) + " selected", Toast.LENGTH_LONG).show();
String Country = String.valueOf(parent.getItemAtPosition(position));
Spinner selectareaspinner = (Spinner) findViewById(R.id.selectareaspin);
List<String> AreaList = new ArrayList<String>();
AreaList.add(cityandarealist.get(position).getArea1());
AreaList.add(cityandarealist.get(position).getArea2());
AreaList.add(cityandarealist.get(position).getArea3());
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, AreaList);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter1.notifyDataSetChanged();
selectareaspinner.setAdapter(adapter1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
}
}
I am fetching the values from Database using JSON and inserting them into spinner. This process is running successfully.
But I am receiving a Spinner hint two times, when I click on spinner; how can I remove the first default value from spinner...
This is snapshot :- hope you understand my problem :
This is my code:-
private class GetCategories extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES,
ServiceHandler.GET);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
categoriesList.clear();
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(
catObj.getString("bus_type_id"),
catObj.getString("bus_type"));
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);
populateSpinner();
}
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
lables.add("Choose Type");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getbus_type());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
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
typeSpinner.setAdapter(spinnerAdapter);
typeSpinner.setOnItemSelectedListener(typeSelectedListener);
}
private OnItemSelectedListener typeSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (typeSpinner.getSelectedItem().toString() == "Choose Type") {
str = "";
typeSpinnercity.getSelectedView();
typeSpinnercity.setEnabled(false);
} else {
ok.setEnabled(true);
str = typeSpinner.getSelectedItem().toString();
typeSpinnercity.getSelectedView();
typeSpinnercity.setEnabled(true);
if (Utils.checkInternet(CutomerOfferActivity.this)) {
new GetCategoriesCity().execute();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
Use the ArrayAdapter and Override the method - getDropDownView..
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables){
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v = null;
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
v = super.getDropDownView(position, null, parent);
}
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
Use the above mentioned code and remove the default value in the dropdown.
I have an SQLite table and in the certain activity I obtain all the names fom the table and populate a listview with these names.
Inside the listview listener, the user have can delete the selected item.
The problem is when I delete the item the app crashes.
Please take a look on my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylocations);
tv_counter = (TextView) findViewById(R.id.counter);
tv_testCounter = (TextView) findViewById(R.id.testCounter);
lv = (ListView) findViewById(R.id.mylist);
mpoh = new MP_DB(this);
db = mpoh.getWritableDatabase();
cv = new ContentValues();
if (hasRecords()) {
Toast.makeText(getBaseContext(), getRowsNum()+" row(s)", Toast.LENGTH_SHORT).show();
get_MPNames();
arrayToArrayList();
setListView();
lv.setOnItemClickListener(listViewListener);
} else {
Toast.makeText(getBaseContext(), "NO RECORDS"+","+getRowsNum()+"rows", Toast.LENGTH_SHORT).show();
}
}
Here are the method to convert the array to arraylist, and the listview listener:
private void arrayToArrayList() {
int s = str.length;
al = new ArrayList<String>();
for (int i=0; i < s; i++) {
al.add(str[i]);
}
}
private int getRowsNum() {
return mpoh.getCurrentRowNumber();
}
OnItemClickListener listViewListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
pos = arg2;
showDialoge();
}
};
Here how I delete element from the DB and the ListView:
private void deleteMPfromListView(int pos) {
al.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), al.size()+" rows left in list view", Toast.LENGTH_SHORT).show();
}
private void deleteMPFromDB(int pos) {
mpoh.deleteMP(pos);
Toast.makeText(getBaseContext(), getRowsNum()+" rows left in DB", Toast.LENGTH_SHORT).show();
}
private Boolean hasRecords() {
if (getRowsNum() == 0) {
return false;
} else {
return true;
}
}
private void setListView() {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, al);
lv.setAdapter(adapter);
}
private void get_MPNames() {
str = new String[getRowsNum()];
for (int i=0; i <= getRowsNum()-1; i++) {
str[i] = mpoh.getMP_Name(i+1);
} //tv_testCounter.setText(str[87]);
}
Removing from the database has nothing to do with removing them from the ListView. I have not code of your implementation but you may try something like this too dynamically add or remove items:
public class LVDemo extends ListActivity {
// handles the ListView data
ArrayAdapter<String> adapter;
// Items that are displayed
ArrayList<String> listItems=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
/**
* Remove item.
*/
public void removeItem(int index) {
listItems.remove(index);
adapter.notifyDataSetChanged();
}
}
In General: You change the the ArrayList containing the element and then notify the adapter for the ListView