Rooms database save and retrieve object using converter - java
when i was trying to save an object using rooms database, data insertion was successful. while retrieving data, a value inside the object, which was an object, was retrieved as array. Converting the array back to object is not working. Other string, and integer values inside the root object was retrieved properly.
Saved object :
[[F#6c173ab
Retrieved object:
[[0.0066505815,
0.00605235, 0.0044598486, -0.011793762, 0.0069282507, -0.059397057, -0.058320906, 0.17123938, -0.019021105, -0.1037456, 0.0018062548, -0.005069571, 0.0035884415, 0.0017127255, 0.004238736, -0.058450952, -0.007079399, -0.010851874, 9.1687456E-4, 0.013117686, 0.26496187, -0.056337364, 0.054294083, 0.0023271786, 0.19248551, -0.031670928, 0.004658082, -0.042408537, -0.08871324, -0.13611381, 0.0048175915, 0.060110737, -0.05661096, -0.004599247, 0.02567487, -0.14492176, 0.41225138, 0.037969578, -0.0060184584, 0.16407079, -0.007605861, -0.004265492, -0.0011223844, 0.006605887, -0.008077469, 0.0015253898, -0.10189122, 0.050602783, 0.0058309403, 0.057144053, 0.07865115, -0.0022470118, 0.005851626, -0.001395651, -0.061264377, -0.007627005, -0.1531251, -8.3948084E-4, 0.02980912, -0.002113619, -0.0018161217, -0.10022795, 0.12291724, 0.07126657, 1.6772193E-4, 0.022098381, 0.0026675903, 0.03227209, 0.011782837, 0.006000733, 0.009471676, 0.036371186, -0.23033214, -0.002258695, 0.039965842, -0.00845738, 0.0025282402, 6.5926113E-4, 0.03005817, 0.032968543, 0.003514709, 0.03701494, -0.0047574765, 0.0067672534, 0.08913908, 0.0014652971, 0.009258712, -0.03202012, -0.024361957, -0.10464151, -0.033407286, -0.0027610548, -0.00944446, -0.0024300436, -0.0232218, 0.0094572455, 0.018079767, 0.23599343, -0.0063236416, 0.034273528, 5.9618044E-4, 0.010737699, 0.008162582, 0.0025107688, 0.007046912, 0.0026148462, -6.691977E-4, 0.0018003252, -0.017509019, 0.0071865367, 0.17709938, -0.0027926106, 0.0041772844, 0.24446069, 0.0035891477, 0.090311974, -0.005678741, 0.002527207, -0.043642007, 0.013362809, -0.10237697, 0.004665849, 0.029806657, 8.510543E-4, 0.008034529, 0.0037261287, 0.0016963077, -0.0065462743, 0.0014083247, -0.09163139, -7.1395264E-4, 0.0034422423, 2.2180262E-4, -0.050950024, 0.052165035, -6.5167714E-4, 0.09660987, 0.059556033, 0.0011484445, 0.0048205433, 0.016215535, -0.0074894307, -4.8624526E-4, 0.09030299, -0.031675506, 0.035420638, 0.00863125, 0.0062305178, -2.9943243E-4, 0.017759249, -0.007217323, -0.17156895, -0.08075601, 0.013375583, -0.0057125236, 0.0019819727, 0.0045942706, -9.6630485E-4, -0.0056799883, -0.001163379, 0.026658272, 0.0045382543, 0.0053815856, -0.0019246427, -0.0020221453, -0.0036204413, -0.016369255, -0.07884872, 0.0012176841, -0.0077565406, 0.08828778, -0.18202521, 0.0031140386, -0.013568612, 0.03727499, 0.0029328368, -0.009444142, 0.061891776, -0.0021317177, 7.041842E-5, -0.06919885, -0.022822084, -0.009733031, 0.0038881213, 0.2372824, 0.15371381, -0.0267819, -0.048720658, 0.029161548, -0.16049597, 0.023316571, 0.0020684062]]
This is the type converter i used
#TypeConverter
public static String fromRecognition(SimilarityClassifier.Recognition recognition) {
if (recognition == null) {
return (null);
}
Gson gson = new Gson();
Type type = new TypeToken<SimilarityClassifier.Recognition>() {
}.getType();
String json = gson.toJson(recognition, type);
return json;
}
#TypeConverter
public static SimilarityClassifier.Recognition toRecognition(String recognitionString) {
if (recognitionString == null) {
return (null);
}
Gson gson = new Gson();
Type type = new TypeToken<SimilarityClassifier.Recognition>() {
}.getType();
SimilarityClassifier.Recognition recognition = gson.fromJson(recognitionString, type);
return recognition;
}
column in data base is given as
#ColumnInfo(name = "record")
#TypeConverters(Converters.class)
private SimilarityClassifier.Recognition record;
public SimilarityClassifier.Recognition getRecord() {
return record;
}
public void setRecord(SimilarityClassifier.Recognition record) {
this.record = record;
}
similarityclassifier.Recognition is given below
public class Recognition {
private final String id;
private final String title;
private final Float distance;
private Object extra;
private RectF location;
private Integer color;
private Bitmap crop;
public Recognition(
final String id, final String title, final Float distance, final RectF location) {
this.id = id;
this.title = title;
this.distance = distance;
this.location = location;
this.color = null;
this.extra = null;
this.crop = null;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public Float getDistance() {
return distance;
}
public RectF getLocation() {
return new RectF(location);
}
public Bitmap getCrop() {
return this.crop;
}
public Integer getColor() {
return this.color;
}
public Object getExtra() {
return this.extra;
}
public void setExtra(Object extra) {
this.extra = extra;
}
public void setColor(Integer color) {
this.color = color;
}
public void setLocation(RectF location) {
this.location = location;
}
public void setCrop(Bitmap crop) {
this.crop = crop;
}
#Override
public String toString() {
String resultString = "";
if (id != null) {
resultString += "[" + id + "] ";
}
if (title != null) {
resultString += title + " ";
}
if (distance != null) {
resultString += String.format("(%.1f%%) ", distance * 100.0f);
}
if (location != null) {
resultString += location + " ";
}
return resultString.trim();
}
}
If anyone else encountered this issue, please help
Related
Scan some text in a document, replace certain words(these words should be variables) and save in a new document using Apache POI in Java
I have json file from which I parse json objects to java objects using Gson library. The next step is to create main class in which with the help of Apache POI prepared docx file is read, some changes were made in the text and new document with changes is created. The problem I faced is that the text which should be changed need to be variable(from json file). I mean that "name" and "testName" both should be variables or methods, so I can call them from text.contains. Can you show my mistake and the right way to do the task. Thanks in advance. Here is my code ` public class main { public static void gson() { Gson gson = new Gson(); BufferedReader br = null; try { br = new BufferedReader(new FileReader("jsonn.json")); Result result = gson.fromJson(br, Result.class); if (result != null) { result.getName(); result.getLastname(); System.out.println(result.getName()); System.out.println(result.getLastname()); for (Phone p : result.getPhones()) { p.getType(); p.getNum(); System.out.println(p.getType() + ": " + p.getNum()); // System.out.println(p.getType()+" : "+p.getNum()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }} public class Result { #SerializedName("name") #Expose private String name; #SerializedName("lastname") #Expose private String lastname; #SerializedName("phones") #Expose private List<Phone> phones = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; }} public class Phone { #SerializedName("name") #Expose private String name; #SerializedName("lastName") #Expose private String lastName; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } #SerializedName("num") #Expose private String num; #SerializedName("type") #Expose private String type; public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getType() { return type; } public void setType(String type) { this.type = type; }} public class Read { public static void main(String[] args) throws InvalidFormatException, IOException { main.gson(); XWPFDocument doc = new XWPFDocument(OPCPackage.open("Шаблон.docx")); Result res = new Result(); String replaceName = res.getName(); for (XWPFParagraph p : doc.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null && text.contains("name")) { text = text.replace("name", "Alex"); r.setText(text, 0); } } } } for (XWPFTable tbl : doc.getTables()) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { for (XWPFRun r : p.getRuns()) { String text = r.getText(0); if (text != null && text.contains("name")) { text = text.replace("name", "Alex"); r.setText(text, 0); } } } } } } doc.write(new FileOutputStream("Пример.docx")); }} ` Here is json file: { "name":"testName", "lastname":"testLastName", "phones":[ { "num":"9000000", "type":"mobile" }, { "num":"1000000", "type":"home" } ]}
Android: Draw direction in google map java
how to find the best route for multiple locations in google maps api in android? I have some locations as LatLng but I dont know how specify a optimal route
ArrayList<LatLng> directionPoint = latLongList; PolylineOptions rectLine = new PolylineOptions().width(8).color( Color.RED); for (int i = 0; i < directionPoint.size(); i++) { rectLine.add(directionPoint.get(i)); } // Adding route on the map map.addPolyline(rectLine); Try this , pass your list of latlongs in latLongList
Using Google maps direction api you can acheive it, follow the documentation about using waypoints - https://developers.google.com/maps/documentation/directions/intro#Waypoints Now a fully functional api looks like this - https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY Here origin = starting point, destination = Ending point, waypoints = points that you want to cover, optimize:true = the route through the given waypoints will be optimized(i.e following Traveling Salesman Problem) and key = your map api key. Now in order to save the api response here is the model class - public class DirectionApiResponse { private ArrayList<Geocoded_waypoints> geocoded_waypoints; private String status; private ArrayList<Routes> routes; public ArrayList<Geocoded_waypoints> getGeocoded_waypoints () { return geocoded_waypoints; } public void setGeocoded_waypoints (ArrayList<Geocoded_waypoints> geocoded_waypoints) { this.geocoded_waypoints = geocoded_waypoints; } public String getStatus () { return status; } public void setStatus (String status) { this.status = status; } public ArrayList<Routes> getRoutes () { return routes; } public void setRoutes (ArrayList<Routes> routes) { this.routes = routes; } #Override public String toString() { return "ClassPojo [geocoded_waypoints = "+geocoded_waypoints+", status = "+status+", routes = "+routes+"]"; } public class Geocoded_waypoints { private String place_id; private String geocoder_status; private ArrayList<String> types; public String getPlace_id () { return place_id; } public void setPlace_id (String place_id) { this.place_id = place_id; } public String getGeocoder_status () { return geocoder_status; } public void setGeocoder_status (String geocoder_status) { this.geocoder_status = geocoder_status; } public ArrayList<String> getTypes () { return types; } public void setTypes (ArrayList<String> types) { this.types = types; } #Override public String toString() { return "ClassPojo [place_id = "+place_id+", geocoder_status = "+geocoder_status+", types = "+types+"]"; } } public class Routes { private String summary; private Bounds bounds; private String copyrights; private ArrayList<String> waypoint_order; private ArrayList<Legs> legs; private ArrayList<String> warnings; private Overview_polyline overview_polyline; public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public Bounds getBounds() { return bounds; } public void setBounds(Bounds bounds) { this.bounds = bounds; } public String getCopyrights() { return copyrights; } public void setCopyrights(String copyrights) { this.copyrights = copyrights; } public ArrayList<String> getWaypoint_order() { return waypoint_order; } public void setWaypoint_order(ArrayList<String> waypoint_order) { this.waypoint_order = waypoint_order; } public ArrayList<Legs> getLegs() { return legs; } public void setLegs(ArrayList<Legs> legs) { this.legs = legs; } public ArrayList<String> getWarnings() { return warnings; } public void setWarnings(ArrayList<String> warnings) { this.warnings = warnings; } public Overview_polyline getOverview_polyline() { return overview_polyline; } public void setOverview_polyline(Overview_polyline overview_polyline) { this.overview_polyline = overview_polyline; } #Override public String toString() { return "ClassPojo [summary = " + summary + ", bounds = " + bounds + ", copyrights = " + copyrights + ", waypoint_order = " + waypoint_order + ", legs = " + legs + ", warnings = " + warnings + ", overview_polyline = " + overview_polyline + "]"; } public class Bounds { private Southwest southwest; private Northeast northeast; public Southwest getSouthwest () { return southwest; } public void setSouthwest (Southwest southwest) { this.southwest = southwest; } public Northeast getNortheast () { return northeast; } public void setNortheast (Northeast northeast) { this.northeast = northeast; } #Override public String toString() { return "ClassPojo [southwest = "+southwest+", northeast = "+northeast+"]"; } public class Southwest { private String lng; private String lat; public String getLng () { return lng; } public void setLng (String lng) { this.lng = lng; } public String getLat () { return lat; } public void setLat (String lat) { this.lat = lat; } #Override public String toString() { return "ClassPojo [lng = "+lng+", lat = "+lat+"]"; } } public class Northeast { private String lng; private String lat; public String getLng () { return lng; } public void setLng (String lng) { this.lng = lng; } public String getLat () { return lat; } public void setLat (String lat) { this.lat = lat; } #Override public String toString() { return "ClassPojo [lng = "+lng+", lat = "+lat+"]"; } } } public class Overview_polyline { private String points; public String getPoints() { return points; } public void setPoints(String points) { this.points = points; } #Override public String toString() { return "ClassPojo [points = " + points + "]"; } } public class Legs { private Duration duration; private Distance distance; private End_location end_location; private String start_address; private String end_address; private Start_location start_location; private ArrayList<String> traffic_speed_entry; private ArrayList<String> via_waypoint; private ArrayList<Steps> steps; public Duration getDuration() { return duration; } public void setDuration(Duration duration) { this.duration = duration; } public Distance getDistance() { return distance; } public void setDistance(Distance distance) { this.distance = distance; } public End_location getEnd_location() { return end_location; } public void setEnd_location(End_location end_location) { this.end_location = end_location; } public String getStart_address() { return start_address; } public void setStart_address(String start_address) { this.start_address = start_address; } public String getEnd_address() { return end_address; } public void setEnd_address(String end_address) { this.end_address = end_address; } public Start_location getStart_location() { return start_location; } public void setStart_location(Start_location start_location) { this.start_location = start_location; } public ArrayList<String> getTraffic_speed_entry() { return traffic_speed_entry; } public void setTraffic_speed_entry(ArrayList<String> traffic_speed_entry) { this.traffic_speed_entry = traffic_speed_entry; } public ArrayList<String> getVia_waypoint() { return via_waypoint; } public void setVia_waypoint(ArrayList<String> via_waypoint) { this.via_waypoint = via_waypoint; } public ArrayList<Steps> getSteps() { return steps; } public void setSteps(ArrayList<Steps> steps) { this.steps = steps; } #Override public String toString() { return "ClassPojo [duration = " + duration + ", distance = " + distance + ", end_location = " + end_location + ", start_address = " + start_address + ", end_address = " + end_address + ", start_location = " + start_location + ", traffic_speed_entry = " + traffic_speed_entry + ", via_waypoint = " + via_waypoint + ", steps = " + steps + "]"; } public class Duration { private String text; private String value; public String getText() { return text; } public void setText(String text) { this.text = text; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } #Override public String toString() { return "ClassPojo [text = " + text + ", value = " + value + "]"; } } public class Start_location { private String lng; private String lat; public String getLng () { return lng; } public void setLng (String lng) { this.lng = lng; } public String getLat () { return lat; } public void setLat (String lat) { this.lat = lat; } #Override public String toString() { return "ClassPojo [lng = "+lng+", lat = "+lat+"]"; } } public class End_location { private String lng; private String lat; public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } #Override public String toString() { return "ClassPojo [lng = " + lng + ", lat = " + lat + "]"; } } public class Distance { private String text; private String value; public String getText() { return text; } public void setText(String text) { this.text = text; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } #Override public String toString() { return "ClassPojo [text = " + text + ", value = " + value + "]"; } } public class Steps { private String html_instructions; private Duration duration; private Distance distance; private End_location end_location; private Polyline polyline; private Start_location start_location; private String travel_mode; public String getHtml_instructions () { return html_instructions; } public void setHtml_instructions (String html_instructions) { this.html_instructions = html_instructions; } public Duration getDuration () { return duration; } public void setDuration (Duration duration) { this.duration = duration; } public Distance getDistance () { return distance; } public void setDistance (Distance distance) { this.distance = distance; } public End_location getEnd_location () { return end_location; } public void setEnd_location (End_location end_location) { this.end_location = end_location; } public Polyline getPolyline () { return polyline; } public void setPolyline (Polyline polyline) { this.polyline = polyline; } public Start_location getStart_location () { return start_location; } public void setStart_location (Start_location start_location) { this.start_location = start_location; } public String getTravel_mode () { return travel_mode; } public void setTravel_mode (String travel_mode) { this.travel_mode = travel_mode; } #Override public String toString() { return "ClassPojo [html_instructions = "+html_instructions+", duration = "+duration+", distance = "+distance+", end_location = "+end_location+", polyline = "+polyline+", start_location = "+start_location+", travel_mode = "+travel_mode+"]"; } public class Polyline { private String points; public String getPoints () { return points; } public void setPoints (String points) { this.points = points; } #Override public String toString() { return "ClassPojo [points = "+points+"]"; } } } } } } Now to draw the route in between way-points you can use the below method - private void setRoutePath(DirectionApiResponse directionObj){ gMap.clear(); addMarkers(localLeedsArrayList); int count = 0; ArrayList<LatLng> points = null; DirectionApiResponse.Routes route = directionObj.getRoutes().get(0); // Traversing through all the routes for(DirectionApiResponse.Routes.Legs leg : route.getLegs()){ PolylineOptions lineOptions = new PolylineOptions(); points = new ArrayList<LatLng>(); Log.e("Route", leg.getStart_address()+" "+leg.getEnd_address()); // Fetching all the points in i-th route //for(DirectionApiResponse.Routes.Legs.Steps step : leg.getSteps()){ for(int j=0;j<leg.getSteps().size();j++){ DirectionApiResponse.Routes.Legs.Steps step = leg.getSteps().get(j); points.addAll(PolyUtil.decode(step.getPolyline().getPoints())); } // Adding all the points in the route to LineOptions lineOptions.addAll(points); lineOptions.width(20); lineOptions.color(colors[count]); Polyline polylineFinal = gMap.addPolyline(lineOptions); count++; } Log.e("SouthWest",directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng()); Log.e("northeast",directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getNortheast().getLng()); /*LatLng lSouth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()), Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng())); LatLng lNorth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()), Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLng())); LatLngBounds latLngBounds = new LatLngBounds(lNorth,lSouth); gMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,14));*/ gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()),15)); } Here gMap is the google map object.. ******* UPDATE Api Calling******** In order to call the api Create interface IApiMethods and put the code below - #GET("json?origin=35.693391,51.424261&destination=35.692032,51.432715&waypoints=35.691997,51.432758") Call<DirectionApiResponse> getDirectionWalking(#Query("key")String key); you can change the co-ordinates accordingly Now call the method below to call the api and get the DirectionApiResponse object private void getDirection(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://maps.googleapis.com/maps/api/directions/") .addConverterFactory(GsonConverterFactory.create()) .build(); IApiMethods service = retrofit.create(IApiMethods.class); Call<DirectionApiResponse> directionApiResponseCall = service.getDirectionWalking("YOUR API KEY"); directionApiResponseCall.enqueue(new Callback<DirectionApiResponse>() { #Override public void onResponse(Call<DirectionApiResponse> call, Response<DirectionApiResponse> response) { setRoutePath(response.body()); } #Override public void onFailure(Call<DirectionApiResponse> call, Throwable t) { } }); } Finally add the following dependencies to the app's build.gradle file - compile 'com.google.android.gms:play-services-maps:8.4.0' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.0.2'
How to get the route You might want to look at the Distance Matrix service: https://developers.google.com/maps/documentation/javascript/distancematrix It gives you distances between a set of origins and destinations, and might help you with narrowing down options. 2. To Find the best route : If using the web service, ensure you set optimize:true before listing your waypoints, and check the waypoint_order array. http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false If use the JS API, set optimizeWaypoints:true in your request. 3. To draw polyline with the latlongs you have PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true); for (int z = 0; z < list.size(); z++) { LatLng point = list.get(z); options.add(point); } line = myMap.addPolyline(options);
How to parse nested JSON objects data?
I'm using volley and gson libs in my Android app which main purpose is to call to the server API and retrieve some data. Everything works well, expect for nested JSON object data. I can't retrieve information (lat, lng) which are inside position object. It throws an error: Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 99 path $.position and points out to deliveryResponse method. Example of my JSON: [{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN"},{"number":18,"name":"John","address":"John Street.","position":{"lat":12.68300406,"lng":45.28001237},"status":"OPEN",}] deliveryResponse method: #Override protected void deliverResponse(JSONArray jsonArray) { if (mListener != null && jsonArray != null) { List<T> responseArray = new ArrayList<T>(); for (int i = 0; i < jsonArray.length(); i++) { try { JSONObject entry = jsonArray.getJSONObject(i); T parsedResponse = new Gson().fromJson(entry.toString(), mClass); if (parsedResponse != null) { responseArray.add(parsedResponse); } } catch (JSONException e) { Log.d(TAG, "Error parsing JSON Object: " + e.getMessage()); mListener.onResponse(jsonArray); } } mListener.onGsonResponse(responseArray); } } Object class: public class Object { private int number; private String name; private String address; private List<PositionObj> position; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<PositionObj> getPosition() { return position; } public void setPosition(List<PositionObj> position) { this.position = position; } PositionObj class: public class PositionObj { private int lat; private int lng; public int getLat() { return lat; } public void setLat(int lat) { this.lat = lat; } public int getLng() { return lng; } public void setLng(int lng) { this.lng = lng; } What do you sugggest?
In your JSON, position is an object and not an array. So, in your class Object(weird name), change private List<PositionObj> position; by private PositionObj position;.
Instance of class in Java can't be tested for null
I'm trying to troubleshoot a null-pointer exception that keeps me from populating an array adapter. I've traced it down to the point at which I create an instance of the class, and so to try to troubleshoot, I created the following toast: private void showSplits() { // populate the split line Split s = new Split(); s = mTransaction.getSplit(); int duration = Toast.LENGTH_SHORT; if (s != null) { Toast toast = Toast.makeText(getActivity(), s.getCategory(), duration); Toast toast2 = Toast.makeText(getActivity(), s.getDescription(), duration); Toast toast3 = Toast.makeText(getActivity(), s.getAmount(), duration); toast.show(); toast2.show(); toast3.show(); } else { Toast toast4 = Toast.makeText(getActivity(), "S was null.", duration); toast4.show(); } .... } When run, the result of this method is to neatly print out the content of each field of the split, then neatly print out "S was null." I've verified that I'm calling the method only once, so I can't see how s could both be null and not null. Here's the detail of the class... public class Split implements Serializable { private static final long serialVersionUID = 1L; private static final String JSON_CATEGORY = "category"; private static final String JSON_AMOUNT = "amount"; private static final String JSON_DESCRIPTION = "description"; private UUID mId; private String mCategory; private String mAmount; private String mDescription; public Split(String category, String amount, String description) { mCategory = category; mAmount = amount; mDescription = description; } public Split() { mId = UUID.randomUUID(); mCategory = "none"; } public Split(JSONObject json) throws JSONException { if (json.has(JSON_CATEGORY)) { mCategory = json.getString(JSON_CATEGORY); } if (json.has(JSON_AMOUNT)) { mAmount = json.getString(JSON_AMOUNT); } if (json.has(JSON_DESCRIPTION)) { mDescription = json.getString(JSON_DESCRIPTION); } } public JSONObject toJSON() throws JSONException { JSONObject json = new JSONObject(); // if (mCategory != null) { json.put(JSON_CATEGORY, mCategory); // } // if (mAmount != null) { json.put(JSON_AMOUNT, mAmount); // } // if (mDescription != null) { json.put(JSON_DESCRIPTION, mDescription); // } return json; } // Factory method to convert an array of JSON objects into a list of objects // User.fromJson(jsonArray); public static ArrayList<Split> fromJson(JSONArray jsonObjects) { ArrayList<Split> splits = new ArrayList<Split>(); for (int i = 0; i < jsonObjects.length(); i++) { try { splits.add(new Split(jsonObjects.getJSONObject(i))); } catch (JSONException e) { e.printStackTrace(); } } return splits; } public String getCategory() { return mCategory; } public void setCategory(String category) { mCategory = category; } public String getAmount() { return mAmount; } public void setAmount(String amount) { mAmount = amount; } public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description; } } To the best of my abilities to tell, showSplits is called only once in the fragment I'm working in.
In the first line you are referencing s variable to a new Split Object, And in the second line you are changing the reference of s to mTransaction.getSplit(). If the object is returned by mTransaction.getSplit() is null then your s will reference to null. Means value of s will be null. Split s = new Split(); s = mTransaction.getSplit(); your mTransaction.getSplit() may be returning null value , Try to debug it
JSF Custom component? How to add Method expression support?
i want add Method Expression support on to my custom component. i've seen that i must write a tagHandler. i've seen this post : How to add Method Expression to a custom JSF component I don't understand what are the parameters "void.class" and "moveEvent" of the methodRule method. This is my customComponent code : public class Link extends UIOutput{ private StringBuilder style = new StringBuilder(); private String id = ""; private Boolean active = false; private String alt = ""; private String href = ""; private String hreflang = ""; private String rel = ""; private String target = ""; private String download = ""; private String media = ""; private String type = ""; public Boolean isActive() { return active; } public void setActive(Boolean active) { this.active = active; } public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getHreflang() { return hreflang; } public void setHreflang(String hreflang) { this.hreflang = hreflang; } public String getRel() { return rel; } public void setRel(String rel) { this.rel = rel; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getDownload() { return download; } public void setDownload(String download) { this.download = download; } public String getMedia() { return media; } public void setMedia(String media) { this.media = media; } public String getType() { return type; } public void setType(String type) { this.type = type; } #Override public void encodeBegin(FacesContext context)throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = getClientId(context); if("".equals(id) || id == null){ id = clientId; } Object styleClass = (getAttributes().get("styleClass") != null) ? (Boolean)getAttributes().get("styleClass") : ""; writer.startElement("li", this); if(active){ style.append(" active "); } if(!"".equals(styleClass)){ style.append(styleClass); } writer.writeAttribute("id", id, null); writer.writeAttribute("class", style.toString().trim(), null); writer.startElement("a", this); writer.writeAttribute("href", href, null); if(!"".equals(alt)) { writer.writeAttribute("alt", alt, null); } if(!"".equals(hreflang)) { writer.writeAttribute("hreflang", hreflang, null); } System.out.println("rel = " + rel); if(!"".equals(rel)) { writer.writeAttribute("rel", rel, null); } if(!"".equals(target)) { writer.writeAttribute("target", target, null); } if(!"".equals(download)) { writer.writeAttribute("download", download, null); } if(!"".equals(media)) { writer.writeAttribute("media", media, null); } if(!"".equals(type)) { writer.writeAttribute("type", type, null); } for (UIComponent child : getChildren()) { child.encodeAll(context); } } #Override public Object saveState(FacesContext context) { Object values[] = new Object[10]; values[0] = super.saveState(context); values[1] = id; values[2] = style; values[3] = active; values[4] = alt; values[5] = href; values[6] = hreflang; values[7] = rel; values[8] = target; values[9] = download; values[10] = media; values[110] = type; return ((Object) (values)); } #Override public void restoreState(FacesContext context, Object state) { Object values[] = (Object[])state; super.restoreState(context, values[0]); id = (String)values[1]; style.insert(0, values[2]); active = (Boolean)values[3]; alt = (String)values[4]; href = (String)values[5]; hreflang = (String)values[6]; rel = (String)values[7]; target = (String)values[8]; download = (String)values[9]; media = (String)values[10]; type = (String)values[11]; } }