Having issue on linking an image, with a bitmap created before - android

since a long time, I have tried to link an image to a Bitmap. I have already created the bitmap, I know how to put it into my image (here it is an icon from Google Maps but it changes nothing). What I want is link this icon to my bitmap called bmp. But there is an error :
Cannot resolve symbol 'bmp'
Here is my code to help you understand my issue :
private void initMarker(List<LocationModel> listData) {
//iterasi semua data dan tampilkan markerny
for (int i = 0; i < mListMarker.size(); i++) {
Bitmap bmp = null;
URL url;
try {
url = new URL(mListMarker.get(i).getIconImage());
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException y) {
y.printStackTrace();
return ;
}
//set latlng nya
LatLng location = new LatLng(Double.parseDouble(mListMarker.get(i).getLatutide()), Double.parseDouble(mListMarker.get(i).getLongitude()));
//tambahkan markernya
mMap.addMarker(new MarkerOptions().position(location).title(mListMarker.get(i).getImageLocationName()).snippet(mListMarker.get(i).getIconImage()).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
//.icon(BitmapDescriptorFactory.fromBitmap(XXX))
//set latlng index ke 0
LatLng latLng = new LatLng(Double.parseDouble(mListMarker.get(0).getLatutide()), Double.parseDouble(mListMarker.get(0).getLongitude()));
//lalu arahkan zooming ke marker index ke 0
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLng.latitude, latLng.longitude), 11.0f));
}
}

You create the instance inside the try-catch statement, but reference it outside:
try{
Bitmap bmp = ...
}catch(IOException e){
//e.print....
}
//do something with bmp
You can't do that as it's locally created within the try-catch statement and can't be accessed outside. Do this instead:
Bitmap bmp = null;
try{
URL url = new URL(mListMarker.get(i).getImageLocationName());
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}catch(IOException e){
//Print stacktrace and return. Otherwise you get an NPE if it fails
}
Declaring it outside the try-catch allows it to be accessed outside it

Related

OSMDroid Throwing OutOfMemoryError when parsing geoJSON on resume

I'm populating an osm map with markers using parseGeoJSON, it works fine when the activity is first started, but if the activity is resumed I get Throwing OutOfMemoryError
Here's my code, it's run from an AsyncTask.
KmlDocument lines = new KmlDocument();
Drawable defaultMarker = getResources().getDrawable(R.drawable.pin);
Bitmap defaultBitmap = ((BitmapDrawable)defaultMarker).getBitmap();
Style defaultStyle = new Style(defaultBitmap, 0x901010AA, 8.0f, 0x20AA1010);
try {
lines.parseGeoJSON(IOUtils.toString(getResources().openRawResource(R.raw.line), "UTF-8"));
linesOver = (FolderOverlay) lines.mKmlRoot.buildOverlay(map, defaultStyle, null, lines);
} catch (IOException e) {
e.printStackTrace();
}
return null;

Importing multiple images in Android application

How can I import multiple images on my Android app? Can I assign single id to that bundle of images to bring it from drawable? Suggest me a way.
Currently I am only able to display one image multiple times in line layout. Here is the code line to bring the image:
placeholder = BitmapFactory.decodeResource(getResources(), R.drawable.picture2);
Should I enter multiple lines for picture3,picture4,...etc?
Simplest way I can think of:
int ids[] = new int[] {
R.drawable.picture2,
R.drawable.picture3,
R.drawable.picture4
};
Bitmap bitmaps[] = new Bitmap[ids.length];
for(int i = 0; i < ids.length; i += 1){
bitmaps[i] = BitmapFactory.decodeResource(getResources(), ids[i]);
}
Also you can re-write it as a function for improving modularity.
public Bitmap[] loadBitmaps(int ids[]){
Bitmap bitmaps[] = new Bitmap[ids.length];
for(int i = 0; i < ids.length; i += 1){
bitmaps[i] = BitmapFactory.decodeResource(getResources(), ids[i]);
}
return bitmaps;
}
Instead of Drawable store all images in Assets then you can get Image by passing name. Add following function in your activity.
private Bitmap getBitmapFromAsset(String paramString)
{
Object localObject = getResources().getAssets();
try
{
Bitmap ret = BitmapFactory.decodeStream(((AssetManager)localObject).open(paramString));
return ret;
}
catch (IOException ex)
{
ex.printStackTrace();
}
return null;
}

How to get Image Bitmap from cache with Volley Library

I want to get Image from cache memory, I am using volley library and displaying image successfully. I want to get same downloaded image from cache Below is my code.
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(ImageUrl);
if (entry != null) {
try {
// Get Data From Catch Successefully
String data = new String(entry.data, "UTF-8");
// but now this code return null value i want Bitmap From Catch
LruBitmapCache bitmapCache = new LruBitmapCache();
mBitmap = bitmapCache.getBitmap(data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
I can get data from cache, but bitmapCache.getBitmap(data); return's null.
use this line instead to convert entry.data into bitmap:
mBitmap = BitmapFactory.decodeByteArray(entry.data, 0, entry.data.length);

Libgdx getting Image from facebook at runtime

I have image-url getting from facebook, I want to display that image at runtine in my game in libgdx.I am using facebook graph api and parse data with help of Json parsing. my approach is as follows:
In main activity
protected void gettingfacebookData() {
try {
JSONArray friendArray = new JSONArray(
prefLevel.getFriendFacebookData());
for (int i = 0; i < friendArray.length(); i++) {
JSONObject jsonObject = friendArray.getJSONObject(i);
String name = jsonObject.getString("name");
String score = jsonObject.getString("score");
String fid = jsonObject.getString("fid");
String image = "http://graph.facebook.com/" + fid
+ "/picture?type=large";
//saving score into array list
PlayingScreen.scoreAl.add(score);
//saving image url into arraylist
PlayingScreen.imageUrlAl.add(image);
} }
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now how can I display image at run time with this particular image url?
We use a wrapper class, that wraps Texture, for displaying images from web (like facebook profile pictures). This wrapper class takes url of the image and a temporary texture. Just as the wrapper is created, it starts to download image bytes in a background thread. Consumer of this wrapper class simply calls getTexture() to obtain texture and until download has finished, this method returns the temporary texture. When there are bytes available to create a texture getTexture() processes this bytes and starts to return new texture created from url.
Below is a simple version of this wrapper class. Note that, processTextureBytes is called inside getTexture method, not somewhere in background thread. It is because we have to construct texture in the thread which obtains the GLContext. You can add caching and retry mechanisms to this class.
BTW, instead of using http://graph.facebook.com/[uid]/picture url try using one of pic_ urls from FQL. You may want to check this.
public class WebTexture {
private final String url;
private Texture texture;
private volatile byte[] textureBytes;
public WebTexture(String url, Texture tempTexture) {
this.url = url;
texture = tempTexture;
downloadTextureAsync();
}
private void downloadTextureAsync() {
Utils.runInBackground(new Runnable() {
#Override
public void run() {
textureBytes = downloadTextureBytes();
}
});
}
private byte[] downloadTextureBytes() {
try {
return Utils.downloadData(url);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Texture getTexture() {
if (textureBytes != null)
processTextureBytes();
return texture;
}
private void processTextureBytes() {
try {
Pixmap pixmap = new Pixmap(textureBytes, 0, textureBytes.length);
Texture gdxTexture = new Texture(pixmap);
gdxTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
texture = gdxTexture;
} catch (Throwable t) {
t.printStackTrace();
} finally {
textureBytes = null;
}
}
}
You should download the image.
Once you have your image as a byte array, you can create a pixmap:
Pixmap pixmap = new Pixmap(imageBytes, 0, imageBytes.length);
Then you can use this pixmap to render the image. For example if are you using scene2d.ui you can set Image's drawable as follows:
image.setDrawable(new TextureRegionDrawable(new TextureRegion(new Texture(profilePicture))));
Hope this helps.

A dummy map tile provider not working (getTile not being called)

I would like to use the google maps api v2, but show just a dummy map in the background.
This is a sample of the PNG file I am using, called "dummy_map_tile.png". I placed it in the asset folder, under a dir named "images". It's size is 256x256 pixels. Tried also a JPG similar file.
This is the code for my dummy map tile provider, which of course is supposed to work offline:
public class DummyTileProvider implements TileProvider {
protected Tile mDummyTile = null;
public DummyTileProvider(Context context) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
String tileFilename = "images/dummy_map_tile.png";
inputStream = context.getResources().getAssets().open(tileFilename);
outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int count;
while((count = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, count);
outputStream.flush();
mDummyTile = new Tile(256, 256, outputStream.toByteArray());
}
catch (IOException e) {
mDummyTile = null;
}
finally {
if (inputStream != null)
try {inputStream.close();} catch (IOException e) {}
if (outputStream != null)
try {outputStream.close();} catch (IOException e) {}
}
}
#Override
public Tile getTile(int x, int y, int zoom) {
return mDummyTile;
}
}
Some logging (not shown in the code above) allowed me to make sure that the dummy tile provider constructs properly, i.e. no IOException occurs, and mDummyTile is not null.
This is the way I am setting the tile provider in the map setup (mMap is my GoogleMap object, properly initialized):
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
DummyTileProvider tileProvider = new DummyTileProvider(this);
mMap.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
Unfortunately, the map doesn't show at all.
The getTile method is never called.
All markers and other stuff I am drawing on the map work correctly, though.
If I remove the three lines of code above, thus using the default tile provider, all works perfectly, showing the standard google maps (only in online mode).
Can anyone give me a useful hint?
There is nothing wrong with the tile provider. It was just a mistake in the rest of the code, that happened to call method clear() on the map object, thus removing the tile provider from the map. Nevertheless, I hope this example of a dummy tile provider can be useful, so I'll leave it here.

Categories

Resources