How to load a Google maps static map using Picasso? - java

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)

Related

JasperReports export to Excel uses only last set background color

Im pretty pretty new to Dynamic-Jasper, but due to work i had to add a new feature to our already implemented solution.
My Problem
The Goal is to add a Column to a report that consists only out of a background-color based on some Information. I managed to do that, but while testing I stumbled upon a Problem. While all my Columns in the html and pdf view had the right color, the Excel one only colored the fields in the last Color.
While debugging i noticed, that the same colored Fields had the same templateId, but while all Views run through mostly the same Code the Excel one showed different behavior and had the same ID in all fields.
My Code where I manipulate the template
for(JRPrintElement elemt : jasperPrint.getPages().get(0).getElements()) {
if(elemt instanceof JRTemplatePrintText) {
JRTemplatePrintText text = (JRTemplatePrintText) elemt;
(...)
if (text.getFullText().startsWith("COLOR_IDENTIFIER")) {
String marker = text.getFullText().substring(text.getFullText().indexOf('#') + 1);
text.setText("ID = " + ((JRTemplatePrintText) elemt).getTemplate().getId());
int rgb = TypeConverter.string2int(Integer.parseInt(marker, 16) + "", 0);
((JRTemplatePrintText) elemt).getTemplate().setBackcolor(new Color(rgb));
}
}
}
The html view
The Excel view
Temporary Conclusion
The same styles uses the same Objects in the background and the JR-Excel export messes something up by assigning the same Object to all the Fields that I manipulated there. If anyone knows of a misstake by me or potential Solutions to change something different to result the same thing please let me know.
Something different I tried earlier, was trying to set the field in an evaluate Method that was called by Jasper. In that method we assign the textvalue of each field. It contained a map with JRFillFields, but unfortunatelly the Map-Implementation denied access to them and just retuned the Value of those. The map was provided by dj and couldn't be switched with a different one.
Edit
We are using JasperReports 6.7.1
I found a Solution, where I replaced each template with a new one that was supposed to look exactly alike. That way every Field has its own ID guaranteed and its not up to chance, how JasperReports handles its Data internaly.
JRTemplateElement custom =
new JRTemplateText(((JRTemplatePrintText) elemt).getTemplate().getOrigin(),
((JRTemplatePrintText) elemt).getTemplate().getDefaultStyleProvider());
custom.setBackcolor(new Color(rgb));
custom.setStyle(((JRTemplatePrintText) elemt).getTemplate().getStyle());
((JRTemplatePrintText) elemt).setTemplate(custom);

Spring Social Facebook: Get Facebook Post Image [duplicate]

I'm currently using the Graph API Explorer to make some tests. That's a good tool.
I want to get the user's friend list, with friends' names, ids and pictures. So I type :
https://graph.facebook.com/me/friends?fields=id,picture,name
But picture is only 50x50, and I would like a larger one in this request.
Is it possible ?
As described in this bug on Facebook, you can also request specific image sizes now via the new API "field expansion" syntax.
Like so:
https://graph.facebook.com/____OBJECT_ID____?fields=picture.type(large)
The best way to get all friends (who are using the App too, of course) with correct picture sizes is to use field expansion, either with one of the size tags (square, small, normal, large):
/me/friends?fields=picture.type(large)
(edit: this does not work anymore)
...or you can specify the width/height:
me/friends?fields=picture.width(100).height(100)
Btw, you can also write it like this:
me?fields=friends{picture.type(large)}
you do not need to pull 'picture' attribute though. there is much more convenient way, the only thing you need is userid, see example below;
https://graph.facebook.com/user_id/picture?type=large
p.s. type defines the size you want
plz keep in mind that using token with basic permissions, /me/friends will return list of friends only with id+name attributes
You can set the size of the picture in pixels, like this:
https://graph.facebook.com/v2.8/me?fields=id,name,picture.width(500).height(500)
In the similar manner, type parameter can be used
{user-id}/?fields=name,picture.type(large)
From the documentation
type
enum{small, normal, album, large, square}
Change the array of fields id,name,picture to id,name,picture.type(large)
https://graph.facebook.com/v2.8/me?fields=id,name,picture.type(large)&access_token=<the_token>
Result:
{
"id": "130716224073524",
"name": "Julian Mann",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15032818_133926070419206_3681208703790460208_n.jpg?oh=a288898d87420cdc7ed8db5602bbb520&oe=58CB5D16"
}
}
}
You can also try getting the image if you want it based on the height or width
https://graph.facebook.com/user_id/picture?height=
OR
https://graph.facebook.com/user_id/picture?width=
The values are by default in pixels you just need to provide the int value
I researched Graph API Explorer extensively and finally found full_picture
https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture
P.S. I noticed that full_picture won't always provide full size image I want. 'attachments' does
https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture,attachments
Hum... I think I've found a solution.
In fact, in can just request
https://graph.facebook.com/me/friends?fields=id,name
According to http://developers.facebook.com/docs/reference/api/ (section "Pictures"), url of profile's photos can be built with the user id
For example, assuming user id is in $id :
"http://graph.facebook.com/$id/picture?type=square"
"http://graph.facebook.com/$id/picture?type=small"
"http://graph.facebook.com/$id/picture?type=normal"
"http://graph.facebook.com/$id/picture?type=large"
But it's not the final image URL, so if someone have a better solution, i would be glad to know :)
You can specify width & height in your request to Facebook graph API: http://graph.facebook.com/user_id/picture?width=500&height=500
You can size it as follows.
Use:
https://graph.facebook.com/USER_ID?fields=picture.type(large)
For details: https://developers.facebook.com/docs/graph-api/reference/user/picture/
From v2.7, /<picture-id>?fields=images will give you a list with different size of the images, the first element being the full size image.
I don't know of any solution for multiple images at once.
I got this error when I made a request with picture.type(full_picture):
"(#100) For field 'picture': type must be one of the following
values: small, normal, album, large, square"
When I make the request with picture.type(album) and picture.type(square), responses me with an image 50x50 pixel size.
When I make the request with picture.type(large), responses me with an image 200x200 pixel size.
When I make the request with picture.width(800), responses me with an image 477x477 pixel size.
with picture.width(250), responses 320x320.
with picture.width(50), responses 50x50.
with picture.width(100), responses 100x100.
with picture.width(150), responses 160x160.
I think that facebook gives the images which resized variously when the user first add that photo.
What I see here the API for requesting user Image does not support
resizing the image requested. It gives the nearest size of image, I think.
In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).
Hacakable URLs/REST API make the Web better.
rest-fb users (square image, bigger res.):
Connection myFriends = fbClient.fetchConnection("me/friends", User.class, Parameter.with("fields", "public_profile,email,first_name,last_name,gender,picture.width(100).height(100)"));
I think that as of now the only way to get large pictures of friends is to use FQL. First, you need to fetch a list of friends:
https://graph.facebook.com/me/friends
Then parse this list and extract all friends ids. When you have that, just execute the following FQL query:
SELECT id, url FROM profile_pic WHERE id IN (id1, id2) AND width=200 AND height=200
200 here is just an exemplary size, you can enter anything. You should get the following response:
{
"data": [
{
"id": ...,
"url": "https://fbcdn-profile-a.akamaihd.net/..."
},
{
"id": ...,
"url": "https://fbcdn-profile-a.akamaihd.net/..."
}
]
}
With each url being the link to a 200x200px image.
I have the same problem but i tried this one to solve my problem. it returns large image.
It is not the perfect fix but you can try this one.
https://graph.facebook.com/v2.0/OBJECT_ID/picture?access_token=XXXXX
try to change the size of the image by changing the pixel size from the url in each json object as follows :
for example I change s480x480 to be s720x720
Before :
https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xfp1/t1.0-9/q71/s480x480/10454308_773207849398282_283493808478577207_n.jpg
After :
https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xfp1/t1.0-9/q71/s720x720/10454308_773207849398282_283493808478577207_n.jpg
JS styled variant.
Just set enormous large picture width and you will get the largest variant.
FB.api(
'/' + userId,
{fields: 'picture.width(2048)'},
function (response) {
if (response && !response.error) {
console.log(response.picture.data.url);
}
}
);
You can use full_picture instead of picture key to get full size image.
Note: From Graph API v8.0 you must provide the access token for every UserID request you do.
Hitting the graph API:
https://graph.facebook.com/<user_id>/picture?height=1000&access_token=<any_of_above_token>
With firebase:
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" +
loginResult.getAccessToken().getToken();
You get the token from registerCallback just like this
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" + loginResult.getAccessToken().getToken();
}
#Override
public void onCancel() {
Log.d("Fb on Login", "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.e("Fb on Login", "facebook:onError", error);
}
});
This is what documentation says:
Beginning October 24, 2020, an access token will be required for all
UID-based queries. If you query a UID and thus must include a token:
use a User access token for Facebook Login authenticated requests
use a Page access token for page-scoped requests
use an App access token for server-side requests
use a Client access token for mobile or web client-side requests
We recommend that you only use a Client token if you are unable to use
one of the other token types.

Android Picasso - Clear cache but image remains

So at certain times I need to clear the Picasso cache within my application, however when I clear it, the image is the same. If the image URL changes, then it pulls the new image but if the image url is the same, then the old image remains.
Can anyone help me clear the cache so that the image is removed?
This is how I set Picasso up:
Cache picassoCache = new LruCache(MEMORY_CACHE_SIZE);
picassoCacheClearer = new PicassoCacheClearerImpl(picassoCache);
picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(context.getCacheDir(), IMAGE_CACHE_SIZE))
.memoryCache(picassoCache)
.build();
and then try and clear it by:
cache.clear();
Below is the code which actually loads the image:
picasso.load(carouselAction.getImageUrl())
.placeholder(R.drawable.ic_placeholder)
.into(viewHolder.plistImageView);
I can see that the Invalidate() method is now deprecated, so what else can i do?
I have had this same problem and I used this hacky method to get around it. To force it to refresh i would just change the url adding a version tag to it. This is used commonly in web development to make sure things aren't used from the cache.
For example i would load an image from example.com/mypic.png?version=1234
and since the url is different it wouldn't load it from cache.
String versionTag = "?version=" + new Date().getTime();
picasso.load(carouselAction.getImageUrl() + versionTag)
.placeholder(R.drawable.ic_placeholder)
.into(viewHolder.plistImageView);
So found out what the issue was. Turns out for this carousel it was using a different instance of Picasso.
I also had to extend OkHttpDownloader to expose the getClient() method in order to get the cache to delete.
I realised it was a different instance of Picasso by enabling the indicators which can be done by setting the following in the builder
.indicatorsEnabled(true);

Most efficient way to load a lot of images from URL Android

I'm making this netflix style app in which images are loaded into different categories. Let's say Dog videos (has 15 images), Cat videos (15 images), etc... All the images are loaded from a URL, it kind of takes a while for all to load. I was wondering if there was anything I could do to speed up the process? Or maybe show an empty container then fill it as the images load (that would be cool).
This is what I have done:
I have multiple async calls in one Activity, (1 async call per category)
JSONTask1 dogTask = new JSONTask1();
JSONTask2 catTask = new JSONTask2();
JSONTask3 pigTask = new JSONTask3();
JSONTask4 horseTask = new JSONTask4();
dogTask.execute("");
catTask.execute("");
pigTask.execute("");
horseTask.execute("");
I have all of those in a row in my actual code. Thanks.
I would use the "proxy pattern". Basically, you need to create a class that contains the minimal informations required for the display. In which, you have a preview image.
When ever you load everything you start by showing the preview content, ie : a loading gif for everypicture with the title of the movie or whatever. and basically the proxy would have a "loadImage" method that would make an ajax call or async call and the photos would load one by one. Plus, to make the loading easier, make sure the photos are not oversized.
You can see Picasso answers , in picasso i suggest you this way :
Picasso.with(getApplicationContext()).load("your url").placeholder(R.drawable.your_place_holder).error(R.drawable.showing_when_error_occured)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});
Also another suggestion from me : convert your thumb images to base64 format in backend, then firstly retrieve your thumbs and show them. Then start an async task and change images when successfull.
Like whatsapp. In whatsapp you have thumb images they have so low resolution and super fast. When you click image if you have internet connection they load actual thumb images, and click again they load larger image.
Picasso website :http://square.github.io/picasso/
Load them asynchronously with Picasso, you can even show a placeholder image until the real one is loaded

Android Libgdx TileAtlas

I am trying to add a Map to my libgdx app as a proof of concept. It seems that no matter how I make a packfile, the com.badlogic.gdx.graphics.g2d.tiled.TileAtlas constructor TileAtlas(TiledMap map, FileHandle inputDir) will not correctly read it. My Tile Map is simple and has only 2 tiles, and both the external gui and internal system will generate a packed file.
Here's the issue, either I name the packfile with a filename to match one of my images to satisfy line 2 below, or the method errors out. If I add 2 packfiles, one for each name of an image in my tile set, I find the Atlas isn't constructed correctly in memory. What am I missing here? Should there only ever be one tile in a tilemap?
Code from Libgdx:
for (TileSet set : map.tileSets) {
FileHandle packfile = getRelativeFileHandle(inputDir, removeExtension(set.imageName) + " packfile");
TextureAtlas textureAtlas = new TextureAtlas(packfile, packfile.parent(), false);
Array<AtlasRegion> atlasRegions = textureAtlas.findRegions(removeExtension(removePath(set.imageName)));
for (AtlasRegion reg : atlasRegions) {
regionsMap.put(reg.index + set.firstgid, reg);
if (!textures.contains(reg.getTexture())) {
textures.add(reg.getTexture());
}
}
}
com.badlogic.gdx.graphics.g2d.tiled --> It looks like you're using the old tiled API. I don't even think that package exists anymore, so you should probably download a newer version.
Check out this blog article. I haven't used the new API yet, but at a quick glance it looks much easier to load maps.

Categories