Get Specific data from json services while populating List - android

i need to populate a list view from data coming under the tag "group" from a JSON array "video". the coding under it is working fine if i remove if condition. Please help me guys. My boss is kicking my ass for this and my job is on the line. thanks in advance
public class CountryJSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jCountries = null;
try {
// Retrieves all the elements in the 'countries' array
jCountries = jObject.getJSONArray("video");
}
catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getCountries(jCountries);
}
private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
int countryCount = jCountries.length();
List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> country = null;
// Taking each country, parses and adds to list object
for(int i=0; i<countryCount;i++){
try {
// Call getCountry with country JSON object to parse the country
country = getCountry((JSONObject)jCountries.get(i));
countryList.add(country);
} catch (JSONException e) {
e.printStackTrace();
}
}
return countryList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getCountry(JSONObject jCountry){
HashMap<String, Object> country = new HashMap<String, Object>();
String countryName = "";
String flag="";
String language = "";
String capital = "";
String currencyCode = "";
String currencyName = "";
try {
countryName = jCountry.getString("Description");
flag = jCountry.getString("thumbnailUrl");
capital = jCountry.getString("title");
language=jCountry.getString("group");
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
if(language.equals("RokuTest-VideoGroup")){
country.put("country", countryName);
country.put("group", language);
country.put("flag", R.drawable.ic_launcher);
country.put("flag_path", flag);
country.put("details", capital);
Log.v("---","Country name: "+countryName+"Flag Url:"+flag+"Title"+capital);
}
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}

Rohit.. Just manage the code in if and else block. It should work as you are saying removing if is working fine.
if(language.equals("RokuTest-VideoGroup")) {
// do somthing
}
else {
// do something
}

Related

How to use Google Places API to search for addresses/places? Android

I want to know how I can use a string to get search results for an address or a place using Google Places API. Currently, I'm using Geocoder to get search results but the results I am getting are not complete or relevant to my current location. Please be a little descriptive because I haven't used Google Places API before. I have read this tutorial
but I can't quiet understand it. I will have a string input from the user in an EditText view and I want to use that string to show a list of matching addresses which are relevant to my current location.
Hi here i'm giving you simple example about autocomplete, if you want you can try other from referring google api site. Just follow few steps. Hope this help you to understand and do your work easily
Step 1.
In you Activity you need to use edit text as text changed listener, then call places api
et_Search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
placesTask = new PlacesTask();
String[] toPass = new String[2];
toPass[0] = s.toString();
placesTask.execute(toPass);
}
});
Step 2.
here is calling for google places api
// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String> {
private String val = "";
#Override
protected String doInBackground(String... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key="+getResources().getString(R.string.google_server_key);
String input="";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String parameters = input+"&"+key + "&components=country:in";
// Output format +gpsTracker.getLatitude() + "," + gpsTracker.getLongitude() + "&radius=20000
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
try{
// Fetching the data from we service
data = Webservices.ApiCallGet(url);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Creating ParserTask
parserTask = new ParserTask();
String[] strData = new String[2];
strData[0] = result;
// Starting Parsing the JSON string returned by Web Service
parserTask.execute(strData);
}
}
Step 3. Getting Result
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
// Getting the parsed data as a List construct
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] { "description"};
int[] to = new int[] { android.R.id.text1 };
AutoCompleteAdapter adapter = new AutoCompleteAdapter(getBaseContext(), result);
// Setting the adapter
if(adapter != null && result != null )
lv_SearchList.setAdapter(adapter);
}
}
// Fetches latitude & longitude from place id
private class LatLongTask extends AsyncTask<Void, Void, String> {
private HashMap<String, String> placeMap;
private ProgressDialog dialog;
public LatLongTask(HashMap<String, String> placeMap){
this.placeMap = placeMap;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(SearchActivity.this, "", "Please Wait...",
true, false);
}
#Override
protected String doInBackground(Void... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key="+getResources().getString(R.string.google_server_key);
String input="";
try {
input = "placeid=" + URLEncoder.encode(placeMap.get("place_id"), "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// Building the parameters to the web service
String parameters = input+"&"+key ;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
try{
// Fetching the data from we service
data = Webservices.ApiCallGet(url);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(dialog!= null && dialog.isShowing()){
dialog.dismiss();
}
try {
JSONObject jResult = new JSONObject(result);
if(jResult.getString("status").equals("OK")) {
JSONObject jsonObject = jResult.getJSONObject("result");
JSONObject jGeometry = jsonObject.getJSONObject("geometry");
JSONObject jLocation = jGeometry.getJSONObject("location");
placeMap.put("lat", ""+jLocation.getString("lat"));
placeMap.put("lng", ""+jLocation.getString("lng"));
ArrayList<HashMap<String, String>> mapArrayList = new ArrayList<HashMap<String, String>>();
mapArrayList.add(placeMap);
Intent intent = new Intent();
intent.putExtra("result", mapArrayList);
if (getParent() == null) {
setResult(Activity.RESULT_OK, intent);
} else {
getParent().setResult(Activity.RESULT_OK, intent);
}
finish();
}else{
Utils.toastmessage(SearchActivity.this, "Please try again later.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Step 4. create this class
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("predictions");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String id="";
String reference="";
String description="";
String place_id = "";
try {
description = jPlace.getString("description");
id = jPlace.getString("id");
reference = jPlace.getString("reference");
place_id = jPlace.getString("place_id");
place.put("description", description);
place.put("_id",id);
place.put("reference",reference);
place.put("place_id", place_id);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}

Extracting STATUS code of Google Places API response

I am new to using JSON and I am having an issue figuring out how to extract the STATUS code from Google Places API response. I guess the issue is because it is a seperate root element from the results array. Here is my code for my parser:
public class PlaceJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity="-NA-";
String latitude="";
String longitude="";
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
Yes, status, results and html_attributions are the 3 root elements in google places api JSON response. You can extract the status data from the response like below:
String statuscheck = jObject.getString("status");

Loading image to ListView

I used this code to retrieve data from PHP and display into a listview.
I put HashMap collections to ArrayList, then insert ArrayList to SimpleAdapter to display on screen.
The problem is If i put into HashMap an element named "image" and value is image URL, SimpleAdapter do not show the image, it understand it as an String ( Not convert string to image ).
How to solve this problem ?
JSONObject jsonObject =
JSONParser.getJSONObject("xxxxxxx/android_get_places.php");
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("place");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = null;
try {
object = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String name = object.getString("name");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", name);
arrayList.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
setListAdapter(new SimpleAdapter(getApplicationContext(), arrayList, R.layout.place_item,
new String[]{"name"}, new int[]{R.id.title}));

How to parse nested json obiect

I've this json:
{"data": [{"name" "category" "id" "picture":{"data":{"url":}}}]
My difficulty is how to parse the picture field. I tried with this code:
public class JSONParser {
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jGames = null;
try {
jGames = jObject.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
return getGames(jGames);
}
private List<HashMap<String, Object>> getGames(JSONArray jGames){
int gameCount = jGames.length();
List<HashMap<String, Object>> gameList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> game = null;
for(int i=0; i<gameCount;i++){
try {
game = getGame((JSONObject)jGames.get(i));
gameList.add(game);
} catch (JSONException e) {
e.printStackTrace();
}
}
return gameList;
}
private HashMap<String, Object> getGame(JSONObject jGame){
HashMap<String, Object> game = new HashMap<String, Object>();
String gameName = "";
String logo="";
String user = "";
try {
gameName = jGame.getString("name");
logo = jGame.getString("logo_url");
user = jGame.getString("daily_active_users");
String details ="Utenti attivi : " + user + "\n";
game.put("name", gameName);
game.put("logo_url", R.drawable.icon);
game.put("logo_path", logo);
game.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
return game;
}
}
this tutorial will help you Android JSON Parsing Tutorial

How to display the parsed JSON data in android

I have parsed the JSON data and storing the parsed JSON data into ArrayList HashMap with the key value ,when I want to display the parsed data I am getting only the last value of the parsed Data rest all data are not displayed for reference
public HashMap<String,String> map = new HashMap<String, String>();
create HASHmap then arraylist
public static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
void parsing(JSONObject json)
{
String id="";
String countryn="";
try
{
countryobj = json.getJSONArray("country_details");
for(int i = 0;i<countryobj.length(); i++)
{
JSONObject items = countryobj.getJSONObject(i);
Log.e("i","value==="+i);
if(items.has("countryid"))
{
id = items.getString("countryid");
map.put("countryid",id);
Log.e("id","valueID==="+id);
}
if(items.has("country"))
{
countryn= items.getString("country");
map.put("country",countryn);
Log.e("counyrt","valueName==="+countryn);
}
contactList.add(i,map);
Log.e("lisvaluet","val--"+i +contactList.get(i));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
in Log I am getting only 08-20 12:13:45.830: E/--ID---(654): value--{countryid=275, country=Palestinian Territory} with 269 times can any help me out where I am doing wrong in storing the parsed data , I am stuck here.
Check this.
private JSONObject[] items;
JSONArray countryobj = json.getJSONArray("country_details");
items = new JSONObject[countryobj.length()];
for(int i=0, i < countryobj.length(); i++)
{
items[i] = countryobj.optJSONObject(i);
id = items[i].getString("countryid");
map.put("countryid",id);
countryn= items[i].getString("country");
map.put("country",countryn);
contactList.add(i,map);
}

Categories

Resources