Given below is my JSON and I want to access "trips" JSON array and want to place it in an array list so that I can use it in a spinner. How can I access trips JSON array directly and use as a ArrayList for spinner?
My JSON:
{
"trips": [
77
],
"status": {
"message": "Successfully fetched the Open trips ",
"code": 200
}
}
My Activity class:
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray(config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
You can get value from json array directly from its index.
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++) {
int value = array.getInt(i);
}
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++)
{
int value = array.getInt(i);
}
JSONObject objStates = yourJsonObject.getJSONObject(“status”);
String msg= objStates.getString(“message”)
Int code= objStates.getInt(“code”)
Try something like
try {
result = response.getJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Declare int value; and parse JSON:
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray("trips");
for (int i=0; i<result.length(); i++) {
value = result.getInt(i);
trips.add(String.valueOf(value));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
As you are using config.JSON_ARRAY key to parse in your code, what is the value for config.JSON_ARRAY. If config.JSON_ARRAY="trips" then fine and replace static "trips" key with yours config.JSON_ARRAY else follow mine static key to parse.
Just update your code with this one: In this I parsed the trips JSON array and added all the items to the trips ArrayList.
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
trips = new ArrayList<>();
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.optJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
Try this it works for me.
JSONObject object = jObj.getJSONObject(result);
Iterator<?> iterator = object.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
ArrayList<JSONObject> value = new ArrayList<>();
JSONArray jsonArray = object.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
value.add(jsonArray.getJSONObject(i));
}
System.out.println("key : " + key + " " + "value : " + value);
hm.put(key, value);
}
Related
I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
I'm trying to pass an ArrayList to a function which will then display it on a list format but it seems my parameters are wrong for Arrayadapter.
#Override
public void handleResult(final Result result) {
final RequestQueue mQueue = Volley.newRequestQueue(this);
String url = "https://fg3qzgb2va.execute-api.ap-southeast-1.amazonaws.com/sample";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length() ; i++) {
JSONObject jsonArray = response.getJSONObject(i);
String first = jsonArray.getString("Name");
String price = jsonArray.getString("Price");
int priceResult = Integer.parseInt(price);
String id = jsonArray.getString("id");
if(id.equals(result.getText())){
addItem.setName(first);
addItem.setPrice(priceResult);
MainActivity.resultTextView.setText("Name: " + addItem.getName() + "\n"+"Price: " + addItem.getPrice());
itemList = new ArrayList<>();
itemList.add(addItem.getName());
addItem.setName("");
addToList.addList(itemList);
}
//Storing into the list
}
} catch (JSONException e) {
e.printStackTrace();
}
public class AddToList extends AppCompatActivity {
ArrayAdapter<String> adapter;
public void addList(ArrayList<String> arrayList ){
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,arrayList);
adapter.notifyDataSetChanged();
MainActivity.list.setAdapter(adapter);
}
}
Try this
Remove line:
MainActivity.list.setAdapter(adapter);
Add:
ListView mList = MainActivity.list;
mList.setAdapter(adapter);
try to change public void addList(ArrayList<String> arrayList ) to public void addList(List<String> arrayList )
I don't know why the items added to ArrayList won't populate ListView, I tried checking if items are indeed added to ArrayList but it shows it does.
You can check the image of the added items here
Here is my code. I'm using another xml for checkedtextview so my listview will display items with checkboxes.
ArrayList<String> symptomsListTest = new ArrayList<>();
ListView chl1;
String URL = "***********";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
addListItem();
chl1 = (ListView) findViewById(R.id.checklistSample);
chl1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.symptoms_checklist, R.id.txt_title, symptomsListTest);
//ArrayAdapter<String> aa=new ArrayAdapter<String>(this,R.layout.symptoms_checklist, R.id.txt_title,symptomsListTest);
chl1.setAdapter(aa);
chl1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = ((TextView) view).getText().toString();
if(symptomsListTest.contains(selectedItem))
{
symptomsListTest.remove(selectedItem); //remove deselected item from the list of selected items
}
else
{
symptomsListTest.add(selectedItem); //add selected item to the list of selected items
}
}
});
}
public void addListItem()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1"))
{
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SAMPLE.this, ""+message,Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(SAMPLE.this, e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SAMPLE.this, error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
String result="success";
params.put("result", result);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
You are executing an AsyncTask which is giving a response after sometime, meanwhile the code of listView and it's adapter is already executed. You just need to add one line after the for loop like this :-
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
//** Add This line **
aa.notifyDataSetChanged();
And make sure your ArrayAdapter is declared global. Hope this helps.
I am new in android I work on a webservice application and the backend in laravel ,I want to read the trades and according to the job I find the tasks but I can not display the data it shows me this error msg ..
"org.json.JSONArray cannot be converted to JSONObject"
public static final String TacheNamearray = "libelle_tache";
public static final String TacheName = "libelle_tache";
public static final String JSON_ARRAY_TACHE = "result";
public static final String MetierNamearray = "libelle_metier";
public static final String MetierName = "libelle_metier";
public static final String JSON_ARRAY = "result";
private JSONArray result;
private ArrayList<String> arrayListTache;
TextView tacheename;
Spinner spinner_tache;
Spinner spinner;
Button button;
private GpsTracker gpsTracker;
private TextView tvLatitude,tvLongitude;
String URL_Post = "http://192.168.1.233/projet/public/api/getmetier";
private ArrayList<String> arrayList;
TextView employeename;
private TextView tvUsername, tvEmail;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recherche);
spinner= (Spinner) findViewById(R.id.spnrEmployee);
spinner_tache= (Spinner) findViewById(R.id.spnrTache);
tacheename= (TextView) findViewById(R.id.tvTache);
employeename= (TextView) findViewById(R.id.tvName);
button = (Button) findViewById(R.id.button);
tvLatitude = (TextView)findViewById(R.id.latitude);
tvLongitude = (TextView)findViewById(R.id.longitude);
arrayListTache = new ArrayList<String>();
userInfo = new UserInfo(this);
tvEmail = (TextView)findViewById(R.id.key_email);
String email = userInfo.getKeyEmail();
tvEmail.setText(email);
arrayList = new ArrayList<String>();
getMetiers();
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
//Setting the values to textviews for a selected item
String metier= arrayList.get(position);
getTaches(metier);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
employeename.setText("");
}
});
}
private void getMetiers() {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/getmetier",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
empdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void empdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(MetierNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
// arrayList.add(0,"Select Employee");
spinner.setAdapter(new ArrayAdapter<String>(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get student name of a particular position
private String getemployeeName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(MetierName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
public void getLocation(View view){
gpsTracker = new GpsTracker(RechercheActivity.this);
insert();
if(gpsTracker.canGetLocation()){
double latitude = gpsTracker.getLatitude();
double longitude = gpsTracker.getLongitude();
tvLatitude.setText(String.valueOf(latitude));
tvLongitude.setText(String.valueOf(longitude));
}else{
gpsTracker.showSettingsAlert();
}
Intent intent = new Intent(RechercheActivity.this,
TechnicienActivity.class);
startActivity(intent);
}
public void insert(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_Post, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplication(),response,Toast.LENGTH_LONG).show();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RechercheActivity.this,error+"",Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String,String>getParams()throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
String text1 = spinner.getSelectedItem().toString();
String lon = tvLongitude.getText().toString().trim();
String lat = tvLatitude.getText().toString().trim();
params.put("libelle_metier",text1);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getTaches(String metier) {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/gettaches",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result= j.getJSONArray(JSON_ARRAY_TACHE);
tachedetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void tachedetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayListTache.add(json.getString(TacheNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
// arrayListTache.add(0,"Select Employee");
spinner_tache.setAdapter(new ArrayAdapter<String>
(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayListTache));
}
//Method to get student name of a particular position
private String gettacheName(int position){
String libelle_tache="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
libelle_tache = json.getString(TacheName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return libelle_tache;
}
and the JSON part gives me that ..
[{"id":1,"libelle_metier":"metier 1","deleted_at":null,"created_at":"2018-04-03 09:12:37","updated_at":"2018-04-03 09:12:37"},{"id":2,"libelle_metier":"metier 2","deleted_at":null,"created_at":"2018-04-03 09:12:44","updated_at":"2018-04-03 09:12:44"},{"id":3,"libelle_metier":"metier 4","deleted_at":null,"created_at":"2018-04-03 09:46:36","updated_at":"2018-04-04 14:15:06"}]
and my PHP code and
class TechniciensController extends Controller
{
public function GetTechniciens()
{
return Technicien::all();
}
return json_encode(Technicien::all());
then you can use json_decode.
this line :
j = new JSONObject(response);
update it:
JSONArray jsonarray = new JSONArray(response);
i think it's works.
I've 2 APIs and two spinners: one for state's list and another for city's list. In some cases the city list's JSONArray might be null. So I want to check in volley's JSON parsing if its null then set some default message in spinner. But its not showing the default message. Instead its showing the city list of the state which is by default set. Is there any solution for this?
// null city list
{
"citylist": []
}
// JSON for state list
{
"statelist": [
{
"state_id": "1",
"state_name": "West bengal"
},
{
"state_id": "3",
"state_name": "Himachal Pradesh"
},
{
"state_id": "4",
"state_name": "Maharashtra"
},
{
"state_id": "11",
"state_name": "Queensland"
}
]
}
public class MainActivity extends AppCompatActivity {
private static final String STATE = "http://example.com/ubooktoday/android/showstatebycountry";
private static final String CITY = "http://example.com/ubooktoday/android/showcitybystate";
Spinner spin1, spin2;
String stateid, cityid, zipid;
ArrayList<String> namelist, idlist;
ArrayAdapter<String> adapter;
HashMap<String,String> spinnerMap1, spinnerMap2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin1=(Spinner)findViewById(R.id.spin1);
spin2=(Spinner)findViewById(R.id.spin2);
namelist = new ArrayList<String>();
idlist = new ArrayList<String>();
loadstate();
spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String statename = spin1.getSelectedItem().toString();
stateid = spinnerMap1.get(statename);
//Toast.makeText(getApplicationContext(), stateid, Toast.LENGTH_SHORT).show();
loadcity();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spin2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String cityname = spin2.getSelectedItem().toString();
cityid = spinnerMap2.get(cityname);
Toast.makeText(getApplicationContext(), cityid, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void loadstate() {
if(namelist!=null )namelist.clear();
if(idlist!=null )idlist.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, STATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("statelist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
namelist.add(obj.getString("state_name"));
idlist.add(obj.getString("state_id"));
String[] spinnerArray = new String[idlist.size()];
spinnerMap1 = new HashMap<String, String>();
for (int j = 0; j < idlist.size(); j++)
{
spinnerMap1.put(namelist.get(j),idlist.get(j));
spinnerArray[j] = namelist.get(j);
}
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, spinnerArray);
spin1.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country_id", "2");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private void loadcity() {
if(namelist!=null )namelist.clear();
if(idlist!=null )idlist.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST, CITY,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("citylist");
if(jsonArray.equals("null")){
namelist.add("No Items");
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, namelist);
spin2.setAdapter(adapter);
}else{
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
namelist.add(obj.getString("city_name"));
idlist.add(obj.getString("city_id"));
String[] spinnerArray = new String[idlist.size()];
spinnerMap2 = new HashMap<String, String>();
for (int j = 0; j < idlist.size(); j++)
{
spinnerMap2.put(namelist.get(j),idlist.get(j));
spinnerArray[j] = namelist.get(j);
}
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, spinnerArray);
spin2.setAdapter(adapter);
}
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("state_id", stateid);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
Use below code for checking json array condition,
if(jsonArray == null || jsonArray.equals("null") || jsonArray.length <= 0)
{
namelist.add("No Items");
adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, namelist);
spin2.setAdapter(adapter);
}