java - How to initialize a JSONArray and use in other methods -
i'm going initialize jsonarray , set input of method copies jsonarray arraylist.
this method:
public arraylist<string> copyjsonarraytoarraylist(jsonarray jarray){ arraylist<string> arraylist = new arraylist<> (); (int = 0; < jarray.length(); i++) { try { arraylist.add(jarray.getjsonobject(i).getstring("city")); } catch (jsonexception e) { e.printstacktrace(); } } return arraylist; } and code:
requestqueue queue = volley.newrequestqueue(getapplicationcontext()); stringrequest stringrequest = new stringrequest(request.method.get, ws_get_city, new response.listener<string>() { @override public void onresponse(string response) { progressbar.setvisibility(view.gone); try { jsonobject = new jsonobject(response); jsonarray = jsonobject.getjsonarray("getcity"); } catch (jsonexception e) { e.printstacktrace(); } } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { toast.maketext(getapplicationcontext(), "error", toast.length_short).show(); progressbar.setvisibility(view.gone); } }); queue.add(stringrequest); ac_srccity = (autocompletetextview) findviewbyid(r.id.ac_srccity); arrayadapter<string> adaptersrc = new arrayadapter<>(this, android.r.layout.simple_list_item_1, copyjsonarraytoarraylist(jsonarray)); ac_srccity.setadapter(adaptersrc); but when use jsonarray method input says jsonarray null ! debugged code , understood sequence of execution this:
1.
requestqueue queue = volley.newrequestqueue(getapplicationcontext()); 2.
queue.add(stringrequest); 3.
ac_srccity = (autocompletetextview) findviewbyid(r.id.ac_srccity); 4.
arrayadapter<string> adaptersrc = new arrayadapter<>(this, android.r.layout.simple_list_item_1, copyjsonarraytoarraylist(jsonarray)); and in line 4 jsonarray null !
any idea !?
your jsonarray isn't being instantiated until callback in onresponse(string), until stringrequest finished jsonarray null. instead move inititlization callback so:
requestqueue queue = volley.newrequestqueue(getapplicationcontext()); stringrequest stringrequest = new stringrequest(request.method.get, ws_get_city, new response.listener<string>() { @override public void onresponse(string response) { progressbar.setvisibility(view.gone); try { jsonobject = new jsonobject(response); jsonarray = jsonobject.getjsonarray("getcity"); ac_srccity = (autocompletetextview) findviewbyid(r.id.ac_srccity); arrayadapter<string> adaptersrc = new arrayadapter<>(this, android.r.layout.simple_list_item_1, copyjsonarraytoarraylist(jsonarray)); ac_srccity.setadapter(adaptersrc); } catch (jsonexception e) { e.printstacktrace(); } } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { toast.maketext(getapplicationcontext(), "error", toast.length_short).show(); progressbar.setvisibility(view.gone); } }); queue.add(stringrequest);
Comments
Post a Comment