Get Elements of JSON Array Android - java

I have a JSON file which looks like the following:
{"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},
{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}
and I can get the first set of latitude and lontitude co-ordinates by doing the following:
JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
o = a.getJSONObject(0);
lat = (int) (o.getDouble("Latitude")* 1E6);
lng = (int) (o.getDouble("lontitude")* 1E6);
Does anyone have an idea of how to get all the latitude and lontitude values ?
Any help would be much appreciated.

Create ArrayLists for the results:
JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
int arrSize = a.length();
List<Integer> lat = new ArrayList<Integer>(arrSize);
List<Integer> lon = new ArrayList<Integer>(arrSize);
for (int i = 0; i < arrSize; ++i) {
o = a.getJSONObject(i);
lat.add((int) (o.getDouble("Latitude")* 1E6));
lon.add((int) (o.getDouble("lontitude")* 1E6));
}
This will cover any array size, even if there are more than two values.

In the below code, I am using Gson for converting JSON string into java object because GSON can use the Object definition to directly create an object of the desired type.
String json_string = {"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}
JsonObject out = new JsonObject();
out = new JsonParser().parse(json_string).getAsJsonObject();
JsonArray listJsonArray = new JsonArray();
listJsonArray = out.get("posts").getAsJsonArray();
Gson gson = new Gson();
Type listType = new TypeToken<Collection<Info>>() { }.getType();
private Collection<Info> infoList;
infoList = (Collection<Info>) gson.fromJson(listJsonArray, listType);
List<Info> result = new ArrayList<>(infoList);
Double lat,long;
if (result.size() > 0) {
for (int j = 0; j < result.size(); j++) {
lat = result.get(j).getLatitude();
long = result.get(j).getlongitude();
}
//Generic Class
public class Info {
#SerializedName("Latitude")
private Double Latitude;
#SerializedName("longitude")
private Double longitude;
public Double getLatitude() { return Latitude; }
public Double getlongitude() {return longitude;}
public void setMac(Double Latitude) {
this.Latitude = Latitude;
}
public void setType(Double longitude) {
this.longitude = longitude;
}
}
Here the result is obtained in lat and long variable.

Trusting my memory and my common sense... have you tried:
o = a.getJSONObject(1);
Look here

Related

convert jsonObject to arraylist

i was tring to find a solution to get lat and lng as a double
JSONArray arr = jsonObject.getJSONArray("hits");
for (int i = 0; i < arr.length(); i++)
{
String geoloc = arr.getJSONObject(i).getString("_geoloc");
Log.d("geoloc"," : " + geoloc);
}
so what i get is this : geoloc: : {"lat":33.84878,"lng":-5.481698}
What I want is something like this :
double lat = 33.84878;
double lng = -5.481698;
my question is how can i get them any help please. and thank you
You need to convert the String geoloc to JSONObject.
For example:
JSONObject geolocJsonObj = (JSONObject) geoloc;
After you can access to lat:
geolocJsonObj.get("lat")
You can create a class of GeoLocation and push values into the ArrayList of that:
class GeoLocation {
private double lat;
private double long;
GeoLocation(double nLat, double nLong) { this.lat = nLat, this.long = nLong }
// ... Getter and Setter methods
}
You can use parseDouble in order to extract double values from the json object like this:
JSONArray arr = jsonObject.getJSONArray("hits");
List<GeoLocation> aGeoLocationList = new ArrayList<GeoLocation>();
for (int i = 0; i < arr.length(); i++)
{
double latVal = Double.parseDouble(arr.getJSONObject(i).getString("lat"));
double longVal = Double.parseDouble(arr.getJSONObject(i).getString("long"));
aGeoLocationList.add(new GeoLocation(latVal, longVal));
}

How to associate an element in one Array with an element in another array (Android Studio)

I have two arrays:
float [] E;
float [] Location;
The elements in array E are the following: {1900, 16400, 77666, 8000, 13200, 15600}
The elements in array Location are {Birmingham, Blackburn, London, Luton, Manchester, Newcastle}
These data have been extracted from my database where they are associated, meaning:
Birmingham - 1900
Blackburn - 16400
London - 77666
Luton- 8000
Manchester-13200
Newcastle-15600
I want to be able ensure that the locations are associated to the right data as I have shown above if that makes sense. Is there a way of doing that?
Thanks In Advance!
Well, they're already associated by index. The entry at index 0 in E is related to the entry at index 0 in Location.
But I would solve this by not having two arrays. Instead, I'd have a single array storing an object, which had (for example) both the float 1900 (I wouldn't use float, though; at least use double) and the string "Birmingham".
class SomeAppropriateName {
private double distance;
private String location;
SomeAppropriateName(double distance, String _location) {
this.distance = _distance;
this.location = _location;
}
// ...add getters and setters as appropriate...
}
Then:
SomeAppropriateName[] info;
You can use android.util.Pair<F,S> for that.
List<Pair<String,Double>> pairs = Arrays.asList(
new Pair("Birmingham", 1900),
new Pair("Blackburn", 16400),
new Pair("London", 77666),
new Pair("Luton", 8000),
new Pair("Manchester", 13200),
new Pair("Newcastle", 15600)
);
for (Pair<String, Double> pair : pairs) {
Log.d("log", pair.first + " - " + pair.second);
}
Simply with HashMap !
HashMap is an array with key value. You can iterate on it etc.. For example this code :
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
/* Get values based on key*/
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
Good Luck
i don't know how you're querying your database, but i assume you're making one query to get both the location and the distance.
//1. create a model to represent the Location and its corresponding distance
public class LocationDistance {
private float distance;
private String location;
public LocationDistance(float distance, String location) {
this.distance = distance;
this.location = location;
}
public String getLocation(){
return this.location;
}
public float getDistance(){
return this.distance;
}
public void setLocation(String loc){
this.location=loc;
}
public void setDistance(float distance){
this.distance=distance;
}
}
//2. Loop over the two arrays and create a list of LocationDistance
List<LocationDistance> locationDistance=new ArrayList<LocationDistance>();
float[] e = { 1900f, 16400f, 77666f, 8000f, 13200f, 15600f };
String[] location = { "Birmingham", "Blackburn", "London", "Luton", "Manchester", "Newcastle" };
for(int i=0; i<e.length;i++){
locationDistance.add(new LocationDistance(e[i],location[i]));
}
is e a float, the same as location?
you should define a Pojo class for that
class Pojo {
private final float e;
private final String city;
public Pojo(float e, String city) {
this.e = e;
this.city = city;
}
public static void main(String[] args) {
final float[] e = { 1900f, 16400f, 77666f, 8000f, 13200f, 15600f };
final String[] location = { "Birmingham", "Blackburn", "London", "Luton", "Manchester", "Newcastle" };
final Pojo[] p = new Pojo[e.length];
for (int i = 0; i < e.length; i++) {
p[i] = new Pojo(e[i], location[i]);
}
}
}

Creating an array list of multiple data types in Java

Some of the file I'm working with: http://pastebin.com/WriQcuPs
Currently I had to make the population, latitude, and longitude strings or else I wouldn't get the desired output. I want for them to be int, double, and double in that order.
public class City {
String countrycode;
String city;
String region;
String population;
String latitude;
String longitude;
public City (String countrycode, String city, String region, String population, String latitude, String longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
this.population = population;
this.latitude = latitude;
this.longitude = longitude;
}
public String toString() {
return this.city + "," + this.population
+ "," + this.latitude + ","
+ this.longitude;
}
}
I suspect it has something to do with how I created the array list. Is there a way to make it so that some of the elements of the list are of a different type? I tried changing it to ArrayList<City> and changing the data types in the City class but it still gave me a ton of errors.
public class Reader {
In input = new In("file:world_cities.txt");
private static City cityInfo;
public static void main(String[] args) {
// open file
In input = new In("world_cities.txt");
input = new In("world_cities.txt");
try {
// write output to file
FileWriter fw = new FileWriter("cities_out.txt");
PrintWriter pw = new PrintWriter(fw);
int line = 0;
// iterate through all lines in the file
while (line < 47913) {
// read line
String cityLine = input.readLine();
// create array list
ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
// add line to array list
cityList.add(cityLine);
// increase counter
line += 1;
// create instance
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), cityList.get(4), cityList.get(5));
System.out.println(cityInfo);
// print output to file
pw.println(cityInfo);
}
// close file
pw.close();
}
// what is printed when there is an error when saving to file
catch (Exception e) {
System.out.println("ERROR!");
}
// close the file
input.close();
}
}
If you declare the list as follows, you can put instances of any reference type into it:
List<Object> list = new ArrayList<>();
But the downside is that when you get an element from the list, the static type of the element will be Object, and you will need to type cast it to the type that you need.
Also note, that you can't put an int or a double into a List. Primitive types are not reference types, and the List API requires the elements to be instances of reference types. You need to use the corresponding wrapper types; i.e. Integer and Double.
Looking at more of your code, I spotted this:
ArrayList<String> cityList =
new ArrayList<String>(Arrays.asList(cityLine.split(",")));
If you change the list to List<Object> where the objects are either Integer or Double, you won't be able to build your list like that.
In fact, the more I look this, the more I think that you don't need a list at all. You should be doing something like this:
// read line
String cityLine = input.readLine();
String[] parts = cityLine.split(",");
// increase counter
line += 1;
// create instance
cityInfo = new City(parts[0], parts[1], parts[2],
Integer.parseInt(parts[3]),
Double.parseDouble(parts[4]),
Double.parseDouble(parts[5]));
Notice: there is no List there at all!!
You could parse the string values before they are passed into a new City object. Then you could change the constructor and variables within a City to be an int, double, and double.
int pop = Integer.parseInt(cityList.get(3));
double latitude = Double.parseDouble(cityList.get(4));
double longitude = Double.parseDouble(cityList.get(5));
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), pop, latitude, longitude);
By looking at the City class you have defined the members are of different primitive data types. When you read the file to create a City, you need to pass the constructor parameters with the defined data types as in your constructor.
Modify your City class as below :
public class City {
String countrycode;
String city;
String region;
int population;
double latitude;
double longitude;
...
Try the following :
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5)));
This will convert the Strings to int and double as desired by the City class.
I believe no, but you can do this
public class City {
String countrycode;
String city;
String region;
String population;
double latitude;
double longitude;
public City (String countrycode, String city, String region, String population, double latitude, double longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
this.population = population;
this.latitude = latitude;
this.longitude = longitude;
}
public String toString() {
return this.city + "," + this.population
+ "," + this.latitude + ","
+ this.longitude;
}
}
public class Reader {
In input = new In("file:world_cities.txt");
private static City cityInfo;
public static void main(String[] args) {
// open file
In input = new In("world_cities.txt");
input = new In("world_cities.txt");
try {
// write output to file
FileWriter fw = new FileWriter("cities_out.txt");
PrintWriter pw = new PrintWriter(fw);
int line = 0;
// iterate through all lines in the file
while (line < 47913) {
// read line
String cityLine = input.readLine();
// create array list
ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
// add line to array list
cityList.add(cityLine);
// increase counter
line += 1;
// create instance
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), cityList.get(3), Doule.parseDouble(cityList.get(4)), Doule.parseDouble(cityList.get(5)));
System.out.println(cityInfo);
// print output to file
pw.println(cityInfo);
}
// close file
pw.close();
}
// what is printed when there is an error when saving to file
catch (Exception e) {
System.out.println("ERROR!");
}
// close the file
input.close();
}
}
You can do something like this:
READER CLASS
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
public class Reader {
In input = new In("file:world_cities.txt");
private static City cityInfo;
public static void main(String[] args) {
// open file
// In input = new In("world_cities.txt");
// input = new In("world_cities.txt");
try {
// write output to file
FileWriter fw = new FileWriter("cities_out.txt");
PrintWriter pw = new PrintWriter(fw);
int line = 0;
// iterate through all lines in the file
while (line < 47913) {
// read line
String cityLine = input.readLine();
// create array list
ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityLine.split(",")));
// add line to array list
cityList.add(cityLine);
// increase counter
line += 1;
// create instance
cityInfo = new City(cityList.get(0), cityList.get(1), cityList.get(2), Integer.parseInt(cityList.get(3)), Double.parseDouble(cityList.get(4)), Double.parseDouble(cityList.get(5)));
System.out.println(cityInfo);
// print output to file
pw.println(cityInfo);
}
// close file
pw.close();
}
// what is printed when there is an error when saving to file
catch (Exception e) {
System.out.println("ERROR!");
}
// close the file
input.close();
}
}
CITY CLASS
public class City {
String countrycode;
String city;
String region;
int population;
double latitude;
double longitude;
public City (String countrycode, String city, String region, int population, double latitude, double longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
this.population = population;
this.latitude = latitude;
this.longitude = longitude;
}
public String toString() {
return this.city + "," + this.population
+ "," + this.latitude + ","
+ this.longitude;
}
}
Is there a way to make it so that some of the elements of the list are
of a different type?
It is possible to have a List with elements of different type, but not if you're populating it with String.split() -- because that returns a String[].
You can convert the strings you get back fro String.split() into the desired types with the valueOf methods on the Java primitive type wrappers, for example...
Integer population = Integer.valueOf("1234567"); // Returns 1234567 as an Integer, which can autobox to an int if you prefer
Like Stephen suggested, you can use List<Object>, besides that, you can just pass String to City but let City itself to handle the datatype.
public class City {
String countrycode;
String city;
String region;
int population;
double latitude;
double longitude;
public City (String countrycode, String city, String region, String population, String latitude, String longitude) {
this.countrycode = countrycode;
this.city = city;
this.region = region;
try{
this.population = Integer.parseInt(population);
this.latitude = Double.parseDouble(latitude);
this.longitude = Double.parseDouble(longitude);
}catch(Exception e){
e.printStacktrace();
}
}
public String toString() {
return this.city + "," + this.population
+ "," + this.latitude + ","
+ this.longitude;
}
}
Btw, you have initiated In twice.
In input = new In("world_cities.txt");
input = new In("world_cities.txt");
Modify it to
In input = new In("world_cities.txt");

Cast my class to JSONObject

I have an array of objects of my class "Points" and I want to put them on a JSONArray, previusly cast to JSONObject, but I have one problem I can't solve, I can't put my points[] on the JSONObject and I don't know how to do it. I put the code to explain it better.
Principal code:
JSONArray jsPoints = new JSONArray();
for(int i = 0; i < points.length; i++)
{
JSONObject js = new JSONObject(points[i]);
jsPoints.put(js);
}
Point class:
public class Point {
String _id;
String _comment;
String _calification;
String _coords;
int _X;
int _Y;
public Point(String id, String comment, String calification, String coords, int x, int y)
{
_id = id;
_comment = comment;
_calification = calification;
_coords = coords;
_X = x;
_Y = y;
}
}
Introducing values into my class:
private void createPoints()
{
points = new Point[drawedInterestPoints.size() / 2];
int j = 0;
for(int i = 0; i < drawedInterestPoints.size() - 1; i++)
{
if(i % 2 == 0)
{
points[j] = new Point(pointType.get(i),comments.get(i),calification.get(i),GPScoords.get(i),drawedInterestPoints.get(i),drawedInterestPoints.get(i + 1));
j++;
}
}
}
Anyone can tall me what I have to do to put each of my points[] in a JSONObject and then in a JSONArray? Thanks!
Try with GSON. Do this:
Gson gson = new Gson();
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);
Hope this helps.. :)
you can not directly cast JSONArray to Points
what you can do something like following
get json as a string
de-serialize json to Point using jackson(ObjectMapper)
In your code
JSONObject js = new JSONObject(points[i]);
make no sense; You should put every items of points[] as tag in the jsObject and then insert it in a JsonArray
Try this:
public void jsonAsStr() {
JSONObject mJsonObj = new JSONObject();
try {
mJsonObj.put("tag1", true);
mJsonObj.put("tag2", 120);
mJsonObj.put("tag3", "Demo");
JSONArray jsPoints = new JSONArray();
jsPoints.put(mJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
You can do this way using gson
Gson gson = new Gson();
Point point = new Point("", "", "", "", 1, 2);
String json = gson.toJson(point);

ClassCastException: java.lang.Object[] cannot be cast to java.lang.Double

I am having a little trouble with my code. I have a hash map which has data. I want to get that data from the hash table and so far so good everything was working properly until I tried to get the coordinates of a point. I have made a class called "Segments" it contains a string "name" and an array of Doubles (longitude latitude). It is supposed to fill the variables with data from the hash table. In debug mode I saw the elements the longitude and latitude but it doesn't put them into the arrays I have specified and it prints out an error:
"ClassCastException: java.lang.Object[] cannot be cast to java.lang.Double"
Here is my code.
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[0];
longitude[i] = (Double)coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Can you tell me what am I doing wrong and how to fix my code?
I think the main issue is that your coord array doesn't contain coordinates but rather an array of array of coordinates. Therefore the correct way to address this would be:
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[i][0];
longitude[i] = (Double)coord[i][1];
}
Notice the second-level array inside the loop.
EDIT: You may need to add an explicit cast to coord[i]. Try these - one of them might work for you:
latitude[i] = ((Double[])coord[i])[0];
longitude[i] = ((Double[])coord[i])[1];
or
latitude[i] = ((double[])coord[i])[0];
longitude[i] = ((double[])coord[i])[1];
or
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];
You are trying to cast a primitive object to Object.
You can try to change your values do Double or cast to double[]
Also this is a very common mistake, remember that all primitives doesn't extend Object in Java
Try this code:
public class Segments
{
public String name;
public Double[] latitude;
public Double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Double[] coord = (Double[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = coord[0];
longitude[i] = coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Guys I found the solution and of course thank you for your help you pointed me to the right way. Sop the solution was that i had to declare the size of the array and the arrays (latitude, longitude) must be "double" not "Double" and so to fill the arrays (latitude, longitude) the code must look like:
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
//Object[] coord2 = new Object[coord.length];
latitude = new double[coord.length];
longitude = new double[coord.length];
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Categories