set spinner blank if jsonarray is null - android

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);
}

Related

while sending array from android to server 1st element sets at server side 0 value but in android it sets correct value what is the solution

server data
android data
I am passing arraylist of srid of all element and post to server using volley request.enter image description here
here is the code
public class AttendenceShowStdList extends AppCompatActivity {
ActivityAttendenceShowStdListBinding AttendenceShowStdList;
ArrayList<AttStdListModel> userlist = new ArrayList<>();
ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
ArrayList<AllStdListModel> stdlist = new ArrayList<>();
AttStdListAdapter adapter;
private DatePickerDialog datePickerDialog;
private String date,clid,sectionId,yrId,instId,usid,usType,attdate;
SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch
private static final String SHARED_PREF_NAME_TEACH="myprefteach";
private static final String Key_USID_TEACH = "techusid";
private static final String Key_INSTID_TEACH = "techinstid";
private static final String Key_USTYPE_TEACH = "techustype";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
setContentView(AttendenceShowStdList.getRoot());
sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);
//getting data from TakeAttendenceAdapter cardview
clid=getIntent().getExtras().getString("ClassId");
sectionId=getIntent().getExtras().getString("sectionId");
Log.d("cliddd",clid);
yrId=getIntent().getExtras().getString("YearId");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.format(new Date());
Log.d("dttt",date);
userlist = (ArrayList<AttStdListModel>) getModel(false);
adapter = new AttStdListAdapter(this,userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
// recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// recyclerView.setHasFixedSize(true);
getData();
//toolbar
setSupportActionBar(AttendenceShowStdList.toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitAttendence();
// Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
// startActivity(intent);
}
});
}
private List<AttStdListModel> getModel(boolean isSelect){
List<AttStdListModel> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
AttStdListModel model = new AttStdListModel();
model.setSelected(isSelect);
// model.setStud_name(String.valueOf(list.get(i)));
model.setAdmi_id(String.valueOf(list.get(i)));
list.add(model);
}
return list;
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
JSONArray jsonArray5=respObj.getJSONArray("studatt_details");
Log.d("std details",jsonArray5.toString());
for(int i=0;i<jsonArray5.length();i++){
JSONObject jsonObject=jsonArray5.getJSONObject(i);
String sr_id=jsonObject.optString("sr_id");
String admi_id=jsonObject.optString("admi_id");
String stud_name=jsonObject.optString("stud_name");
String stud_phone=jsonObject.optString("stud_phone");
String stud_email=jsonObject.optString("stud_email");
String attd_status=jsonObject.optString("attd_status");
String attd_reason=jsonObject.optString("attd_reason");
userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
Log.d("s", String.valueOf(userlist));
list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new AttStdListAdapter(getApplicationContext(),userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("get_studattd","1");
params.put("us_id",usid);
params.put("inst_id",instId);
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("stud_attend_date",date);
return params;
}
};
queue.add(request);
}
//submit attendence
private void submitAttendence() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
String msg=respObj.getString("message");
Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
Log.d("response msg",msg);
if(msg.equals("Attendance Generated Successfully..!")){
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
Log.d("error msg", String.valueOf(error));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
ArrayList<String> allstdsrid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdsrid.add(String.valueOf(list.get(i).getSr_id()));
}
params.put("sr_id", String.valueOf(allstdsrid));
Log.d("params", String.valueOf(params));
Log.d("allstudentsrid", String.valueOf(allstdsrid));
ArrayList<String> allstdadmid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdadmid.add(list.get(i).getAdmi_id());
params.put("admission_id", String.valueOf(allstdadmid));
}
Log.d("allstudentsadmid", String.valueOf(allstdadmid));
///selected student list
ArrayList<String> attstd = new ArrayList<String>();
for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
if (AttStdListAdapter.userlist.get(i).getSelected()) {
attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
}
}
params.put("student_attend_submit","1");
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("att_status", String.valueOf(attstd));
Log.d("params", String.valueOf(params));
params.put("stud_attend_date",date);
params.put("inst_id",instId);
params.put("us_id",usid);
params.put("us_type",usType);
return params;
}
};
queue.add(request);
}
//toolbar back to home
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
After submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.

Now i want to display the specific data form that listview into another listview using the ArrayAdapter

String url = "http://example.com/bilal/fetchparty.php";
StringRequest sr = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("data");
cid = new String[ja.length()];
cname = new String[ja.length()];
username = new String[ja.length()];
name1 = new String[ja.length()]; //for size
timetaken = new String[ja.length()];
link = new String[ja.length()];
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
for (int i = 0; i < ja.length(); i++) {
JSONObject job = ja.getJSONObject(i);
cid[i] = job.getString("cid");
cname[i] = job.getString("cname");
username[i] = job.getString("username");
timetaken[i] = job.getString("timetaken");
link[i] = job.getString("link");
if (cid[i].equals(shared1.sp1.getString("pid", null)) && cname[i].equals(shared1.sp1.getString("title", null))) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("cid", cid[i]);
hashMap.put("cname", cname[i]);
hashMap.put("username", username[i]);
hashMap.put("timetaken", timetaken[i]);
hashMap.put("link", link[i]);
arrayList.add(hashMap);
Toast.makeText(Vote.this, username[i], Toast.LENGTH_SHORT).show();
nameCall (username);
}
}
String[] from = {"username", "timetaken", "link"};
int[] to = {R.id.tvUsername, R.id.tvTime, R.id.tvLink};
SimpleAdapter sa = new SimpleAdapter(Vote.this, arrayList, R.layout.vote, from, to);
lvVote.setAdapter(sa);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Vote.this);
requestQueue.add(sr);
lvVote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bi = link[position];
Toast.makeText(Vote.this, bi, Toast.LENGTH_SHORT).show();
}
});
}
private void nameCall(final String name[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, name);
lvVoteNow.setAdapter(adapter);
bVoteSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int p;
String s;
p = lvVoteNow.getCheckedItemPosition();
if (p != ListView.INVALID_POSITION) {
s = name[p];
Toast.makeText(Vote.this, "You voted for " + s, Toast.LENGTH_SHORT).show();
//use s here
s = null;
} else {
Toast.makeText(Vote.this, "Please Give Your Vote", Toast.LENGTH_SHORT).show();
}
}
});
}
I fetch the data from the online server and display the data into the ListView using the simpleAdapter. Now i want to display the specific data form that Listview into another Listview using the ArrayAdapter
But it is displaying the whole list not according the if condition in the second ListView i.e lvVoteNow
This is my code
public class Vote extends AppCompatActivity {
ListView lvVote,lvVoteNow;
TextView tvUsername,tvTime,tvLink,cidVote,cnameVote;
List<String> testUserName = new ArrayList<>();
Button bVoteSubmit;
String bi;
String [] cid,cname,username,timetaken,link,name1,name2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote);
lvVoteNow = findViewById(R.id.lvVoteNow);
bVoteSubmit = findViewById(R.id.bVoteSubmit);
tvUsername = findViewById(R.id.tvUsername);
tvTime = findViewById(R.id.tvTime);
tvLink = findViewById(R.id.tvLink);
cidVote = findViewById(R.id.cidVote);
cnameVote = findViewById(R.id.cnameVote);
lvVote = findViewById(R.id.lvVote);
lvVote.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
final Shared shared1 = new Shared(getApplicationContext());
cidVote.setText(shared1.sp1.getString("pid", null));
cnameVote.setText(shared1.sp1.getString("title", null));
//fetching data for vote
String url = "http://example.com/bilal/fetchparty.php";
StringRequest sr = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("data");
cid = new String[ja.length()];
cname = new String[ja.length()];
username = new String[ja.length()];
name1 = new String[ja.length()]; //for size
timetaken = new String[ja.length()];
link = new String[ja.length()];
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
for (int i = 0; i < ja.length(); i++) {
JSONObject job = ja.getJSONObject(i);
cid[i] = job.getString("cid");
cname[i] = job.getString("cname");
username[i] = job.getString("username");
timetaken[i] = job.getString("timetaken");
link[i] = job.getString("link");
if (cid[i].equals(shared1.sp1.getString("pid", null)) && cname[i].equals(shared1.sp1.getString("title", null))) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("cid", cid[i]);
hashMap.put("cname", cname[i]);
hashMap.put("username", username[i]);
hashMap.put("timetaken", timetaken[i]);
hashMap.put("link", link[i]);
arrayList.add(hashMap);
Toast.makeText(Vote.this, username[i], Toast.LENGTH_SHORT).show();
testUserName.add(username[i]); // add userName to list
// nameCall (username);
}
}
//after all specific users add on list to this
String[] stringArray = testUserName.toArray(new String[0]);
nameCall(stringArray);
String[] from = {"username", "timetaken", "link"};
int[] to = {R.id.tvUsername, R.id.tvTime, R.id.tvLink};
SimpleAdapter sa = new SimpleAdapter(Vote.this, arrayList, R.layout.vote, from, to);
lvVote.setAdapter(sa);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Vote.this);
requestQueue.add(sr);
lvVote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bi = link[position];
Toast.makeText(Vote.this, bi, Toast.LENGTH_SHORT).show();
}
});
}
private void nameCall(final String name[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, name);
lvVoteNow.setAdapter(adapter);
bVoteSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int p;
String s;
p = lvVoteNow.getCheckedItemPosition();
if (p != ListView.INVALID_POSITION) {
s = name[p];
Toast.makeText(Vote.this, "You voted for " + s, Toast.LENGTH_SHORT).show();
//use s here
s = null;
} else {
Toast.makeText(Vote.this, "Please Give Your Vote", Toast.LENGTH_SHORT).show();
}
}
});
}
}

how to access an element of an JSON array

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);
}

How to parse a field in JSON in to a String array

This is my JSON,
[{
"album_id": "71",
"user_id": "38",
"category_name": "Gallery 1",
"album_image": "../images/album/gallery1rapport3871.jpg",
"org_image_name": "Love-Couple-3.jpg",
"date": "16-10-2016",
"status": "0"
}, {
"album_id": "73",
"user_id": "38",
"category_name": "Gallery 1",
"album_image": "../images/album/gallery1rapport3873.jpeg",
"org_image_name": "t1.daumcdn.net.jpeg",
"date": "16-10-2016",
"status": "0"
}]
I am tring to fetch all the org_image_name values. But I am only getting one value when I display it using a Toast.
Here is my code. Please help me.
public class Album_Display extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
public static TextView cart_count,disp;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
disp = (TextView) findViewById(R.id.top_Album_text);
disp.setText(Disp);
Datas.Uid=Uid;
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(Album_Display.this);
pDialog.setMessage("Loading...");
pDialog.show();
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_Gallery1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(Album_Display.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
grid1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Album_Display.this, Display.class);
intent.putExtra("count", xl);
intent.putExtra("pos", position);
startActivity(intent);
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
public void back(View view){
finish();
}
public void upload_img(View view){
Intent in = new Intent(Album_Display.this, Image_Upload.class);
startActivity(in);
}
public void select(View view){
Toast.makeText(getApplication(), imagename, Toast.LENGTH_LONG).show();
Intent in=new Intent(Album_Display.this,Album_Select.class);
in.putExtra("category_name", category);
in.putExtra("album_id", selected);
in.putExtra("org_image_name", imagename);
startActivity(in);
}
}
Look at the value of "org_image_name" property. The JSON response as itself is returning a String value instead of an Array. First I think it should represent the response like following,
"org_image_name":["imgOne.jpg", "imgTwojpg"],
"date": "16-10-2016",
"status": "0"
Then you comes to a point where you need to parse it as a String array.

How to create ExpandableListview with json data in Android

can anyone suggest that how to create expandable list-view with Json data, i want to parse json data in my expandable list view, plss suggest how can i create
This is exactly what you looking for,you can parse and display data to ExpandableListview
See this : http://www.tutorialsbuzz.com/2015/02/android-expandable-listview-json-http.html
public class MainActivity extends Activity {
String url = "http://api.tutorialsbuzz.com/cricketworldcup2015/cricket.json";
ProgressDialog PD;
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandList = (ExpandableListView) findViewById(R.id.exp_list);
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
makejsonobjreq();
}
private void makejsonobjreq() {
PD.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Group> list = new ArrayList<Group>();
ArrayList<Child> ch_list;
try {
Iterator<String> key = response.keys();
while (key.hasNext()) {
String k = key.next();
Group gru = new Group();
gru.setName(k);
ch_list = new ArrayList<Child>();
JSONArray ja = response.getJSONArray(k);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
Child ch = new Child();
ch.setName(jo.getString("name"));
ch.setImage(jo.getString("flag"));
ch_list.add(ch);
} // for loop end
gru.setItems(ch_list);
list.add(gru);
} // while loop end
ExpAdapter = new ExpandListAdapter(
MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
PD.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
}
});
MyApplication.getInstance().addToReqQueue(jsonObjReq, "jreq");
}
}

Categories

Resources