get result of AsyncTask in other Method - java

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().

Related

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 take on selected item from list view to autocomplete textview

I want to show item of list view in autocomplete text view when click on that item in the list view using the following code.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, AdapterView.OnItemClickListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,FindMarker;
Location mLastLocation;
CustomAutoCompleteTextView atvPlaces = null;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
final int PLACES=0;
final int PLACES_DETAILS=1;
LatLng latLng;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (CustomAutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(this);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}else{
return true;
}
}
private String getAutoCompleteUrl(String place){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// place to be be searched
String input = "input="+place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaceDetailsUrl(String ref){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
//Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(1000);
// mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(CurrentMarker != null){
CurrentMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOption);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
// atvPlaces.setAdapter(lv);
// list adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.list_item,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
}
I want to show selected item in autocompleteTextview from listView when click on that item. Please tell me using my source code.
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str);
atvPlaces.dismissDropDown();
}
Pls check this code, I modified.
String mSelectedItem;
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int ClikedPosition, long id) {
//Getting clicked item from list view
mSelectedItem=adapter.getItem(ClikedPosition);
//Setting to auto complete text view
mAutoCompleteTextView.setText(mSelectedItem);
}
});

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

Parse JSON and set it to TextView

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;

Categories