Parse JSON and set it to TextView - java

In my android application I need to parse JSON. From one website I take this JSON. I want to parse an array 'words' in this JSON and set it to one TextView. I am little bit confused. Can any way show me right way and check my code. Thanks for any help!
JSON:
MainActivity.java
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_location.xml
SupportMapFragment mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
mGoogleMap = mSupportMapFragment.getMap();
// Enabling MyLocation Layer of Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = mLocationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = mLocationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng mLatLng = new LatLng(latitude, longitude);
//Add Marker to current location of devise
//mGoogleMap.addMarker(new MarkerOptions().position(mLatLng).title("Geolocation system").snippet("Your last current location which was available!").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));
// Showing the current location in Google Map
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
// Show Zoom buttons
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
// Turns on 3D buildings
mGoogleMap.setBuildingsEnabled(true);
// Zoom in the Google Map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Convert double to String
String mLatitude = Double.toString(latitude);
String mLongitude = Double.toString(longitude);
// URL of what3words service
String w3w_URL = "http://api.what3words.com/position?key=" + w3w_API_KEY + "&position=" + mLongitude + "," + mLatitude;
String json = null;
try {
json = readUrl(w3w_URL);
} catch (Exception e) {
e.printStackTrace();
}
JSONResponse response = new Gson().fromJson(json, JSONResponse.class);
String[]words = response.getWords();
TextView positionWords = (TextView) findViewById(R.id.location_information);
positionWords.setText(Arrays.toString(words).replaceAll("\\[|\\]", ""));
}
private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
JSONResponse.java:
public class JSONResponse {
private String[] words;
long position;
public String[] getWords() {
return words;
}
public void setWords(String[] words) {
this.words = words;
}
public long getPosition() {
return position;
}
public void setPosition(long position) {
this.position = position;
}
}
Logcat error:
04-05 19:56:33.905 21272-21272/ua.com.what3wordsexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:31)
at ua.com.what3wordsexample.MainActivity$1.success(MainActivity.java:27)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5454)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)

You can use https://code.google.com/p/google-gson/
Use something like that
User user = new Gson().fromJson(userJSON, User.class);
Update:
public class Response {
private String[] words;
private Position position;
private String language;
public String[] getWords() {
return words;
}
public void setWords(String[] words) {
this.words = words;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
Finally:
Response response = new Gson().fromJson(String_response_from_server, Response.class);
String_response_from_server - it's your String response from server, in your code it's
json = mStringBuilder.toString();
After that you can easily get needed information
String[]words = response.getWords()
Update2
private String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Usage:
String json = readUrl("http://api.what3words.com/position?key=YOURAPIKEY&position=" + mLongitude + "," + mLatitude);
Response response = new Gson().fromJson(json, Response.class);
P.S. I can't see what contains your position array so I puted some class Position, if there are the same values like in words you can replase it with String[] position;

Related

null pointer exception in async task [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
when i tried to put direction from source to destination on map
this null pointer exception heppen
when i tried to put direction from source to destination on map
this null pointer exception heppen
l
ocat:
07-05 02:19:21.569 23133-23133/com.example.saad.testapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.saad.testapp, PID: 23133
java.lang.NullPointerException
at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:248)
at com.example.saad.testapp.map$TaskParser.onPostExecute(map.java:205)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
map.class is as follows :
public class map extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
loc ambLoc;
loc patLoc;
String tempE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ambLoc=new loc();
patLoc=new loc();
tempE=new String();
}
#Override
public void onMapReady(GoogleMap googleMap) {
getPoints();
}
void getPoints()
{
//some code here
String url=getRequestUrl(ambLoc,patLoc);
TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
taskRequestDirections.execute(url);
}
private String getRequestUrl(loc origin, loc dest) {
//Value of origin
String str_org = "origin=" + origin.getLatitude() +","+origin.getLongitude();
//Value of destination
String str_dest = "destination=" + dest.getLatitude()+","+dest.getLongitude();
//Set value enable the sensor
String sensor = "sensor=false";
//Mode for find direction
String mode = "mode=driving";
//Build the full param
String param = str_org +"&" + str_dest + "&" +sensor+"&" +mode;
//Output format
String output = "json";
//Create url to request
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param;
return url;
}
private String requestDirection(String reqUrl) throws IOException {
String responseString = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try{
URL url = new URL(reqUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//Get the response result
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
responseString = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
httpURLConnection.disconnect();
}
return responseString;
}
public class TaskRequestDirections extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String responseString = "";
try {
responseString = requestDirection(strings[0]);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Parse json here
TaskParser taskParser = new TaskParser();
taskParser.execute(s);
}
}
having exception on the below line
public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject = null;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionParser directionsParser = new DirectionParser();
routes = directionsParser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
//Get list route and display it into the map
ArrayList points = null;
PolylineOptions polylineOptions = null;
for (List<HashMap<String, String>> path : lists) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
for (HashMap<String, String> point : path) {
double lat = Double.parseDouble(point.get("lat"));
double lon = Double.parseDouble(point.get("lon"));
points.add(new LatLng(lat,lon));
}
polylineOptions.addAll(points);
polylineOptions.width(15);
polylineOptions.color(Color.BLUE);
polylineOptions.geodesic(true);
}
if (polylineOptions!=null) {
Toast.makeText(getApplicationContext(), "adding polyline!", Toast.LENGTH_SHORT).show();
having exception on the
mMap.addPolyline(polylineOptions);
} else {
Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
}
}
}
}
suggest any solution if you have
thank you
thank you
thank you
thank you
You never set mMap variable try like this
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getPoints();
}

get result of AsyncTask in other Method

I am trying to get the response of a servlet as text, to parse this text and extract the coordinates for showing markers on google maps. My problem is that I don't know how to call the result from onPostExecute method in the onMapReady method. Like I'm calling in my code, the input String is obviously empty.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
tvResult = (TextView) findViewById(R.id.tvResult);
textView2 = (TextView) findViewById(R.id.textView2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (checkNetworkConnection())
// perform HTTP GET request
new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}
public boolean checkNetworkConnection() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
boolean isConnected = false;
if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
// show "Connected" & type of network "WIFI or MOBILE"
tvIsConnected.setText("Connected " + networkInfo.getTypeName());
// change background color to red
tvIsConnected.setBackgroundColor(0xFF7CCC26);
} else {
// show "Not Connected"
tvIsConnected.setText("Not Connected");
// change background color to green
tvIsConnected.setBackgroundColor(0xFFFF0000);
}
return isConnected;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line + "\n";
inputStream.close();
return result;
}
private String HttpGet(String myUrl) throws IOException {
InputStream inputStream = null;
String result = "";
URL url = new URL(myUrl);
// create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// make GET request to the given URL
conn.connect();
// receive response as inputStream
inputStream = conn.getInputStream();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
return result;
}
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpGet(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
//onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
tvResult.setText(result);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
String input = tvResult.getText().toString();
String[] lines = input.split( "\n" );
List<Pair<Double, Double>> list = new ArrayList<>();
String ss="i";
for( int i =1; i < lines.length-1; i++ ) {
int firstcomma = lines[i].indexOf(",");
int secondcomma = lines[i].indexOf(",", firstcomma + 1);
int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
list.add(new Pair(lat,longitude));
}
for(int j=1; j<list.size();j++) {
map = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
}
The reason you can't call the result of onPostExecute() in onMapReady() is because they are both running in the background. The only thing that you can really do here is either call getMapAsync() from your onPostExecute(), which will ensure that your onPostExecute() has completed; or, move the functionality of the onMapReady() into the onPostExecute(). You basically have 2 asyncTasks running, so you either need to chain them (which is kind of hacky) or move the logic from onMapReady() to onPostExecute().

Get coordinates from API request before showing on Maps

I developed an app in which i am receiving latitude and longitude through API REST from my server, so what i want is that the api call will be solved before the display of such coordinates on map. Please guide me how to do this.
I've already implemented a solution but it seems to not work.
From the stack trace I've got this message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: pro.rane.myapplication, PID: 1590
java.lang.NullPointerException: Attempt to get length of null array
at pro.rane.myapplication.MapsActivity.onMapReady(MapsActivity.java:160)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:392)
at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I am conscious that this error is caused by the fact that function getCoordinates() doesn't work properly. I've also tried in past to use Volley library but it didn't work in same way. How can I make my API request works ?
Please note that the url is working, if you do your own get request on my server you can see the correct result in your browser.
Here's my code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String LATITUDE = "latitude";
private static final String LONGITUDE = "longitude";
private GoogleMap mMap;
private String info;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Bundle b = getIntent().getExtras();
if (b != null)
info = b.getString("qrCodeInformation");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/*connection to obtain the array of positions*/
private static String[][] getCoordinates(String tran_id) throws JSONException {
String dummy_tran_id = "1";
String richiesta = "http://myurl/getArticleTravel?tran_id=" + dummy_tran_id;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpGet request = new HttpGet(richiesta);
request.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = "";
try {
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("Errore http request",""+e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
Log.i(squish.getMessage(), squish.getMessage());
}
}
JSONArray jObject;
String[][] coordinates;
jObject = new JSONArray(result);
String[] latitude = new String[jObject.length()];
String[] longitude = new String[jObject.length()];
for (int i = 0; i < jObject.length(); i++) {
latitude[i] = jObject.getJSONObject(i).getString(LATITUDE);
longitude[i] = jObject.getJSONObject(i).getString(LONGITUDE);
}
coordinates = new String[latitude.length][longitude.length];
for(int i =0; i < latitude.length;i++){
coordinates[i][0] = latitude[i];
coordinates[i][1] = longitude[i];
}
//String[][] dummy_coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"}};
return coordinates;
//return dummy_coordinates;
}
#Override
public void onMapReady(GoogleMap googleMap) {
String[][] coordinates = {{"45.465454", "9.186515999999983"}, {"41.9027835", "12.496365500000024"},{"40.9027835", "15.496365500000024"}}; //= null;
try {
coordinates = getCoordinates(info);
} catch (JSONException e) {
e.printStackTrace();
}
Integer a;
mMap = googleMap;
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
for (a = 0; a < coordinates.length; a++) {
if(a==0){
numTxt.setText("Go");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title("GO")
.snippet("Start point "+ a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}else {
numTxt.setText(a.toString());
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])))
.title(a.toString())
.snippet("Arrival point " + a.toString())
.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker)))
);
}
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Double.parseDouble(coordinates[a][0]), Double.parseDouble(coordinates[a][1])),5));
}
}
// Convert a view to bitmap
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
}
Extend the AsyncTask class and use doInBackground to handle the work from getCoordinates in a background thread.
public class YourAsyncTask extends AsyncTask<Void, Void, YourReturnType> {
public interface OnFinishListener{
void onFinish(YourReturnType result);
}
private OnFinishListener mListener;
public OnFinishListener setOnFinishListener(#Nullable OnFinishListener l){
mListener = l;
}
#Override
protected YourReturnType doInBackground(Void... params) {
// Replace all "YourReturnType" with the actual type/object you want to return
YourReturnType returnValue;
// Do your work here and build/create your returnValue
return returnValue;
}
// This will get called automatically after doInBackground finishes
#Override
protected void onPostExecute(YourReturnType result) {
// If listener is set
if(mListener != null){
mListener.onFinish(result); // Return the returnValue
}
}
}
In your Activity when you want to get the coordinate values, execute your AsyncTask and set the listener interface;
YourAsyncTask yourTask = new YourAsyncTask();
yourTask.execute();
yourTask.setOnFinishListener(new YourAsyncTask.OnFinishListener(){
#Override
public void onFinish(YourReturnType result){
// Retrieve your returned value from result
// And if mMap is ready, perform map actions
}
});
AsyncTask documentation

Android getInputStream Isn't Working Properly

I'm trying to create a method for getting the altitude of a place from the website:
https://maps.googleapis.com/maps/api/elevation/json?locations=0,0 (where the 0,0 can be replaced with any coordinates).
However, I got a problem when getting the InputStream from the URL connection.
private double altitude(double lat, double longi) {
String elevation = "";
try {
URL alt = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations="+lat+","+longi);
HttpURLConnection altFind = (HttpURLConnection) alt.openConnection();
altFind.setDoInput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(altFind.getInputStream()));
String inputLine;
OUT:
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("elevation")) {
for (int i = 23; ; i++) {
if (inputLine.charAt(i) != ',') {
elevation = elevation + "" + inputLine.charAt(i);
} else {
break OUT;
}
}
}
}
return Double.parseDouble(elevation);
} catch (MalformedURLException e) {}
catch (IOException e) {}
return 0;
}
That is the method and I call it from here:
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
double elev;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
String longlat = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
longlat = longlat.replaceAll(" ", "");
String [] longilati = longlat.split(",");
final double [] coord = new double[2];
coord[0] = Double.parseDouble(longilati[0]);
coord[1] = Double.parseDouble(longilati[1]);
t = (TextView) findViewById(R.id.textView);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
elev = altitude(coord[0], coord[1]);
} else {
Toast.makeText(this, "No connection available", Toast.LENGTH_LONG).show();
}
I've tried following similar questions to no avail.
You should perform Network Connections on Background Thread.
You can use Asynctask class and move altitude method inside doInBackground().
You can read more here:
https://developer.android.com/reference/android/os/AsyncTask.html
EDITED:
I found this class called JSONParser which I think this is what you need, check this out:
https://gist.github.com/dmnugent80/b2e22e5546c4b1c391ee
Copy and paste it into your project.
You can modify your altitude method by calling makeHttpRequest method from JSONParser class and passing all the parameters needed. If you do it right, then the method will return JSON object from the URL. For example:
private static final String URL = "https://maps.googleapis.com/maps/api/elevation/json";
private static final String METHOD = "GET"; // You can use POST either
private double altitude(double lat, double lng) {
double elevation = 0.0;
HashMap<String, String> params = new HashMap<>();
params.put("locations", lat + "," + lng);
// Here you can put another params if needed
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.makeHttpRequest(URL, METHOD, params);
if(jsonObject != null) {
Log.d(TAG, jsonObject.toString()); // Check if data has arrived safely?
try {
JSONArray results = jsonObject.getJSONArray("results");
JSONObject result = results.getJSONObject(0);
elevation = result.getDouble("elevation");
} catch (JSONException e) {
e.printStackTrace();
}
return elevation;
} else {
return -1;
}
}
Call altitude inside doInBackground and see the result.

how to get url with different ids in android (async task)

EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}

Categories