OSMDroid Throwing OutOfMemoryError when parsing geoJSON on resume - android

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;

Related

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

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

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

How to read line to line when my txt is in the raw folder?

I have a txt in my raw folder with this text:
38.706937,-0.494406,Alcoy,Alcoy,Comunidad Valenciana
37.605651,-0.991294,Vuelo1,Cartagena,Región de Murcia
37.652022,-0.719147,Vuelo2,La Manga del Mar Menor,Región de Murcia
42.817988,-1.644183,Vuelo3,Pamplona,Navarra
36.750779,-5.812395,Vuelo4,Arcos de la frontera,Andalucia
And a method where I do this:
private void leerPuntosApp(){
InputStream stream =getResources().openRawResource(R.raw.sitios);
BufferedReader brin = new BufferedReader(new InputStreamReader(stream));
String todoPartes = null;
try {
while(brin.read() != -1){
todoPartes = brin.readLine();
dibujarPuntos(todoPartes);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void dibujarPuntos(String punto){
Toast.makeText(this, punto, Toast.LENGTH_SHORT).show();
String []separados = punto.split(",");
Dialog dialog = hacerDialogo(separados[0],separados[1],
separados[2],separados[3],separados[4]);
itemOverlay = new CargarItem(puntosMapa,this,dialog);
lat = Double.parseDouble(separados[0])*1E6;
lon = Double.parseDouble(separados[1])*1E6;
GeoPoint point = new GeoPoint(lat.intValue(),lon.intValue());
//GeoPoint point = calcularCoordenadas(listaDeSitios.get(i).getCiudad());
item = new OverlayItem(point,separados[2], null);
itemOverlay.addOverlay(item);
mapOverlays.add(itemOverlay);
mapView.postInvalidate();
}
The strange thing is that the method dibujarPuntos just draw the first point but the toast shows me all the lines.
Thank you for your help.
By doing the read() you are eating the first character of the line... are you sure the Toast was showing the correct data?
See if this helps
try {
while((todoPartes = brin.readLine()) != null){
dibujarPuntos(todoPartes);
}
} catch (IOException e) {
e.printStackTrace();
}
And instead of using Toast for logging, just use Log.d("MYTAG", punto) and then check the LogCat output to see if it's parsing the information correctly.
It's true read() eat my first character for the all the lines except the first. But if I do that you say I have a NumberFormatException in this line
lat = Double.parseDouble(separados[0])*1E6;

Dynamically populating an expandableListView

So All I'm trying to do is create a dynamic expandableListView Currently It works if I just do the groupViews. The problem comes in when I have to populate the children of those groupViews.. I don't know if I'm doing something wrong, or if theres another better way to do it. If anyone knows please let me know. I'm open to anything.
Currently I'm pulling my data off a server and the error I'm getting is java null pointer exception. So I'm thinking it might have something to do with how big I specified my array sizes?
private static String[][] children = new String[7][4];
private static String[] groups = new String[7];
Here is the rest of the code when I try to populate the View.
public void getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
childrenCount = 0;
// check to see if readline equals Location
//Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
temp = my_buffer.readLine();
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[groupCount][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
groupCount++;
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
}
to me it looks like an error in the loop - as you are reading another line without checking is it null
your while loop should look something like this methinks:
// prime read
while (temp != null ){
int childrenCount = 0;
// check to see if readline equals Location
// start a new location
//Log.w("HERasdfsafdsafdsafE", temp);
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
//>>remove following line as that one isn't checked and
//>>you are loosing on a line that is potentialy a child
//temp = my_buffer.readLine();
//>>check do you have first item to add subitems
else if (tempGroupCount>0){
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[tempGroupCount-1][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
//>>next counter is probably not need but can't see if you're using it somewhere else
//groupCount++;
}
I would first replace strings array to some 2d collection for example arraylist2d ( you can google it ) so you could easally add and remove data from list. If you created adapter that extends BaseExpandableListAdapter everything should be handled without any problems.
About NULLPointer, could you paste stacktrace or more info on which line it occurs ?

Dynamically setting imageview in a listview item is slow

I'm having trouble with my listviews items. I'm dynamically getting some images from a XML file, downloading the image and setting it.
I'm trying to primitively cache the bitmap fetched to speed up the getView process of my listviews adapter. But when trying to scroll my listview the phone seems to 'lag'.
This is the part of my code which is responsible for the 'lag':
if( ni.Bitmap == null )
{
Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
Matcher m = p.matcher(ni.Description);
boolean result = m.find();
if( result )
{
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(m.group(1)).getContent());
ni.Bitmap = bitmap;
holder.theimage.setImageBitmap(ni.Bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else
holder.theimage.setImageBitmap(ni.Bitmap);
Can I in anyway speed up this process?
Check this Url. you will get lot thing about this.
https://stackoverflow.com/search?q=lazy+loading+listview+android

Categories

Resources