Java Object in list doesn't get found - java

I have a problem. I have the following class:
public class Cross implements Comparable<Cross> {
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
Now I have a list containing 500 objects of these elements. Here are the first 4 shown:
{ openTime='1504332000000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='363.7', trend='Down'}
{ openTime='1504663200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='325.73', trend='Up'}
{ openTime='1504879200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='294.05', trend='Down'}
{ openTime='1505181600000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='304.41', trend='Up'}
In a variable I have stored the epoch of a specific datetime and with that I want to find the first valid cross, so I tried this:
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
But this code returns the value null When my searchEpoch is for example: 1514764800000. In the list I do see multiple objects that have a lower openTime than the searchEpoch. The result I want is the cross with the highest openTime, but it still has to be smaller than the searchEpoch.
Here is the error I get:
runDateTimeGMT0: 2018-01-01T00:00
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at com.hatop.drivers.SimulatorDriver.run(SimulatorDriver.java:297)
at com.hatop.drivers.HatopDriver.main(HatopDriver.java:120)
Caused by: java.lang.NullPointerException: Cannot invoke "com.hatop.models.Cross.getTrend()" because the return value of "com.hatop.drivers.HatopDriver.getValidCross(List<Cross>, LocalDateTime)"
is null
at com.hatop.strategies.modules.module_java001.run(module_java001.java:186)
... 6 more
Why is my return value null?

This is caused due to the value the argument runDateTimeGMT0 is given and this:
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
Since this is working:
public class Demo {
private static Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = 1514764800000L;
return crossList.stream()
.filter(cross -> cross.getOpenTime() < searchEpoch)
.max(Cross::compareTo)
.orElse(null);
}
#SneakyThrows
public static void main(String[] args) {
List<Cross> crosses = Arrays.asList(
new Cross(1504332000000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 363.7, "Down"),
new Cross(1504663200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 325.73, "Up"),
new Cross(1504879200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 294.05, "Down"),
new Cross(1505181600000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 304.41, "Up")
);
Cross validCross = getValidCross(crosses, null);
System.out.println(validCross);
}
}
Output:
Cross(openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up)
By the way, equals() is implemented without hashcode() - a recipe for problems.

I tested you code by passing the value in a proper Cross constructor, as it appears in your list and it works fine. In particular, openingTime is passed as primitive type long.
The issue is NOT in the filter, as you can definitely use any operator with Long type.
In my opinion, there is something wrong in the file format of your Cross object. Highly likely is because of the openingTime field's value, which is probably converted in the wrong value.
Here is the test I wrote:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
public class TestCross {
public static void main(String[] args) {
List<Cross> crossList = List.of(new Cross(1504332000000L,"USDT", "ETH", "2h","EMA12", "EMA26",363.7,"Down" ),
new Cross(1505181600000L,"USDT", "ETH", "2h","EMA12", "EMA26",304.41,"Up" ),
new Cross(1504663200000L,"USDT", "ETH", "2h","EMA12", "EMA26",325.73,"Up" ),
new Cross(1504879200000L,"USDT", "ETH", "2h","EMA12", "EMA26",294.05,"Down" ));
Cross cross = new TestCross().getValidCross(crossList, LocalDateTime.now());
System.out.println(cross);
}
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
}
Cross class
public class Cross implements Comparable<Cross> {
public Cross(Long openTime, String market, String coin, String period, String metric1, String metric2, Double close,
String trend) {
super();
this.openTime = openTime;
this.market = market;
this.coin = coin;
this.period = period;
this.metric1 = metric1;
this.metric2 = metric2;
this.close = close;
this.trend = trend;
}
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public String toString() {
return "Cross [openTime=" + openTime + ", market=" + market + ", coin=" + coin + ", period=" + period
+ ", metric1=" + metric1 + ", metric2=" + metric2 + ", close=" + close + ", trend=" + trend + "]";
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
And here is the output:
Cross [openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up]

Related

Custom TiledDataSource with paging library

I tried to implement custom TiledDataSource for using with paging library. When I used LivePagedListProvider like returns type for my Dao method it worked fine (after table items updating - ui updated automatically).
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC")
LivePagedListProvider<Artist> loadArtists();
But when I try implement custom TiledDataSource for LivePagerListProvider table updates not triggered my observers.
Abstract generic class:
public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {
#Override
public int countItems() {
return DataSource.COUNT_UNDEFINED;
}
#Override
public List<ResultType> loadRange(int startPosition, int count) {
fetchFromNetwork(startPosition, count);
return loadFromDb(startPosition, count);
}
#WorkerThread
private void fetchFromNetwork(int startPosition, int count) {
if (createCall(startPosition, count) != null)
try {
Response<RequestType> response = createCall(startPosition, count).execute();
if (response.isSuccessful() && response.code() == 200) {
saveCallResult(response.body());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#WorkerThread
protected abstract void saveCallResult(#NonNull RequestType item);
#WorkerThread
protected abstract List<ResultType> loadFromDb(int startPosition, int count);
#WorkerThread
protected abstract Call<RequestType> createCall(int startPosition, int count);
public LiveData<PagedList<ResultType>> getAsLiveData() {
return new LivePagedListProvider<Integer, ResultType>() {
#Override
protected DataSource<Integer, ResultType> createDataSource() {
return PagedNetworkBoundResource.this;
}
}.create(0, new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(20)
.setInitialLoadSizeHint(20)
.build());
}
}
My dao method for this case:
#Query("SELECT * FROM " + Table.States.PLAY_STATE + ", "+Table.Chart.ARTIST+ " ORDER BY position ASC LIMIT (:limit) OFFSET (:offset)")
List<Artist> loadArtists(int offset, int limit);
I update Table.States.PLAY_STATE.
public void updatePlayerState(PlayerStateEntity state){
new Thread(() -> {
dao.deleteState();
dao.insertState(state);
}).run();
}
#Dao
public interface PlayStateDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insertState(PlayerStateEntity playEntity);
#Query("DELETE FROM " + Table.States.PLAY_STATE)
void deleteState();
#Query("SELECT * FROM "+Table.States.PLAY_STATE)
PlayerStateEntity getPlayerState();
}
#Entity(tableName = Table.States.PLAY_STATE)
public class PlayerStateEntity extends IdEntity {
#ColumnInfo(name = "album_played_id")
private Long albumPlayedId = -1L;
#ColumnInfo(name = "track_played_id")
private Long trackPlayedId = -1L;
#ColumnInfo(name = "artist_played_id")
private Long artistPlayedId = -1L;
#ColumnInfo(name = "state")
private PlayingState state;
#ColumnInfo(name = "playing_type")
private PlayingType playingType;
public Long getAlbumPlayedId() {
return albumPlayedId;
}
public void setAlbumPlayedId(Long albumPlayedId) {
this.albumPlayedId = albumPlayedId;
}
public Long getTrackPlayedId() {
return trackPlayedId;
}
public void setTrackPlayedId(Long trackPlayedId) {
this.trackPlayedId = trackPlayedId;
}
public Long getArtistPlayedId() {
return artistPlayedId;
}
public void setArtistPlayedId(Long artistPlayedId) {
this.artistPlayedId = artistPlayedId;
}
public PlayingState getState() {
return state;
}
public void setState(PlayingState state) {
this.state = state;
}
public PlayingType getPlayingType() {
return playingType;
}
public void setPlayingType(PlayingType playingType) {
this.playingType = playingType;
}
}
class Artist extends PlayEntity{
private String name;
private String link;
private String picture;
#ColumnInfo(name = "picture_small")
private String pictureSmall;
#ColumnInfo(name = "picture_medium")
private String pictureMedium;
#ColumnInfo(name = "picture_big")
private String pictureBig;
#ColumnInfo(name = "picture_xl")
private String pictureXl;
private Boolean radio;
private String tracklist;
private Integer position;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getPictureSmall() {
return pictureSmall;
}
public void setPictureSmall(String pictureSmall) {
this.pictureSmall = pictureSmall;
}
public String getPictureMedium() {
return pictureMedium;
}
public void setPictureMedium(String pictureMedium) {
this.pictureMedium = pictureMedium;
}
public String getPictureBig() {
return pictureBig;
}
public void setPictureBig(String pictureBig) {
this.pictureBig = pictureBig;
}
public String getPictureXl() {
return pictureXl;
}
public void setPictureXl(String pictureXl) {
this.pictureXl = pictureXl;
}
public Boolean getRadio() {
return radio;
}
public void setRadio(Boolean radio) {
this.radio = radio;
}
public String getTracklist() {
return tracklist;
}
public void setTracklist(String tracklist) {
this.tracklist = tracklist;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
#Override
public boolean isItemPlaying() {
return getId() == getArtistPlayedId().longValue() && getPlayingType() == PlayingType.Artist && getState() == PlayingState.Playing;
}
}
public abstract class PlayEntity extends PlayerStateEntity {
public abstract boolean isItemPlaying();
}
public class ArtistsRepository {
private final ChartArtistDao chartArtistDao;
private final DeezerService deezerService;
#Inject
public ArtistsRepository(ChartArtistDao chartArtistDao, DeezerService deezerService) {
this.chartArtistDao = chartArtistDao;
this.deezerService = deezerService;
}
public LiveData<PagedList<ChartArtistDao.Artist>> getArtist() {
return new PagedNetworkBoundResource<ChartArtistDao.Artist, ModelList<ChartArtistEntity>>() {
#Override
protected void saveCallResult(#NonNull ModelList<ChartArtistEntity> item) {
if (item != null) {
chartArtistDao.saveArtists(item.getItems());
}
}
#Override
protected List<ChartArtistDao.Artist> loadFromDb(int startPosition, int count) {
return chartArtistDao.loadArtists(startPosition, count);
}
#Override
protected Call<ModelList<ChartArtistEntity>> createCall(int startPosition, int count) {
return deezerService.getChartArtist(startPosition, count);
}
}.getAsLiveData();
}
}
For each Artist items I add fields from PlayerStateEntity (not good solution but this easy way to represent state of ui items). After PlayerStateEntity table updates Room should notify about data changes, but doesn't do it.
I understand that Room doesn't know about query what I used, and can't updates my RecyclerView which provide by paging library. But maybe some one knows how to notify Room about tables which I used inside mine DataSource for future triggering ui updates?
The problem was related with custom DataSource realization. When data has changed, LivePagedListProvider should create a new DataSource instance for right ui updating. I used the same instance, so my previous solution is not right.

Using Camel to Parse CSV

I am attempting to use Camel's bindy annotation to parse through a CSV. I have followed some tutorials online but cannnot seem to get them to work. I am new to this side of camel, so I dont quite understand the errors I am getting. For right now my CSV is very simple as I am just trying to understand how this functionallity works.
The CSV currently looks likes this:
HDR|Suborg|CountryCode|BrokerFile|Batch|Time|Date|
The Error Im getting it this:
org.apache.camel.RuntimeCamelException: java.lang.InstantiationException: com.ups.ttg.bsis.fromdos.AlamoHdr
Here is my code:
public class AlamoPipeRouteBuilder extends RouteBuilder {
final DataFormat bindy = new BindyCsvDataFormat(AlamoHdr.class);
/*
* Endpoints
*/
#EnforceInitialization
private Logging logging;
#EnforceInitialization
private RatingProfileAlamoSplitHandler ratingProfileAlamoSplitHandler;
#EnforceInitialization
private String start = "";
#EnforceInitialization
private String end = "";
#Override
public void configure() throws Exception {
System.out.println("Started Configure Method");
/*
* Basic Route
*/
from(start)
.setExchangePattern(ExchangePattern.InOnly)
.routeId("processRatingProfile.alamo")
//.beanRef("RatingProfileExchangeUtilies", "checkForNoRecords(*)")
.beanRef("logging", "debug(*, 'Starting aggregation strategy loop...')")
.split(body().tokenize("\n"), ratingProfileAlamoSplitHandler).streaming()
.unmarshal(bindy)
.setHeader("INDEX", simple("${header.CamelSplitIndex}") )
.setHeader("COMPLETE", simple("${header.CamelSplitComplete}") )
.end()
.beanRef("logging", "debug(*, 'Aggregation strategy loop complete...')")
.removeHeader("lastRatingProfile")
.to(end);
}
public void setStart(String start) {
this.start = start;
}
public void setEnd(String end) {
this.end = end;
}
public void setRatingProfileAlamoSplitHandler(RatingProfileAlamoSplitHandler ratingProfileAlamoSplitHandler) {
this.ratingProfileAlamoSplitHandler = ratingProfileAlamoSplitHandler;
}
public void setLogging(Logging logging) {
this.logging = logging;
}
}
public class RatingProfileAlamoSplitHandler implements AggregationStrategy {
#EnforceInitialization
private static Logging logging;
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
Integer currIndex = -1;
boolean lastLine = false;
if(newExchange != null) {
currIndex = (Integer) newExchange.getIn().getHeader("INDEX");
System.out.println("THIS IS THE INDEX: " + currIndex);
/*lastLine = (Boolean) newExchange.getIn().getHeader("COMPLETE");
System.out.println("THIS IS THE COMPLETE: " + lastLine);*/
System.out.println("This IS THE BODY: " + newExchange.getIn().getBody());
if(currIndex == 0) {
AlamoHdr alamoHdr = (AlamoHdr) newExchange.getIn().getBody();
}
}
return newExchange;
}
public static void setLogging(Logging logging) {
RatingProfileAlamoSplitHandler.logging = logging;
}
}
public class AlamoHdr implements InitializingBean, DisposableBean {
#DataField(pos = 2, trim = true)
private String suborg;
#DataField(pos = 3, trim = true)
private String countryCode;
#DataField(pos = 4, trim = true)
private String brokerFile;
#DataField(pos = 5, trim = true)
private String batch;
#DataField(pos = 6, trim = true)
private String time;
#DataField(pos = 7, trim = true)
private String date;
public AlamoHdr(String suborg, String countryCode, String brokerFile, String batch, String time, String date) {
super();
this.suborg = suborg;
this.countryCode = countryCode;
this.brokerFile = brokerFile;
this.batch = batch;
this.time = time;
this.date = date;
}
public String getSuborg() {
return suborg;
}
public void setSuborg(String suborg) {
this.suborg = suborg;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getBrokerFile() {
return brokerFile;
}
public void setBrokerFile(String brokerFile) {
this.brokerFile = brokerFile;
}
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#Override
public String toString() {
return "AlamoHdr [suborg=" + suborg + ", countryCode=" + countryCode + ", brokerFile=" + brokerFile + ", batch="
+ batch + ", time=" + time + ", date=" + date + "]";
}
public void destroy() throws Exception {
// TODO Auto-generated method stub
}
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
}
}
For anyone who may also come across this problem, I found what was going wrong. When using a | as your separator you need to pass it in like so
#CsvRecord(separator = "\\|", skipFirstLine = false)
because the | is a meta character that represents the OR operation and we need a regular expression for this operation.
Also you cannot have a constructor in files like AlamoHdr because the variables are being populated through the binding not through calling the constructor.

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);

I am getting "Exception in thread "main" java.lang.NullPointerException even though no values are set to null

public class ParkedCar {
private String make;
private String model;
private String color;
private String licenseNum;
public ParkedCar(String make, String model, String color, String licenseNum) {
this.make = make;
this.model = model;
this.color = color;
this.licenseNum = licenseNum;
}
public void setMake(String ma) {
make = ma;
}
public void setModel(String mo) {
model = mo;
}
public void setColor(String c) {
color = c;
}
public void setLicenseNum(String ln) {
licenseNum = ln;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getLicenseNum() {
return licenseNum;
}
}
public class ParkingMeter {
private ParkedCar parkedcar;
private int timePurchased;
private int timeParked;
public ParkingMeter(ParkedCar parkedcar, int timePurchased, int timeParked) {
this.parkedcar = parkedcar;
this.timePurchased = timePurchased;
this.timeParked = timeParked;
}
/*public ParkingMeter (ParkedCar parkedcar) {
this.parkedcar = null;
}*/
public void setTimePurchased(int timePurchased) {
this.timePurchased = timePurchased;
}
public int getTimePurchased() {
return timePurchased;
}
public void setTimeParked(int timeParked) {
this.timeParked = timeParked;
}
public int getTimeParked() {
return timeParked;
}
public int TimeExpired() {
if (timeParked > timePurchased)
return timeParked - timePurchased;
else
return 0;
}
public String toString() {
return "Make: " + parkedcar.getMake() + "\nModel: " + parkedcar.getModel() + "\nColor: " + parkedcar.getColor() + "\nLicense Number: " + parkedcar.getLicenseNum();
}
}
public class ParkingTicket {
private ParkingMeter parkingmeter;
public ParkingTicket(ParkingMeter parkingmeter) {
this.parkingmeter = parkingmeter;
}
public int TicketCost() {
if (parkingmeter.getTimeParked() > parkingmeter.getTimePurchased()) {
if (parkingmeter.getTimeParked() <= 60)
return 25;
else
return 25 + (10*(parkingmeter.TimeExpired())/60);
}
else
return 0;
}
}
public class PoliceOfficer {
private String OfficerName;
private int OfficerNum;
private ParkingMeter pm;
private ParkingTicket pt;
public PoliceOfficer(ParkingTicket pt, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
public void setOfficerName(String OfficerName) {
this.OfficerName = OfficerName;
}
public void setOfficerNum(int OfficerNum) {
this.OfficerNum = OfficerNum;
}
public String getOfficerName() {
return OfficerName;
}
public int getOfficerNum() {
return OfficerNum;
}
public boolean isExpired() {
if (pm.getTimeParked() > pm.getTimePurchased())
return true;
else
return false;
}
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
}
public class ParkingTicketDemo {
public static void main(String[] args) {
ParkedCar pc = new ParkedCar("Toyota", "Camry", "Blue", "BXZ 152");
System.out.println(pc);
ParkingMeter pm = new ParkingMeter(pc, 60, 120);
ParkingTicket pt = new ParkingTicket(pm);
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
}
}
I have been trying to create a program to create and issue a parking ticket and have run into the problem where it compiles, but when it runs it gives out the error message Exception in thread "main" java.lang.NullPointerException. I am a fairly new programmer and this is the first time I have encountered the problem so I have yet fully understand it and cannot seem to fix it. i have tried reading other things online, but just do not understand I would love a simple explaination to my problem.
The NPE happens because of these two lines:
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
In your constructor for PoliceOfficer, you don't do anything with the ParkingTicket instance pt.
public PoliceOfficer(ParkingTicket pt /* not set anywhere */, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
The fields ParkingMeter pm and ParkingTicket pt remain null since you haven't initialized them.
Then you try to print the object: System.out.println(po); What this does is call toString() on po, it is equivalent to this:
System.out.println(po.toString());
Now because your toString()
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
uses the pt, it creates a NullPointerException, since pt is null.
Since you are already passing a ParkingTicket instance into the constructor for PoliceOfficer, use that instance to assign its member variable pt.

Error when using DocumentReferences with Ektorp and JSF

I have been getting an error with DocumentReferences in a small JSF project i created to learn CouchDB/Ektorp .
I belive everything is working as is should in the CRUD, the id of the parent document is stored as a string, similar to the tutorial project.
But when I retrieve the parent object from the database I get this error:
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type
[simple type, class com.pro.documents.Apple] from JSON String; no single-String
constructor/factory method (through reference chain: com.pro.documents.Eiere["apple"])
Here is the rest of the code:
{
"_id": "_design/Eiere",
"_rev": "17-ebb06b0d3102622a3d9849b9399cd94f",
"language": "javascript",
"views": {
"all": {
"map": "function(doc){if (doc.type == 'eiere') {emit(doc._id, doc);}}"
},
"ektorp_docrefs_apple": {
"map": "function(doc){ if(doc.eiere){emit([doc.eiere, 'apple', doc.kategori], null);}}"
}
}
}
{
"_id": "_design/Apple",
"_rev": "8-e04d8b5633776545b9eacdc998db4aea",
"language": "javascript",
"views": {
"all": {
"map": "function(doc){ if(doc.type == 'apple'){emit(doc._id, doc);}}"
}
}
}
public class Eiere extends CouchDbDocument {
#TypeDiscriminator
private String type;
private String navn;
private String telefon;
#DocumentReferences(backReference = "eiere", fetch = FetchType.LAZY, descendingSortOrder = true)
private Set<Apple> apple;
private Date dateCreated;
public Set<Apple> getApple() {
return apple;
}
public void setApple(Set<Apple> apples) {
this.apple = apples;
}
public void addApple(Apple c) {
Assert.notNull(c, "Apple may not be null");
if (getApple() == null) {
apple = new TreeSet<Apple>();
}
c.setEiere(this.getId());
apple.add(c);
}
public String getType() {
if (type == null) {
type = "eiere";
}
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
public String getTelefon() {
return telefon;
}
public void setTelefon(String telefon) {
this.telefon = telefon;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
}
public class Apple extends CouchDbDocument implements Comparable<Apple>{
private static final long serialVersionUID = 1L;
#TypeDiscriminator
private String type;
private List<String> prices;
private String kategori;
private String eiere;
private Date dateCreated;
public String getType() {
if(type == null){
type = "apple";
}
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getPrices() {
if(prices == null){
prices = new ArrayList<String>();
prices.add(0, " ");
prices.add(1, " ");
prices.add(2, " ");
}
return prices;
}
public void setPrices(List<String> prices) {
this.prices = prices;
}
public String getKategori() {
return kategori;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public String getEiere() {
return eiere;
}
public void setEiere(String eiere) {
this.eiere = eiere;
}
#Override
public String toString() {
return prices.toString();
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Override
public int compareTo(Apple other) {
if (other == this) return 0;
if (dateCreated != null) {
return - dateCreated.compareTo(other.dateCreated);
}
return 0;
}
}
Any help or advice to help me understand what I'm doing wrong will be much appreciated.
Edit: If there is any information that I could add that would make my problem clearer or help in determining the cause of it please let me know.
Br.

Categories

Resources