onPostExecute does not properly start activity - android

I am using AsyncTask to run information to and from my online mySQL database. I am then using JSON parsing to add the information from the database as a marker on my MapBox map. Currently when a user uploads a new marker (washroom in the code) it uploads the information to the database, then runs the onPostExecute method and goes back to the MapsActivity.java. MapsActivity.java should reload the map and display the newly added marker but it doesn't; it only displays the markers that where added before adding the new one. If you close and open the app the markers are updated, displaying all the markers including the new one! Any help would be appreciated!
Part of MapsActivity.java
public class MapsActivity extends FragmentActivity {
private MapView mapView;
private MapboxMap map;
private ImageButton locationToggle;
private LocationServices locationServices;
private String json_string;
private JSONObject jsonObject;
private JSONArray jsonArray;
public static String WASHROOMINFO;
public static String CURRENT_LOCATION;
private static final int PERMISSIONS_LOCATION = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, getString(R.string.accessToken));
setContentView(R.layout.activity_maps);
//getting location services
locationServices = com.mapbox.mapboxsdk.location.LocationServices.getLocationServices(MapsActivity.this);
//onClick to go to add washroom activity
findViewById(R.id.addWashroom).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (CURRENT_LOCATION != null) {
Intent intent = new Intent(getBaseContext(), AddWashroom.class);
startActivity(intent);
} else {
Toast.makeText(getBaseContext(),"You Must Turn on User Location Before Adding a Washroom!",Toast.LENGTH_LONG).show();
}
}
});
//washrooms have not been loaded in yet
if (!BackgroundTask.WASHROOMS_LOADED) {
//getting database info
String method = "getWashroom";
BackgroundTask backgroundTask = new BackgroundTask(getBaseContext());
backgroundTask.execute(method);
finish();
}
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
//when map is ready assign mapboxMap variable
map = mapboxMap;
//Washroom loading has been requested and JSON data is ready
if (BackgroundTask.WASHROOMS_LOADED) {
//Getting JSON data from intent
json_string = getIntent().getExtras().getString("json_data");
try {
//new JSON object from JSON data
jsonObject = new JSONObject(json_string);
//gets JSON array from JSON object
jsonArray = jsonObject.getJSONArray("server_response");
//Marker list for buffering markers
List<Marker> markers = new ArrayList<Marker>();
//do this for all markers!
for (int i = 0; i < jsonArray.length(); i++) {
//Single JSON object of single marker
JSONObject JO = jsonArray.getJSONObject(i);
//Dividing location field into lat & lng
String latlng = JO.getString("location");
String[] latlngSplit = latlng.split(" , ",2);
double lat = Double.valueOf(latlngSplit[0]);
double lng = Double.valueOf(latlngSplit[1]);
//adding marker
Marker marker = map.addMarker(new MarkerOptions()
.title(JO.getString("name"))
.setSnippet(JO.getString("price"))
.position(new LatLng(lat,lng))
);
//add marker to markers list.
markers.add(marker);
}
BackgroundTask.WASHROOMS_LOADED = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
locationToggle = (ImageButton) findViewById(R.id.location_toggle);
locationToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (map != null) {
//toggle GPS when clicking show location button
toggleGps(!map.isMyLocationEnabled());
}
}
});
}
BackgroundTask (AsyncTask)
class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
public static boolean WASHROOMS_LOADED;
private String JSON_STRING;
private String json_string;
BackgroundTask(Context ctx) {
this.ctx = ctx.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String add_url = "http://appart-software.com/add_washroom.php";
String get_url = "http://appart-software.com/get_washroom.php";
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("addWashroom")) {
String location = params[1];
String name = params[2];
String price = params[3];
try {
URL url = new URL(add_url);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
OutputStream outputStream = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string = URLEncoder.encode("WClocation","UTF-8")+"="+URLEncoder.encode(location,"UTF-8")+"&"+
URLEncoder.encode("WCname","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("WCprice","UTF-8")+"="+URLEncoder.encode(price,"UTF-8");
bufferedWriter.write(data_string);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
inputStream.close();
httpUrlConnection.disconnect();
return "Washroom Added!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//You want to get washroom info
} else if (method.equals("getWashroom")){
try {
URL url = new URL(get_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null) {
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//Return JSON formatted info
return stringBuilder.toString().trim();
} catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("Washroom Added!")) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
WASHROOMS_LOADED = false;
} else {
//setting result as a movable string
json_string = result;
//intent and sending JSON data
Intent intent = new Intent(ctx,MapsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("json_data",json_string);
ctx.startActivity(intent);
WASHROOMS_LOADED = true;
}
}
}
If you need anymore of my code, I would be happy to show some more.

You are getting new marker on reopening the app because you are getting database info in your onCreate() method which is triggered only on start of activity. Try getting database info either when location changes or try overriding onNewIntent method. To override onNewIntent first set launchmode of your activity to singleTop in manifest.

Related

Google android map app crashes while getting latitude and longitude from the database

I need to show a bus location on the map, I have latitude and longitude saved in my database. To retrieve the Latitude and Longitude i am using AsynTask. But i think there is some problem with my code, app crashes if call AsyncTask in onMapReady. I checked without calling AsyncTask giving manual latitude and longitude, it works fine. Please help me fix the issue.
This is my code:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
GetLocation getLocation = new GetLocation(getApplicationContext());
getLocation.execute();
}
public class GetLocation extends AsyncTask<String,Void,String> {
Context context;
GetLocation(Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
String login_url = "https://www.mywebsite.com/android/getlonglatt.php";
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result="";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
JSONObject jsonObject = new JSONObject(result);
String latitudedb = (String) jsonObject.get("latitude");
String longitudedb = (String) jsonObject.get("longitude");
String busnum = (String) jsonObject.get("busnum");
Double newlatt = Double.valueOf(latitudedb);
Double newlong = Double.valueOf(longitudedb);
LatLng location = new LatLng(newlatt, newlong);
MarkerOptions options = new MarkerOptions().position(location).title(busnum);
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,19.2f));
bufferedReader.close();
httpURLConnection.disconnect();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onProgressUpdate(Void... values) {
}
}

Return LatLng object from nested asynctask

I have spent days on this, but I can't find a solution to my problem:
I'm developing an app that retrieves a list of theaters showing some movie selected by the user, parsing an HTML page in an AsyncTask.
I want to visualize those theaters on a Map with markers, so I need coordinates: once the "GetCinemaList" AsyncTask is completed, I try to populate my markerList in onPostExecute.
I have an SQLite db in which I store [theater|city|lat|lng]. So I first look up in the db, if it is not found I want call another AsyncTask to retrieve coordinates from HTTP google geocoding ('cause device geocoder returns null, causing the app to crash)
The problem is I am not able to return the LatLng point to the first AsyncTask...
I have tried to use listeners and to override processFinish(LatLng p), but I can't assign the value to my variable cause, accessing it from inner class it should be final.
Any help/idea? Thanks!
Here my code (containing error) for the AsyncTasks , in my Activity.
private class GetCinemaList extends AsyncTask<URL, Void, List<String>> {
private Context mContext;
public GetCinemaList(Context c){
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
List<String> cinemas = new ArrayList<>();
Document docHTML = null;
try {
docHTML = QueryUtils.makeRequest(urls[0]);
cinemas = QueryUtils.extractCinemasFromHTML(mTitile, docHTML);
} catch (IOException e) {
Log.e("JSwa", "Problem making request for parsing HTML "+e);
}
return cinemas;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
cinemaList = result;
LatLng point;
pointList = new ArrayList<>();
for (String elem : cinemaList) {
String name = elem.split("\t")[0];
String orari = elem.split("\t")[1];
Cursor cursor = queryDB(mCinemaDbR, city, name);
if (!cursor.moveToFirst()) {
// call geocoding service
new LatLongFromService(name.concat(" " + city), new AsyncResponse() {
#Override
public void processFinish(LatLng output) {
point = output;
}
}).execute();
Log.d("JSwa", "Inserting point "+point.toString());
// insert new value in the database
long id = addCimena(mCinemaDbW, name, city, String.valueOf(point.latitude), String.valueOf(point.longitude));
// insert new value in the list
MarkerOptions marker = new MarkerOptions().position(point).title(name).snippet(orari);
pointList.add(marker);
}
else{
double lat = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LAT)));
double lng = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LNG)));
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat,lng)).title(name)
.snippet(orari);
pointList.add(marker);
}
cursor.close();
}
for (MarkerOptions marker : pointList){
m_map.addMarker(marker);
}
}
}
// Sometimes happens that device gives location = null
public class LatLongFromService extends AsyncTask<Void, Void, StringBuilder> {
String place;
public AsyncResponse delegate = null;
public LatLongFromService(String place, AsyncResponse resp) {
this.place = place;
delegate = resp;
}
#Override
protected StringBuilder doInBackground(Void... params) {
try {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + this.place + "&sensor=false";
URL url = new URL(googleMapUrl);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(
conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
return jsonResults;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
try {
JSONObject jsonObj = new JSONObject(result.toString());
JSONArray resultJsonArray = jsonObj.getJSONArray("results");
JSONObject location = resultJsonArray
.getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
String lat_helper = location.getString("lat");
double lat = Double.valueOf(lat_helper);
String lng_helper = location.getString("lng");
double lng = Double.valueOf(lng_helper);
delegate.processFinish(new LatLng(lat, lng));
} catch (JSONException e) {
e.printStackTrace();
}
}
}`

Populating a map with markers from a server

I'm populating a Google map with markers, I don't get errors and my variables are getting their values but it isnt populating any markers. It just show one marker and it is my current location.
here is the code that i call when populating:
private void showData() {
int count = users.length();
for(;i<=count;i++) {
try {
JSONObject jsonObject = users.getJSONObject(i);
maplat = Double.parseDouble(jsonObject.getString(lat));
maplng = Double.parseDouble(jsonObject.getString(lng));
MarkerOptions marker = new MarkerOptions().position(new LatLng(maplat, maplng)).title("Hello Maps");
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
googleMap.addMarker(marker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My whole code:
public class MapActivity extends AppCompatActivity{
private GoogleMap googleMap;
double curLat;
double curLng;
double maplat;
double maplng;
private static final String JSON_ARRAY = "result";
private static final String lat= "lat";
private static final String lng = "lng";
private JSONArray users = null;
private String q;
private static final String GET_URL = "http://testevent.site88.net/getlocation.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
GPSTracker gps = new GPSTracker(this);
curLat = gps.getLatitude();
curLng = gps.getLongitude();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(q);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showData() {
int count = users.length();
for(int i = 0;i<=count;i++) {
try {
JSONObject jsonObject = users.getJSONObject(i);
maplat = Double.parseDouble(jsonObject.getString(lat));
maplng = Double.parseDouble(jsonObject.getString(lng));
MarkerOptions marker = new MarkerOptions().position(new LatLng(maplat, maplng)).title("Hello Maps");
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
googleMap.addMarker(marker);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MapActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
q=s;
extractJSON();
showData();
MarkerOptions marker = new MarkerOptions().position(new LatLng(curLat, curLng)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
// adding marker
googleMap.addMarker(marker);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
getJSON(GET_URL);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}

How to convert the URL path into image and showing on the list view

Based on the location i am trying to search the stores and search result is showing on the list view of the cell . I am getting the name,address,related Icons and rating from the Google but the problem is to how to show the Image on the list view of the list cell.I got the URL path of the Image.I also convert the URL path into bitmapImages using Bitmap getBitmapFromURL().But it is showing the NPE(Null POinter Exception). Below i am going to paste the code.
public class NearByActivity extends Activity implements LocationListener
{
// private ListAdapter adapter;
ListView lvPlaces;
ImageView ivPhone,ivCamera,ivPrinter,ivMore;
String name,vicinity,formatted_phone_number,rating,icon;
double mLatitude=0;
double mLongitude=0;
SharedPreferences spref;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// CustomListAdapter customListAdapter;
public ImageLoader imageLoader;
private static final String Name = "name";
private static final String Vicinity = "vicinity";
private static final String Rating="rating";
private static final String Icon="icon";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby);
lvPlaces=(ListView)findViewById(R.id.lvPlaces);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
lvPlaces.setAdapter(adapter);
lvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> MainActivity, final View view,int position, long id)
{
final TextView tvVicinity=(TextView)view.findViewById(R.id.tvVicinity);
final TextView tvRating=(TextView)view.findViewById(R.id.tvRating);
final TextView tvName=(TextView)view.findViewById(R.id.tvName);
final ImageView ivPhone = (ImageView)findViewById(R.id.ivPhone);
final ImageView ivCamera = (ImageView)findViewById(R.id.ivCamera);
final ImageView ivPrinter = (ImageView)findViewById(R.id.ivPrinter);
final ImageView ivMore = (ImageView)findViewById(R.id.ivMore);
ivPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getApplication(),"Do you want the call",Toast.LENGTH_SHORT).show();
}
});
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getApplication(),"Do you want to take pics",Toast.LENGTH_SHORT).show();
}
});
ivPrinter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getApplication(),"Do you want to print",Toast.LENGTH_SHORT).show();
}
});
ivMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getApplication(),"Do you want more",Toast.LENGTH_SHORT).show();
}
});
tvName.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String getName=tvName.getText().toString();
String getVicinity=tvVicinity.getText().toString();
String getRating=tvRating.getText().toString();
Intent i = new Intent(getApplication(),Information.class);
i.putExtra(Name,getName);
i.putExtra(Vicinity,getVicinity);
i.putExtra(Rating,getRating);
startActivity(i);
}
});
}
});
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null)
{
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider,20000,0,this);
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=1000");
sb.append("&types=beauty_salon");
sb.append("&sensor=true");
sb.append("&key=AIzaSyBgtVo5lfnDQFY8W44TfMevgg2klgj5WeA");
// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
/** 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 sb1 = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null)
{
sb1.append(line);
}
data = sb1.toString();
br.close();
}
catch(Exception e)
{
Log.d("Exception while downloading url", e.toString());
}
finally
{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onLocationChanged(Location location)
{
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
public Bitmap getBitmapFromURL(String icon ) {
try {
URL url = new URL(icon);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
#Override
protected String doInBackground(String... url)
{
try
{
data = downloadUrl(url[0]);
}
catch(Exception e)
{
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result)
{
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>
{
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData)
{
JSONObject jObject;
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try
{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}
catch(Exception e)
{
Log.d("Exception",e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String,String>> list)
{
for(int i=0;i<list.size();i++)
{
HashMap<String, String> hmPlace = list.get(i);
name = hmPlace.get("place_name");
vicinity = hmPlace.get("vicinity");
rating=hmPlace.get("rating");
formatted_phone_number = hmPlace.get("phone_number");
icon = hmPlace.get("icon");
placesListItems.add(hmPlace);
}
Toast.makeText(getApplication(),""+icon,Toast.LENGTH_SHORT).show();
ImageView ivPics = (ImageView)findViewById(R.id.ivPics);
ivPics.setImageBitmap(getBitmapFromURL(icon));
ListAdapter adapter=new SimpleAdapter(NearByActivity.this,placesListItems,
R.layout.myplace,
new String[]{"place_name","vicinity","rating","phone_number"},
new int[]{R.id.tvName,R.id.tvVicinity,R.id.tvRating,R.id.ivPhone});
lvPlaces.setAdapter(adapter);
}
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at info.androidhive.slidingmenu.Activities.NearByActivity$ParserTask.onPostExecute(NearByActivity.java:328)
at info.androidhive.slidingmenu.Activities.NearByActivity$ParserTask.onPostExecute(NearByActivity.java:289)
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:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
try this
URL url = new URL("http://abcd.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Did you add INTERNET permission to your manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
update 1:
Also, are you sure that icon = hmPlace.get("icon"); is not null.
PS ivPics looks fishy to me.
update 2:
The problem I guess is the ivPics, I think it's null.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference

How to make a phone call from a marker on the map

I have some markers in a map that represent libraries (taken from a JSON files).
Now I would like to give the user the possibility to make a phone call/send emails/visit website to these libraries from the marker, can someone help me?
// Setting OnClickEvent listener for the GoogleMap
map.setOnMapClickListener(new OnMapClickListener() {
public void onMapClick(LatLng latlng, String nome, String indirizzo, String tel, String fax, String url, String email) {
addMarkerBiblio(latlng, nome, indirizzo, tel, fax, url, email);
}
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
}
});
// Starting locations retrieve task
new RetrieveTask().execute();
}
//MARKER DELLE BIBLIO
// Adding marker on the GoogleMaps
private void addMarkerBiblio(LatLng latlng, String nome, String indirizzo, String tel, String fax, String url, String email) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.snippet(indirizzo);
markerOptions.title(nome);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_biblio));
boolean visible = false;
markerOptions.visible(visible);
Marker biblioM = map.addMarker(markerOptions);
biblioMarker.add(biblioM);
}
// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String strUrl = "http://hyperion.sal.disco.unimib.it:8080/RESTfulProject/REST/biblio";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
String nome = marker.get("nome");
String indirizzo = marker.get("indirizzo");
String tel = marker.get("tel");
String fax = marker.get("fax");
String url = marker.get("url");
String email = marker.get("email");
addMarkerBiblio(latlng,nome,indirizzo,tel,fax,url,email);
}
}
}
You could use
OnInfoWindowClickListener
to be able to catch the "click" on the info window of each marker you created.
Then you can use "onInfoWindowClick" to open another activity via Intent eg Webview
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(MainActivity.this,Web.class);
Log.d(TAG, "URL: " + marker.getSnippet());
intent.putExtra("url", marker.getSnippet());
startActivity(intent);
}
For Phone call you use the call Intent
Intent intent = new Intent(Intent.ACTION_DIAL);
If you have several options to choose, i would use a dialog here and then open the Intent with the dialog result

Categories

Resources