Whenever I am trying to remove an object from JsonArray , It shows there is no such method exists. My target API version is 8. I look up for other questions regarding this but could not find a suitable solution. please help me with this.
class JSONAsync extends AsyncTask<String, Void, JSONArray>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = Util.setProgressDialog(Activity.this, "Please Wait",
"loading....", false);
progressDialog.show();
}
#Override
protected JSONArray doInBackground(String... urls)
{
try
{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200)
{
HttpEntity entity = response.getEntity();
String resString = EntityUtils.toString(entity);
JSONObject jso= new JSONObject(resString);
JSONArray jsono= jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsono);
for (int i = 0; i < jsono.length(); i++) {
if (jsono.getJSONObject(i).getString("jobName").equals(null) || jsono.getJSONObject(i).getString("jobName").equals("null") || jsono.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsono.getJSONObject(i).getString("jobName"));
jsono.remove(i);
}
}
if(jsono.length()>=0)
{
jobname = new String[(jsono.length())];
jobid = new String[(jsono.length())];
for(int i=0;i<jsono.length();i++)
{
JSONObject js = jsono.getJSONObject(i);
Log.e("Name : ", jsono.getJSONObject(i).getString("jobName"));
jobname[i] = jsono.getJSONObject(i).getString("jobName");
Log.e("Id : ", jsono.getJSONObject(i).getString("jobId"));
jobid[i] = jsono.getJSONObject(i).getString("jobId");
}
return jsono;
}
else
{
Toast.makeText(getApplicationContext(), "No Workers available : "+ logedinUserId , Toast.LENGTH_LONG).show();
return null;
}
}
} catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result)
{
progressDialog.dismiss();
}
}
Do you really want a headache supporting a bit amount of so old devices?
Nevertheless, use this:
JSONObject jso= new JSONObject(resString);
JSONArray jsonArray = jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsonArray);
ArrayList<Integer> i_ar = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.getJSONObject(i).getString("jobName").equals(null) || jsonArray.getJSONObject(i).getString("jobName").equals("null") || jsonArray.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsonArray.getJSONObject(i).getString("jobName"));
i_ar.add(i);
}
}
JSONArray jsono = new JSONArray();
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i_ar.indexOf(i) == -1)
{
list.put(jsonArray.get(i));
}
}
}
if(jsono.length()>=0)
{
//.... continue...
Related
I want to retrieve "opening_hour" object and parse "open_now" array. But I am unable to do that for some reason, may be my parsing hierarchy is wrong. Can someone suggest, how should it be. Below is my JSON link :
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.9647254,77.7191899&radius=500&name=cafe&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
}
JSONArray jarraytwo = jsono.getJSONArray("opening_hours");
for (int i = 0; i < jarraytwo.length(); i++) {
JSONObject objecttwo = jarraytwo.getJSONObject(i);
Elements parameterstwo = new Elements();
parameterstwo.setAuthor(objecttwo.getString("open_now"));
Toast.makeText(getApplicationContext(), "open_now : " + objecttwo.getString("open_now"), Toast.LENGTH_LONG).show();
elementListtwo.add(parameterstwo);
}
return true;
This is dumb question I know but I am unaware of nested json parsing. Below is my full code and link from where I am passing
public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
private static final int PERMISSION_ACCESS_COARSE_LOCATION = 1;
private GoogleApiClient googleApiClient;
int status;
ArrayList<String> result;
ArrayList<Elements> elementList;
ArrayList<Elements> elementListtwo;
ElementAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Welcome to Harman Framework");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//mVoiceInputTv.setText(result.get(0));
Toast.makeText(getApplicationContext(), "You searched : " + result.get(0), Toast.LENGTH_LONG).show();
elementList = new ArrayList<Elements>();
new JSONAsyncTask().execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ElementAdaptor(getApplicationContext(), R.layout.row, elementList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
Intent intent = new Intent(getApplicationContext(), DescriptionActivity.class);
intent.putExtra("title", elementList.get(position).getTitle());
intent.putExtra("author", elementList.get(position).getAuthor());
intent.putExtra("publishedat", elementList.get(position).getPublishedat());
intent.putExtra("description", elementList.get(position).getDescription());
intent.putExtra("imageurl", elementList.get(position).getImage());
startActivity(intent);
}
});
}
break;
}
}
}
//String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=" + result.get(0) + "&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk";
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading.......");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpParams params = httpclient.getParams();
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
}
return true;
}
} catch (JSONException e3) {
e3.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
You need to nest your for loops into each other. Take a look at the structure of your JSON-File: You have your jarray, which is an Array of JSON Objects. Each of these JSON Objects in the array have it's own opening hours. So you want somethin like this:
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Elements parameters = new Elements();
parameters.setTitle(object.getString("name"));
parameters.setImage(object.getString("icon"));
elementList.add(parameters);
// Get opnening hours for current result
JSONObject curOpeningHours = object.getJSONObject("opening_hours");
hoursList.push(curOpeningHours);
String openNow = curOpeningHours.getString("open_now");
// Do something...
}
It did not test this, but it should give you an idea
Use nested JSONObject
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
JSONArray jarray1 = object.getJSONArray("opening_hours");
for (int j = 0; j < jarray1.length(); j++) {
JSONObject object2 = jarray1.getJSONObject(j);
parameters.setOpenNow(object2.getString("open_now"));
}
}
I wouldn't use JSONObject at all when parsing a complex json or if the json at least contains an array of objects.
Instead use google-gson.
Using gson you can serialize/deserialize your json with less code and effort.
I would first create a java class that represents the same json scheme you're trying to parse.
for example, trying to parse this JSon String:
[
{
"FirstName": "What",
"LastName": "Ever"
},
{
"FirstName": "John",
"LastName": "Snow"
}
]
In java code, I would first create a class:
public class Person {
public String FirstName;
public String LastName;
}
Now to parse the json:
Gson gson = new Gson();
List<Person> people = gson.fromJson("Json string here", new TypeToken<List<Person>>() {}.getType());
Now you can simply do a loop on the list, and find John Snow.
I am working on application in which i want one output as shown in below image.
for that i tried following code:
private ListView notification_listview;
private String BeauticianId="98";
private String serviceType="all";
private ArrayList<NameValuePair> params11;
ArrayList<MainArray_method> MainList;
MainArray_adapter main_adapter;
ArrayList<SubArray_method> SubList;
SubArray_adapter sub_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification_listview = (ListView) findViewById(R.id.listView_notification);
}
#Override
public void onResume() {
super.onResume();
params11 = new ArrayList<NameValuePair>();
params11.add(new BasicNameValuePair("iBeauticianId", BeauticianId));
params11.add(new BasicNameValuePair("serviceType", serviceType));
new background().execute();
}
private class background extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/services", params11);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result", "" + result);
try {
JSONObject json = new JSONObject(result);
String status = json.getString("status");
Log.d("Status:", status);
String data = json.getString("data");
Log.d("Data:", data);
MainList = new ArrayList<MainArray_method>();
JSONArray MainArray = json.getJSONArray("data");
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
}
if (main_adapter== null && sub_adapter == null)
{
main_adapter=new MainArray_adapter(getApplicationContext(),MainList);
notification_listview.setAdapter(main_adapter);
sub_adapter=new SubArray_adapter(getApplicationContext(),SubList);
notification_listview.setAdapter(sub_adapter);
} else {
sub_adapter.notifyDataSetChanged();
main_adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
pDialog.dismiss();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
but in this i just get two record of subarray.
What should i do to get output as shown in image.
Thanks in advance.
JSON response:
{
"status":1,
"data":[
{
"iMainServiceId":1,
"main":"NAILS",
"sub":[
{
"iSubServiceId":1,
"vName":"Manicure",
"fPrice":15,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":2,
"vName":"Gel Manicure",
"fPrice":25,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":5,
"vName":"Nail art ",
"fPrice":10,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":6,
"vName":"Nail Pain ",
"fPrice":10,
"vDuration":"20 Minutes"
}
]
},
{
"iMainServiceId":2,
"main":"HAIR",
"sub":[
{
"iSubServiceId":3,
"vName":"Haircuts",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":4,
"vName":"Hair color",
"fPrice":50,
"vDuration":"60 Minutes"
},
{
"iSubServiceId":7,
"vName":"Textures",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":8,
"vName":"Treatments",
"fPrice":30,
"vDuration":"60 Minutes"
}
]
},
{
"iMainServiceId":3,
"main":"Face",
"sub":[
{
"iSubServiceId":9,
"vName":"Facials",
"fPrice":20,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":10,
"vName":"Brow Bar",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":11,
"vName":"Makeup ",
"fPrice":40,
"vDuration":"49 Minutes"
}
]
},
{
"iMainServiceId":4,
"main":"Body",
"sub":[
{
"iSubServiceId":12,
"vName":"Hair Removal",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":13,
"vName":"Body Treatments",
"fPrice":30,
"vDuration":"30 Minutes"
}
]
}
]
}
and wt i get as enter image description hereoutput is:
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
// This should be in outer for loop<<---------------------<<<<<
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
}
The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
public void startBlat(String tosearch) {
AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
}
else {
asynctaskMovie.execute(tosearch);
}
The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {
JSONParser jsonParser = new JSONParser();
private static final String SEARCH_URL = "http://www.omdbapi.com/?";
#Override
protected void onPreExecute() {
super.onPreExecute();
movieArrayList = new ArrayList();
Log.i(getActivity().getCallingPackage(), "onPreExecute");
}
#Override
protected ArrayList<Movie> doInBackground(String... args) {
Log.i(getActivity().getCallingPackage(),"doInBackground");
HashMap<String, String> params = new HashMap<>();
params.put("s", args[0]);
params.put("r", "json");
JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
Log.i(getActivity().getCallingPackage(), json.toString());
if (json != null) {
try {
if (json.getString("Response").equals("False")) {
return movieArrayList;
}
} catch (JSONException e) {
}
try {
JSONArray jsonArray = json.getJSONArray("Search");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
if (!movieid.equals("null")) {
Movie movie = new Movie(movieid);
movieArrayList.add(movie);
}
}
jsonArray = new JSONArray();
for (Movie movie : movieArrayList) {
params = new HashMap<>();
params.put("i", movie.getMovieid());
params.put("plot", "short");
params.put("r", "json");
JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
if (jsongetfullinfo != null) {
jsonArray.put(jsongetfullinfo);
Log.i("", jsongetfullinfo.toString());
}
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
movieArrayList.get(i).updateFromIMDB(jObject);
}
for (Movie movie : movieArrayList) {
movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
}
return movieArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return movieArrayList;
}
#Override
protected void onPostExecute(ArrayList<Movie> movieArrayList) {
Log.i("ronen", "list size: " + movieArrayList.size());
if (movieArrayList.size() > 0) {
listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
listView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
}
}
private Bitmap LoadFromUrl(String theurl) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(theurl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return bmp;
}
}
I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.
Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!
In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.
I am fetching some data from php and trying to show that data in spinner through arrayadater, but there is a prob can
**DownloadDetails downloaddeatils = new DownloadDetails(this);
downloaddeatils.execute(url);
public class DownloadDetails extends AsyncTask<String, Void, String> {
Context context;
ProgressDialog progressDialog;
public DownloadDetails(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Fetching Data, please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String output = null;
for(String url: urls) {
output = getOutputFromUrl(url);
}
return output;
}**
private String getOutputFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject object = null;
JSONObject object1 = null;
JSONObject object2 = null;
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("speciality_id", sid));
nameValuePairs.add(new BasicNameValuePair("type",type));
nameValuePairs.add(new BasicNameValuePair("condition_id", cid));
nameValuePairs.add(new BasicNameValuePair("locality", locality));
nameValuePairs.add(new BasicNameValuePair("city_name", city_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost,
responseHandler);
Log.d("Respone",responseBody);
if(!responseBody.equals(null))
{
JSONObject jsonResponse = new JSONObject(responseBody);
object = jsonResponse.getJSONObject("firstarray");
object1 = jsonResponse.getJSONObject("secondarray");
object2 = jsonResponse.getJSONObject("thirdarray");
try {
if (!object.toString().trim().contains("null")) {
Log.d("Inside ","count"+count);
if (count == 0) {
JSONArray jArray = object.getJSONArray("values");
for (int i = 0; i < jArray.length(); i++) {
String str = jArray.getString(i).substring(0,
jArray.getString(i).length());
String[] data = str.split("_");
specialistList.add(data[0]);
specialistNameList.add("" + data[1]);
//specialistAdapter.add("" + data[1]);
}
//specialistAdapter.setNotifyOnChange(true);
count = 1;
}
}
if (!object1.toString().trim().contains("null")) {
JSONArray JArray1 = object1.getJSONArray("values1");
for (int i = 0; i < JArray1.length(); i++) {
String str = JArray1.getString(i).substring(0,
JArray1.getString(i).length());
String[] data = str.split("_");
conditionList.add(data[0]);
//conditionAdapter.add(data[1]);
conditionNameList.add(data[1]);
}
//conditionAdapter.setNotifyOnChange(true);
Log.d("Inside","SecondArray");
}
if (!object2.toString().trim().contains("null")) {
JSONArray JArray1 = object2.getJSONArray("values2");
for (int i = 0; i < JArray1.length(); i++) {
String str = JArray1.getString(i).substring(0,
JArray1.getString(i).length());
String[] data = str.split("_");
doctorIdList.add(data[0]);
doctorNameList.add(data[1]);
// adapter.add(data[1]);
}
// adapter.setNotifyOnChange(true);
}
} catch (Exception e) {
Log.d("Unknown exception",""+e);
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),"Unable to fetch data from server",Toast.LENGTH_LONG).show();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String output) {
super.onPostExecute(output);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
for(int i=0;i<specialistNameList.size();i++)
specialistAdapter.add(specialistNameList.get(i));
for(int j=0;j<conditionNameList.size();j++)
conditionAdapter.add(conditionNameList.get(j));
for(int k=0;k<doctorNameList.size();k++)
adapter.add(doctorNameList.get(k));
}
if(output != null) {
Toast.makeText(getApplicationContext(), "Cannot connect to Server",Toast.LENGTH_LONG).show();
}
else {
}
}
}
You should write code, which modify event thread, in onPostExecute(), or onPreExecute(), or onPublishedProgress() methods, not in doInBackground() methods.