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.
Related
I am trying to fetch two different objects from JSON array, but somehow I am unable to fetch second object ("opening_hours"). Not sure if am i Parsing it correctly. I also want to get element "open_now" from "opening_hours" and set it to method "SetAuthor". Below is the code url for JSON array :
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&radius=500&types=food&name=%22%20+%20cafe+%20%22&key=AIzaSyD_kA7xtNYffQNlykVkVGk5ZNQgQtZFZTk
#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);
}
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;
}
} catch (JSONException e3) {
e3.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return false;
}
Full Activity Code :
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);
}
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;
}
} 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();
}
}
}
Elements.java
public class Elements {
private String title;
private String description;
private String author;
private String publishedat;
private String urltoimage;
public Elements() {
// TODO Auto-generated constructor stub
}
public Elements(String title, String description, String author,
String publishedat, String urltoimage) {
this.title = title;
this.description = description;
this.author = author;
this.publishedat = publishedat;
this.urltoimage = urltoimage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublishedat() {
return publishedat;
}
public void setPublishedat(String publishedat) {
this.publishedat = publishedat;
}
public String getImage() {
return urltoimage;
}
public void setImage(String urltoimage) {
this.urltoimage = urltoimage;
}
}
First of all "opening_hours" is a JSONObject not a JSONArray.
Second thing "opening_hours" object inside "result" array.
So parsing should be 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);
// add here
JSONObject jarraytwo = jsono.getJSONObject("opening_hours");
}
try this JSON parsing
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 = object.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);
}
}
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...
In my application after parsing json data i want to send the data from one activity to another activity with the help of intents. but in my second activity it shows only last array json data. it is not showing all the json parsed data in second activity.
first activity:
private class GetData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("COMPANYNAME", CompanyName);
Log.v("TAG_COMPANYNAME",""+CompanyName);
intent.putExtra("COMPANYID", companyid);
intent.putExtra("BUSFARE", fare);
intent.putExtra("BUSLABEL", buslabel);
intent.putExtra("BUSTYPENAME", bustypename);
intent.putExtra("AVALIABLESEATS", avaliableseats);
// intent.putExtra("arrayListIdentifier",);
startActivity(intent);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
secondActivity:
Intent intent = getIntent();
String company_name = intent.getStringExtra("COMPANYNAME");
String company_id = intent.getStringExtra("COMPANYID");
String bus_fare = intent.getStringExtra("BUSFARE");
String bus_typename = intent.getStringExtra("BUSTYPENAME");
String bus_label = intent.getStringExtra("BUSLABEL");
String avaliable_seats = intent.getStringExtra("AVALIABLESEATS");
BusData bs = new BusData();
bs.setCompanyname(company_name);
bs.setCompanyid(company_id);
bs.setFare(bus_fare);
bs.setBuslabel(bus_label);
bs.setBustypename(bus_typename);
bs.setAvaliableseats(avaliable_seats);
bdata.add(bs);
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
fromto is a listview.
the size of bdata is 1.
Use Bundle to pass the value from current activity to next acivity
Current Activtiy to pass data
if(issuceess.equals("true"))
{
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
intent.putExtra("json_objcet", result.toString());//result is a json object
startActivity(intent);
}
In Next activity to receive data
Intent intent = getIntent();
String json_object = intent.getStringExtra("json_objcet");
try
{
JSONObject result = new JSONObject(json_object);
JSONArray routearray = result.getJSONArray("Route");
for (int i = 0; i < routearray.length(); i++) {
String companyid = routearray.getJSONObject(i).getString("CompanyId");
String CompanyName = routearray.getJSONObject(i).getString("CompanyName");
String deptime = routearray.getJSONObject(i).getString("DepTime");
String routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
String arrtime = routearray.getJSONObject(i).getString("ArrTime");
String fare = routearray.getJSONObject(i).getString("Fare");
String hasac = routearray.getJSONObject(i).getString("HasAC");
String hasnac = routearray.getJSONObject(i).getString("HasNAC");
String hasseater = routearray.getJSONObject(i).getString("HasSeater");
String hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
String isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
String buslabel = routearray.getJSONObject(i).getString("BusLabel");
String avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
String bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bs = new BusData();
bs.setCompanyname(CompanyName);
bs.setCompanyid(companyid);
bs.setFare(fare);
bs.setBuslabel(buslabel);
bs.setBustypename(bustypename);
bs.setAvaliableseats(avaliableseats);
bdata.add(bs);
}
BusDataAdapter adapter = new BusDataAdapter(this, bdata);
fromto.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
try this code
first activity
private class GetData extends AsyncTask<String, Void, JSONObject> {
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SearchActivity.this, "", "");
}
#Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("FromCityid",fromcity_bus));
nameValuePair.add(new BasicNameValuePair("Tocityid",tocity_bus));
nameValuePair.add(new BasicNameValuePair("DOJ",journey_bus));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
// Log.v("TAG_RESULT",""+result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("Response");
String message = jobj.getString("Message");
String issuceess = jobj.getString("IsSuccess");
Log.v("TAG_Message",""+message);
Log.v("TAG_Message",""+issuceess);
if(issuceess.equals("true"))
{
JSONArray routearray = result.getJSONArray("Route");
for(int i = 0; i<routearray.length(); i++)
{
companyid = routearray.getJSONObject(i).getString("CompanyId");
CompanyName = routearray.getJSONObject(i).getString("CompanyName");
deptime = routearray.getJSONObject(i).getString("DepTime");
routeScheduleId = routearray.getJSONObject(i).getString("RouteScheduleId");
arrtime =routearray.getJSONObject(i).getString("ArrTime");
fare =routearray.getJSONObject(i).getString("Fare");
hasac = routearray.getJSONObject(i).getString("HasAC");
hasnac = routearray.getJSONObject(i).getString("HasNAC");
hasseater = routearray.getJSONObject(i).getString("HasSeater");
hassleeper = routearray.getJSONObject(i).getString("HasSleeper");
isvolvo = routearray.getJSONObject(i).getString("IsVolvo");
buslabel = routearray.getJSONObject(i).getString( "BusLabel");
avaliableseats = routearray.getJSONObject(i).getString("AvailableSeats");
bustypename = routearray.getJSONObject(i).getString("BusTypeName");
BusData bData = new BusData(companyid,CompanyName,fare,buslabel,bustypename,avaliableseats,);
arrayBusData.add(bData);
}
Intent intent=new Intent(SearchActivity.this,FromtoActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("bus_data", arrayBusData);
intent.putExtras(bundleObject);
startActivity(intent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
second activity
ArrayList<BusData> arrayBusData = new ArrayList<BusData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle bundleObject = getIntent().getExtras();
arrayBusData = (ArrayList<BusData>) bundleObject
.getSerializable("requestProductItem");
BusDataAdapter adapter = new BusDataAdapter(this, arrayBusData);
fromto.setAdapter(adapter);
}
BusData class also create constructor in BusData class
public class BusData implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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 + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}
I am converting my HTTP calls to asynchronous calls from synchronous ones. Because the connection is running in the background the data isn't there when I originally set my list adaptor. How can I get the list adaptor to update after my HTTP call? I've tried a few things like not setting the adaptor until data gets sent back and setting the adaptor again, but nothing has worked. Here's my current oncreate code
protected void onCreate(Bundle savedInstanceState) {
overridePendingTransition(R.layout.anim_out,R.layout.anim_in);
setTheme(R.style.Theme_D_theme);
setContentView(R.layout.news_fragment);
super.onCreate(savedInstanceState);
text = (TextView) this.findViewById(R.id.nomore);
list = (ListView) this.findViewById(R.id.newslist);
list.setDividerHeight(2);
new MyAsyncTask().execute("THIS");
list.setOnItemClickListener(this);
list.setCacheColorHint(Color.WHITE);
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
}
And my AsyncTast
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}
in on post execution add this line. in the end.
x.add(temp);
adapter.notifyDataSetChanged();
Do this way
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
//UPDATE HERE
adapter = new SimpleAdapter(this, x, R.layout.drill1_listview,
new String[] {"title","content","distance", "image"},
new int[] {R.id.title, R.id.content, R.id.distance, R.id.image} );
list.setAdapter(adapter);
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
HttpClient httpclient = new DefaultHttpClient();
String type = getIntent().getExtras().getString("type");
HttpGet httppost = new HttpGet("http://myip.../all?latitude=42.12345&longitude=-76.2154");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String JSONstring = EntityUtils.toString(entity);
Log.w("HTTPRESPONSE", JSONstring);
//Toast.makeText(this, JSONstring, Toast.LENGTH_SHORT).show();
if (!(JSONstring.equals(" 0"))) {
JSONArray array = new JSONArray(JSONstring);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
HashMap<String,String> temp = new HashMap<String,String>();
String thisid = row.getString("id");
ider.add(thisid);
String starthold = row.getString("start_time");
start.add(starthold);
String endhold = row.getString("end_time");
end.add(endhold);
String latitudehold = row.getString("latitude");
latitude.add(latitudehold);
String longitudehold = row.getString("longitude");
longitude.add(longitudehold);
String addresshold = row.getString("street");
address.add(addresshold);
String title = row.getString("company");
company.add(title);
temp.put("title", title);
String distance_hold = row.getString("distance");
distance.add(distance_hold);
temp.put("distance", distance_hold);
int[] images = new int[] { R.drawable.local_eat,R.drawable.local_eat,
R.drawable.local_drink, R.drawable.local_shop,
R.drawable.local_do, R.drawable.local_chance,
R.drawable.local_all };
String image = row.getString("promo_type");
temp.put("image", Integer.toString(images[Integer.valueOf(image)]));
String description = row.getString("name");
name.add(description);
temp.put("content", description);
x.add(temp);
}
}
} catch (Exception e) {
// Oops
} finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
}
}