Related
I have
["A","B","C","D"]
I want to bind this to the android spinner. How can I remove []"", from ["A","B","C","D"] so only characters will display in the spinner.
sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String asd = "";
arrayList3.clear();
asd= arrayList2.get(position);
String[] items = asd.split(",");
List<String> list = Arrays.asList(items);
for(String item : list)
{
arrayList3.add(item);
}
ArrayAdapter<String> dataAdapter1 =
new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, arrayList3);
sp2.setAdapter(dataAdapter1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
just replace this code with foreach loop in your code
for(String item : list)
{
item = item.replace("[","");
item = item.replace("]","");
item = item.replace("\"","");
arrayList3.add(item);
}
I have 3 spinners and depend on each other like that;
Category1
Category2
Category3
When user select Category1, 2.spinner should show that;
Category1-1
Category1-2
Category1-3
And user select Category1-2, 3.spinner should show that;
Category1-1-1
Category1-1-2
Category1-1-3
I implement this way, but it is too long
so i want to any suggestion for more efficient code
public class BookActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Spinner sp1,sp2,sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
List<String> list = new ArrayList<String>();
list.add("Category1");
list.add("Category2");
list.add("Category3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
sp1.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
fillSpinnerList(parent.getItemAtPosition(position).toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void fillSpinnerList(String selectedSpinnerName){
if(selectedSpinnerName =="Category1" ){
List<String> list = new ArrayList<String>();
list.add("Category1-1");
list.add("Category1-2");
list.add("Category1-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category2" ){
List<String> list = new ArrayList<String>();
list.add("Category2-1");
list.add("Category2-2");
list.add("Category2-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category3" ){
List<String> list = new ArrayList<String>();
list.add("Category3-1");
list.add("Category3-2");
list.add("Category3-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
sp2.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-1" ){
List<String> list = new ArrayList<String>();
list.add("Category1-1-1");
list.add("Category1-1-2");
list.add("Category1-1-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-2" ){
List<String> list = new ArrayList<String>();
list.add("Category1-2-1");
list.add("Category1-2-2");
list.add("Category1-2-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
if(selectedSpinnerName =="Category1-3" ){
List<String> list = new ArrayList<String>();
list.add("Category1-3-1");
list.add("Category1-3-2");
list.add("Category1-3-3");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
sp3.setOnItemSelectedListener(this);
}
}
}
You can refactor it like that. It's still long as a part of it can be generalised but it's more readable.
BookActivity
public class BookActivity extends AppCompatActivity {
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
initSpinner1();
}
private void initSpinner1() {
final List<String> list = new ArrayList<>();
list.add("Category1");
list.add("Category2");
list.add("Category3");
initSpinner(sp1, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner2(itemName);
}
});
}
private void initSpinner2(String selectedCategory) {
final List<String> list = new ArrayList<>();
switch (selectedCategory) {
case "Category1":
list.add("Category1-1");
list.add("Category1-2");
list.add("Category1-3");
break;
case "Category2":
list.add("Category2-1");
list.add("Category2-2");
list.add("Category2-3");
break;
case "Category3":
list.add("Category3-1");
list.add("Category3-2");
list.add("Category3-3");
break;
default:
break;
}
initSpinner(sp2, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner3(itemName);
}
});
}
public void initSpinner3(String selectedCategory) {
final List<String> list = new ArrayList<>();
switch (selectedCategory) {
case "Category1-1":
list.add("Category1-1-1");
list.add("Category1-1-2");
list.add("Category1-1-3");
break;
case "Category1-2":
list.add("Category1-2-1");
list.add("Category1-2-2");
list.add("Category1-2-3");
break;
case "Category1-3":
list.add("Category1-3-1");
list.add("Category1-3-2");
list.add("Category1-3-3");
break;
default:
break;
}
initSpinner(sp3, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
// TODO
}
});
}
private void initSpinner(Spinner spinner, List<String> list, SpinnerListener.Callback callback) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final AdapterView.OnItemSelectedListener listener = new SpinnerListener(this, callback);
spinner.setOnItemSelectedListener(listener);
}
}
The implementation of the OnItemSelectedListener
public class SpinnerListener implements AdapterView.OnItemSelectedListener {
private final Context mContext;
private final Callback mCallback;
public SpinnerListener(Context context, Callback callback) {
mContext = context;
mCallback = callback;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String itemName = parent.getItemAtPosition(position).toString();
Toast.makeText(mContext, "YOUR SELECTION IS : " + itemName, Toast.LENGTH_SHORT).show();
mCallback.onResult(itemName);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing
}
public interface Callback {
void onResult(String itemName);
}
}
The code can be shorten a little bit if you use lambda function (Java 8). For instance:
initSpinner(sp2, list, new SpinnerListener.Callback() {
#Override
public void onResult(String itemName) {
initSpinner3(itemName);
}
});
can be written:
initSpinner(sp2, list, itemName -> initSpinner3(itemName));
or even shorter:
initSpinner(sp2, list, this::initSpinner3);
EDIT
Or you can do something like that by using String arrays instead of lists. You can export the methods to init the array into a separated file so it makes the code in the Activity lighter:
public class BookActivity extends AppCompatActivity {
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
initSpinner1();
}
private void initSpinner1() {
final String[] list = SpinnerArrayInitializer.getSpinner1Array();
initSpinner(sp1, list, itemName -> initSpinner2(itemName));
}
private void initSpinner2(String selectedCategory) {
final String[] list = SpinnerArrayInitializer.getSpinner2Array(selectedCategory);
initSpinner(sp2, list, itemName -> initSpinner3(itemName));
}
public void initSpinner3(String selectedCategory) {
final String[] list = SpinnerArrayInitializer.getSpinner3Array(selectedCategory);
initSpinner(sp3, list, itemName -> {
// TODO
});
}
private void initSpinner(Spinner spinner, String[] list, SpinnerListener.Callback
callback) {
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final AdapterView.OnItemSelectedListener listener = new SpinnerListener(this, callback);
spinner.setOnItemSelectedListener(listener);
}
}
And the to initialise the arrays:
public interface SpinnerArrayInitializer {
static String[] getSpinner1Array() {
return new String[]{"Category1", "Category2", "Category3"};
}
static String[] getSpinner2Array(String selectedCategory) {
switch (selectedCategory) {
case "Category1":
return new String[]{"Category1-1", "Category1-2", "Category1-3"};
case "Category2":
return new String[]{"Category2-1", "Category2-2", "Category2-3"};
case "Category3":
return new String[]{"Category3-1", "Category3-2", "Category3-3"};
default:
return new String[0];
}
}
static String[] getSpinner3Array(String selectedCategory) {
switch (selectedCategory) {
case "Category1-1":
return new String[]{"Category1-1-1", "Category1-1-2", "Category1-1-3"};
case "Category1-2":
return new String[]{"Category1-2-1", "Category1-2-2", "Category1-2-3"};
case "Category1-3":
return new String[]{"Category1-3-1", "Category1-3-2", "Category1-3-3"};
default:
return new String[0];
}
}
}
Try this:
public class BookActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private final static int SP1_NUM_OF_OPTIONS = 3;
private final static int SP2_NUM_OF_OPTIONS = 3;
private final static int SP3_NUM_OF_OPTIONS = 3;
private final static String SP3_HINT = "<SELECT>";
Spinner sp1, sp2, sp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
sp1 = (Spinner) findViewById(R.id.sp1);
sp2 = (Spinner) findViewById(R.id.sp2);
sp3 = (Spinner) findViewById(R.id.sp3);
// Setup data list and adapter for sp1.
ArrayList<String> list = new ArrayList<>();
for(int i=1; i<=SP1_NUM_OF_OPTIONS; i++){
list.add("Category" + i);
}
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(adapter);
// Set listeners for all spinners.
sp1.setOnItemSelectedListener(this);
sp2.setOnItemSelectedListener(this);
sp3.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
fillSpinnerList(parent.getId(), parent.getItemAtPosition(position).toString());
// Automatically do something different after last step is selected.
if(parent.getId() == R.id.sp3){
if(!parent.getItemAtPosition(position).toString().equals(SP3_HINT)){
// Do something
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
public void fillSpinnerList(int spinnerId, String selectedSpinnerName){
ArrayAdapter adapter;
if(spinnerId == R.id.sp1){
String[] list1;
list1 = getResources().getStringArray(getResources().getIdentifier(selectedSpinnerName, "array", getPackageName()));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
}else if(spinnerId == R.id.sp2){
ArrayList<String> list = new ArrayList<>();
list.add(SP3_HINT);
String[] list1;
list1 = getResources().getStringArray(getResources().getIdentifier(selectedSpinnerName, "array", getPackageName()));
list.addAll(Arrays.asList(list1));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp3.setAdapter(adapter);
}
}
}
Add your Category in strings.xml:
<array name="Category1">
<item>Category1_1</item>
<item>Two</item>
<item>Three</item>
</array>
<array name="Category1_1">
<item>Category1_1_1</item>
<item>Category1_1_2</item>
<item>Category1_1_3</item>
</array>
<array name="Two">
<item>Category1_2_1</item>
<item>Category1_2_2</item>
<item>Category1_2_3</item>
</array>
<array name="Three">
<item>Category1_3_1</item>
<item>Category1_3_2</item>
<item>Category1_3_3</item>
</array>
<array name="Category2">
<item>Category2_1</item>
<item>Four</item>
<item>Five</item>
</array>
<array name="Category2_1">
<item>Category2_1_1</item>
<item>Category2_1_2</item>
<item>Category2_1_3</item>
</array>
<array name="Four">
<item>Category2_2_1</item>
<item>Category2_2_2</item>
<item>Category2_2_3</item>
<item>Category2_2_4</item>
</array>
<array name="Five">
<item>Category2_3_1</item>
<item>Category2_3_2</item>
<item>Category2_3_3</item>
<item>Category2_3_4</item>
<item>Category2_3_5</item>
</array>
<array name="Category3">
<item>Category3_1</item>
<item>Six</item>
<item>Seven</item>
</array>
<array name="Category3_1">
<item>Category3_1_1</item>
<item>Category3_1_2</item>
<item>Category3_1_3</item>
</array>
<array name="Six">
<item>Category3_2_1</item>
<item>Category3_2_2</item>
<item>Category3_2_3</item>
<item>Category3_2_4</item>
<item>Category3_2_5</item>
<item>Category3_2_6</item>
</array>
<array name="Seven">
<item>Category3_3_1</item>
<item>Category3_3_2</item>
<item>Category3_3_3</item>
<item>Category3_3_4</item>
<item>Category3_3_5</item>
<item>Category3_3_6</item>
<item>Category3_3_7</item>
</array>
Hope it helps!!
I am using Autocompltetextview and I want user to allow only to accept the value of suggested list. User should not enter other value and submit. if user did not select the value of autocomplettextview then i want to show toast. can any one help me to solve this . check my snippet code and help me?
Code
actv = (AutoCompleteTextView)rootView.findViewById(R.id.search_donor_area);
actv.setThreshold(1);//will start working from first character
materialDesignSpinner.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
sel_blood_group=materialDesignSpinner.getText().toString();
Log.d("sel_blood_group",sel_blood_group);
}
});
citymaterialDesignSpinner = (MaterialBetterSpinner)
rootView.findViewById(R.id.search_donor_city);
citymaterialDesignSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Log.d("POSITION", CITY_SPINNERLIST[position]);
sel_city=citymaterialDesignSpinner.getText().toString();
Log.d("search_sel_city",sel_city);
if (position == 0) {
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> areasadapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.select_dialog_item, AREA_DONOR);
actv.setAdapter(areasadapter);//setting the adapter data into the AutoCompleteTextView
} else if (position == 1) {
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> areasadapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.select_dialog_item, AREA_DONOR_RAJKOT);
actv.setAdapter(areasadapter);//setting the adapter data into the AutoCompleteTextView
}
else if (position == 2) {
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> areasadapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.select_dialog_item, AREA_DONOR_SURAT);
actv.setAdapter(areasadapter);//setting the adapter data into the AutoCompleteTextView
}
else if (position == 3) {
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> areasadapter = new ArrayAdapter<String>
(getActivity(), android.R.layout.select_dialog_item, AREA_DONOR_BARODA);
actv.setAdapter(areasadapter);//setting the adapter data into the AutoCompleteTextView
}
}
});
ArrayAdapter<String> cityarrayAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_dropdown_item_1line, CITY_SPINNERLIST);
citymaterialDesignSpinner.setAdapter(cityarrayAdapter);
actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("========>>", actv.getText().toString());
sel_area=actv.getText().toString();
}
});
search_button = (Button)rootView.findViewById(R.id.search_button);
Compare actv.getText().toString() with your adapter's values.
boolean isValid = false;
for (String suggestion : listSuggestion) {
if (actv.getText().equalsIgnoreCase(suggestion))
isValid = true;
}
If isValid = false, show toast.
I am using dynamic and static spinner.
This is my code, how can I implement a HashMap to show what the user selects (values)?
public class DatosAutoActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner sp_marca, sp_modelo, sp_colores;
private TextView tvMarca, tvModelo, tvColor, tvPlacas;
private Button btn_enviarDatos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_auto);
sp_marca = (Spinner)findViewById(R.id.sp_marca);
sp_modelo = (Spinner)findViewById(R.id.sp_modelo);
sp_colores = (Spinner)findViewById(R.id.sp_colores);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
R.array.array_marcas,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_marca.setAdapter(adapter);
sp_marca.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapterColor = ArrayAdapter.createFromResource(
this,
R.array.array_colores,
android.R.layout.simple_spinner_item);
adapterColor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_colores.setAdapter(adapterColor);
sp_colores.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int[] marcas = {R.array.array_chevrolet, R.array.array_ford, R.array.array_honda,
R.array.array_nissan,R.array.array_renault, R.array.array_toyota,
R.array.array_volkswagen};
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
marcas[position],
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_modelo.setAdapter(adapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
protected void onResume() {
super.onResume();
btn_enviarDatos = (Button)findViewById(R.id.btn_enviarDatos);
btn_enviarDatos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent siguiente = new Intent(DatosAutoActivity.this, VerificacionDatosActivity.class);
startActivity(siguiente);
}
else {
Toast.makeText(getApplicationContext(), "Debes llenar todos los campos", Toast.LENGTH_SHORT).show();
}
});
}
}
Using Hashmap hope this will help you.
Value for spinner
String[] spinnerArray = new String[array.size()];
HashMap<Integer,String> spinnerMap = new HashMap<Integer, String>();
for (int i = 0; i < array.size(); i++)
{
spinnerMap.put(i,array.get(i));
spinnerArray[i] = array.get(i);
}
Set value to spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Get value from spinner
String name = spinner.getSelectedItem().toString();
String id = spinnerMap.get(spinner.getSelectedItemPosition());
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) {
}
});
}
}
}
}