How do I save and load entire sql tables - java

I have a maps app on android that tracks your route via location data and stores the LatLng points in an SQL database and draws a line on the map with Polyline.
I would like to go further with that and allow the user to be able to save the route and load past routes. Is there a way that I can store/delete the entire table data into a file so that a fresh route can be created, then be able to load that file into the database again if the user chooses?

1: use objects to store your datas, and keep them as a Collection for example (Set, Map, ...)
2: use serialization, it is direct
What does Serializable mean?

You could try making a Route class, containing all information you want to store in your database, like so:
public class Coordinate {
double longitude;
double latitude;
public Coordinate(double x, double y){
this.longitude = x;
this.latitude = y;
}
}
public class Route {
private List<Coordinate> coordinates;
public Route() {
coordinates = new ArrayList<>();
}
}
Using Google Gson, you can convert routes to a Json file. You can store these files in the local storage, and use them when the user wants to use a past route.

A fantastic Guide to get you started:
http://developer.android.com/training/location/receive-location-updates.html
A tutorial, probably exactly what you are looking for:
http://javapapers.com/android/draw-path-on-google-maps-android-api/
Further Reading:
I would look at Google's Android Location API:
https://developers.google.com/android/reference/com/google/android/gms/location/package-summary
It also has a listener inbuilt, so that when the users location changes it will update you automatically.
You could then keep a history, like you suggest in your Database and when required. Then when required using the API to rebuild or monitor the users current path.
Location Listener: https://developers.google.com/android/reference/com/google/android/gms/location/LocationListener
Your Data, like you also suggest should translate to/from the API stored 'Location' format of:
http://developer.android.com/reference/android/location/Location.html

Well lets think clever here.
A route contains many possible locations.So a good idea is to create two sql tables.One table will be for the locations and one for routes
So you will make a search and you will find all locations that exist in a route.It depends on what kind of implementation you will make for your database.

Related

How do I retrieve video custom labels through the RestFB API using Java?

I'm creating a java application that pulls data from facebook videos using RestFB. How can I retrieve the custom labels from each video?
Although I'm able to pull the normal data from each video, there doesn't seem to be any RestFB function that gets custom labels.
I've tried creating my own function by copying the RestFB source code for getting the title and then changing it according to the data I need, but that doesn't seem to work.
The custom labels field is missing atm in RestFB, so you can wait until a new version is released or write a custom video type like this:
public class CustomLabelsVideo extends Video {
#Facebook("custom_labels")
private List<String> customLabels = new ArrayList<>();
public List<String> getCustomLabels() {
return customLabels;
}
public void setCustomLabels(List<String> customLabels) {
this.customLabels = customLabels;
}
}
You need to use this type in the fetchObject method, and don't forget to add the custom_labels string to the fields you fetch.

Spring Facebook Template map fetchObject to PagedList

I'm using the following approach to return a Facebook user's music preferences:
//FIXME: Fetch results in a single operation
val likes = facebook.likeOperations().music
val artists = ArrayList<Artist>()
for (musicLiked in likes)
{
val musicProfile = facebook.fetchObject(musicLiked.id, Page::class.java, "id", "name", "genre");
artists.add(Artist(name = musicProfile.name, genre = musicProfile.genre))
}
The above approach won't scale, since we have an additional network operation for each artist the user likes.
I tried:
I tried using facebook.likeOperations.music however this doesn't fetch genre.
Question:
I would like to use facebook.fetchObject with a query that returns a PagedList. How to do this?
(No need to post example code in Kotlin if you prefer or are more familiar with Java - I'll be happy with information in any language).
Facebook api uses "fields" parameter in requests to return custom fields for objects. This parameter can be also used for liked music rest request.
me/music?fields=id,genre,name
above link will return all liked music with id, genre and name of the artist/group. Unfortunately FacebookTemplate does not have method which will apply for your needs. The method Facebook.likeOperations() returns instance of the LikeTemplate class which has constant PAGE_FIELDS with value
private static final String PAGE_FIELDS = "id,name,category,description,location,website,picture,phone,affiliation,company_overview,likes,checkins";
In above constant you do not have genre field. So you have two ways:
You can simply use facebook rest api with some rest library
You can override FacebookTemplate and return your own implementation of LikeTemplate as result of the likeOperations() method. You implementation of the LikeTemplate class should have different value in mentioned constant (added genre field at the end of the string)
Maybe some one will be more helpful but in my knowledge you do not have other options.
Thanks to advice given in #burovmarley's answer, I inspected the source and came up with:
val music = facebook.fetchConnections(userPage.id, "music", Page::class.java,
PagingParameters(25, 0, null, null).toMap(), "id,name,,genre")
for (musicLiked in music)
{
println("likes: ${musicLiked.name}, genre: ${musicLiked.genre}")
}
This allows using Spring Social Facebook as an unmodified dependency, and without issuing a pull request, which seem to be fairly slow in processing through the queue at the present time.

How to save variable value of the last session(program exit) [duplicate]

This question already has an answer here:
Saving user settings from GUI
(1 answer)
Closed 8 years ago.
How can i save the value of a variable in my program and then reuse it at the next program run ? I don't want to do it with file write/read.
Use the Java Preferences API.
import java.util.prefs.*;
public class Example {
// Preference key
private static final String FRUIT = "fruit";
public void savePreference(String favoriteFruit) {
Preferences prefs = Preferences.userNodeForPackage(Example.class);
prefs.put(FRUIT, favoriteFruit);
}
public String readPreference() {
Preferences prefs = Preferences.userNodeForPackage(Example.class);
return prefs.get(FRUIT, "default");
}
}
The data is stored based on the fully-qualified name of your class, so your package name and class name are relevant. From the documentation for the Preferences class:
This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.
One can store settings using java.util.prefs.Preferences. For two target groups: normally user settings, and less often application/system settings. They can use the platform settings, like under Windows.
There exists however also the possibility to store the settings as XML, which is a cleaner way, as it does not touch the Windows registry, which might be protected. Then a customary location would be inside a directory like ".myapp" under the directory System.getProperty("user.home").
You can use an in-memory key-value store like Redis, or an in-memory database like H2. But this may be overkill depending on your needs.

How to load a Google maps static map using Picasso?

In my Android app I use Picasso to load images. This normally works perfectly well.
Today I tried loading a static image from the google maps api, but this doesn't seem to work. When I open the example link as provided on their info page, I get to see the static map image perfectly well. When I load it in my Android app using the line below, I get nothing at all.
Picasso.with(getContext()).load("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false").into(mapView);
I also tried to download the image and uploading it to my personal webspace, from which it loads perfectly well, but somehow, it doesn't seem to load directly from the direct google API url.
Does anybody know why this is so, and how I can solve it?
The only programmatic point-of-failure that comes to mind is in parsing the URI. Looking at the current Picasso code (https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/Picasso.java) I see the following:
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
So I'd first debug
Uri.parse("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false")
and see what that Object looks like. Does it drop or confuse any of your parameters?
If that doesn't lead you anwhere, try downloading the file manually using a HttpClient [or similar]. Then at least you can fully debug the request/response.
Also, I know Google maps has some limits -- are you sure you haven't reached them?
replace http with https
replace | with %7C
add api key
The .loadMap() function has many declared variables. This is the heart of the whole process.
So what is required for the static maps API to give us an image is that we make an http request with a given url, for which an image response (URL) is received. Let us run through the meaning and utility of these variables. Yes, all of them have a completely different meaning!
The mapUrlInitial variable is always the same while making an API call. It has a query of center ( ?center ) which specifies that we want the location to be centered in the map.
The mapUrlProperties variable contains a string where you control the actual zooming of the image response you will get, the size ofthe image and the color of the marker which will point out our place.
The mapUrlMapType variable is a string where you can actually determine the marker size you want and the type of the map. We are using a roadtype map in the app.
Finally latLong is a string which concatenates the latitude and the longitude of the place we want to pinpoint!
We then concatenate all of these strings to form a feasible Url. The Url is then loaded as we have seen above, in the Picasso code. One thing we can notice is that an event object is always required for all of this to happen, because we are able to fetch the position details using the event object! Final Code:-
fun loadMap(event: Event): String{
//location handling
val mapUrlInitial = “https://maps.googleapis.com/maps/api/staticmap?center=”
val mapUrlProperties = “&zoom=12&size=1200×390&markers=color:red%7C”
val mapUrlMapType = “&markers=size:mid&maptype=roadmap”
val latLong: String = “” +event.latitude + “,” + event.longitude
return mapUrlInitial + latLong + mapUrlProperties + latLong + mapUrlMapType
}
//load image
Picasso.get()
.load(loadMap(event))
.placeholder(R.drawable.ic_map_black_24dp)
.into(rootView.image_map)

How to implement a Lazy List using SmartGWT and SQL

I was trying all of yesterday to try and integrate a SQL Database with SmartGWT for a lazy list but I just couldn't figure out how to implement it. (JavaDoc, and example of a lazy list)
What I want to do is create a list of a bunch of "sites" all over the world. The problem is there will probably be about a million of them, so I'm trying to load as few as possible at a time. Each site in my DB has an address, so I'm trying to sort them in the tree structure like (Country->State->City->Sites). Every time you go down a level there will be a query to the DB asking for all of the next level (Whether that be all the cities that have sites in the state chosen, or what ever).
Any help is greatly appreciated.
ALSO:
In the example linked the folders and leafs are the type of element, is there a way to keep folders, folders, and then leafs a separate type of object?
After a while I finally got it. I ended up creating my own RPC that would serve up an array of strings that would represent the names of all the TreeNodes for the next level.
So entry point would be:
private NodeServiceAsync nodesRpc; //The RPC that grabs more nodes
private Tree data; //The data structure to hold all of the nodes
private ColumnTree list; //The GUI element that is shown on in the browser
public void onModuleLoad() {
nodesRpc = (NodeServiceAsync) GWT.create(NodeService.class);
data = new Tree();
list = new ColumnTree;
list.setAutoFetchData(true);
list.setLoadDataOnDemand(true);
list.addNodeSelectedHandler(new NodeSelectedHandler () {
public void onNodeSelected(NodeSelectedEvent event) {
if(/*Node is folder and hasn't been opened before*/) {
//Get More Nodes
AsyncCallback<String[]> callback = new NodeGetter<String[]>();
nodesRpc.getData(event.getNode(), callback);
}
else if(/*Node is not a folder (at the end) */) {
//Do something else
}
}
});
list.setData(data); //Make the GUI Element Represent The Data Structure
RootPanel.get().add(list); //Add to screen
}
The serverlet on the server side creates the query, executes, then translates the ResultSet into an array of Strings and passes that back. All the callback has to do, back on the client side, is translate that array into an array of TreeNodes and attach them to the original Node that was clicked on. Finally after all of this the GUI element is redrawn with the new nodes.
I was surprised that there was very little down time between node loads (less then 1 sec) even when sometimes a hundred or so nodes where being queried then displayed.
Note there is also a Pro version of the product which includes SQL connectivity like this out of the box (for Java server platforms). Showcase here:
http://www.smartclient.com/smartgwtee/showcase/
The SQL connector in the Pro product includes load on demand / data paging, search, and all 4 CRUD operations, as well as DataSource Wizards that can generate a working SQL DataSource for an existing database table if you just enter JDBC settings.
Note the Pro product doesn't require SQL, that's just one of the things it can connect to.

Categories