How to wait until onPostExecute finishes - android

So I am new to programming, what I'm trying to do is to make an android app that will give to the client the nearest and fastest way to go the cinema/gas station/market. The problem with that is that first I need to find the nearest places via google api get the lats and lngs and then use them to direction api.
So what I have done is this:
GetNearbyPlaces.java
public class GetNearbyPlaces extends AsyncTask<Object, String, String>
{
private String googleplaceData, url;
private GoogleMap mMap;
#Override
protected String doInBackground(Object... objects)
{
mMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try
{
googleplaceData = downloadUrl.ReadTheURL(url);
}
catch (IOException e)
{
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s)
{
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
super.onPostExecute(s);
Log.d("Message","telos execute ");
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList)
{
for (int i=0; i<nearbyPlacesList.size();
{
Log.d("Message","mesa stin for ");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
String nameOfPlace = googleNearbyPlace.get("place_name");
String vicinity = googleNearbyPlace.get("vicinity");
double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(nameOfPlace + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
}
}
GoogleUserMaps.java
case R.id.gasstation_nearby:
mMap.clear();
mMap.addMarker(userLocMarkerOptions);
mMap.setTrafficEnabled(true);
url = getUrl(latitude,longitude,gasStation);
transferData[0] = mMap;
transferData[1] = url;
Log.d("Message","Prin kanei execute ");
getNearbyPlaces.execute(transferData);
Log.d("Message","afou kanei execute ");
Toast.makeText(this, "Searching for Nearby Gas Stations.", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Showing for Nearby Gas Stations.", Toast.LENGTH_SHORT).show();
break;
I want to add something inside DisplayNearbyPlaces a public variable in order to get the lats and lngs but when I use it after the getNearbyPlaces.execute(transferData).get(); of GoogleUserMaps.java it gives me 0 result. I can't understand AsyncTask. Is there any way that I can wait until
getNearbyPlaces.execute(transferData).get(); finishes the execute in order to get the lats and lngs ?
Thank you in advance !
my logcat
I want to get the result after the execute finishes as I show you in the image bellow

Async task runs in a seperate thread than UI thread. It would be better if you try to use a Callback interface and when onPost of Async task is called perform the action in that callback

#Strack I am posting code example of interface
`
public interface PlaceListener{
void searchStarted();
void searchEnded();
}
public class GetNearbyPlaces extends AsyncTask<Object, String, String>
{
private String googleplaceData, url;
private GoogleMap mMap;
private PlaceListener placeListener;
public GetNearbyPlaces(PlaceListener placeListener){
this.placeListner = placeListener;
}
//onPreExecute(){ placeListner.searchStarted();}
#Override
protected String doInBackground(Object... objects)
{
mMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try
{
googleplaceData = downloadUrl.ReadTheURL(url);
}
catch (IOException e)
{
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s)
{
placeListner.serachEnded();
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
super.onPostExecute(s);
Log.d("Message","telos execute ");
}
}
`
Implement the PlaceListener in Caller Activity and perform your desired task in searchEnded. You can make the parameters of your interface methods according to your desired data you want to pass

ok. create a new call back:
public interface MyCallBack {
void myTaskDone(List<HashMap<String, String>> nearbyPlacesList);
}
create one in your activity:
MyCallBack myCallBack = new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
};
send a reference to the Aynctask:
getNearbyPlaces.execute(transferData, map, new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
});
complete code:
public interface MyCallBack {
void myTaskDone(List<HashMap<String, String>> nearbyPlacesList);
}
public class GetNearbyPlaces extends AsyncTask<Object, String, String> {
private String googleplaceData;
private String url;
private GoogleMap mMap;
private MyCallBack myCallBack;
public GetNearbyPlaces(String url, GoogleMap mMap, MyCallBack myCallBack) {
this.url = url;
this.mMap = mMap;
this.myCallBack = myCallBack;
}
#Override
protected String doInBackground(Object... objects) {
DownloadUrl downloadUrl = new DownloadUrl();
try {
googleplaceData = downloadUrl.ReadTheURL(url);
} catch (IOException e) {
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s) {
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
myCallBack.myTaskDone(nearbyPlacesList);
}
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
/// your code
}
MyCallBack myCallBack = new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
};
How to call it:
//.....
transferData[0] = mMap;
transferData[1] = url;
Log.d("Message","Prin kanei execute ");
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces(transferData, map, myCallBack);
getNearbyPlaces.execute();
//or:
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces(transferData, map, new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
});
getNearbyPlaces.execute();

Related

Fetch data using volley and display in Google Maps

This is my first time working with Google Maps in android. I was able to create a map displaying one marker. That was a good start for me. However, I would like to display multiple markers. To do these, I am fetching the locations from the database using volley. However, I am experiencing one problem, one that I have experienced before but I managed to have a work around then and now it has surfaced again in my current project i.e I like using Singletons in my application to store data as long as the application is in memory. My singleton for instance could hold an array list of objects and I can get the array list anywhere and any time in any activity/fragment. However, I need to populate the arraylist in my singleton before activity/fragment becomes active and access the arraylist of objects in onCreate/onCreateView but it seems the activity/fragment loads very fast and a reference to the arraylist of objects from the singleton is always null. In my current project:
This is the singleton class that handles all the locations
public class PointOfInterestLab {
private ArrayList<PointOfInterest> mPointOfInterests;
private static PointOfInterestLab sPointOfInterestLab;
private Context mAppContext;
private PointOfInterestLab(Context appContext){
mAppContext = appContext;
mPointOfInterests = new ArrayList<PointOfInterest>();
}
public static PointOfInterestLab get(Context c){
if(sPointOfInterestLab == null){
sPointOfInterestLab = new PointOfInterestLab(c.getApplicationContext());
}
return sPointOfInterestLab;
}
public ArrayList<PointOfInterest> getPointOfInterests(){
return mPointOfInterests;
}
public PointOfInterest getPointOfInterest(int id){
for(PointOfInterest pointOfInterest: mPointOfInterests){
if(pointOfInterest.getID() == id){
return pointOfInterest;
}
}
return null;
}
public void addPointOfInterest(PointOfInterest pointOfInterest){
mPointOfInterests.add(pointOfInterest);
}
public void clearPointOfInterests(){
mPointOfInterests.clear();
}
public void deletePointOfInterest(PointOfInterest pointOfInterest){
mPointOfInterests.remove(pointOfInterest);
}
}
In the fragment that I want to display the locations:
public class PointOfInterestMapFragment extends Fragment implements OnMapReadyCallback {
private static final String TAG = PointOfInterestMapFragment.class.getSimpleName();
private GoogleMap mGoogleMap;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//get locations from server
getPOISFromDB();
}//end method onCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle saveInstanceState){
View v = inflater.inflate(R.layout.fragment_poi_map, parent, false);
//obtain the support fragment and get notified when the map is ready
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager()
.findFragmentById(R.id.map);
//pass fragment in getMapAsync handler
mapFragment.getMapAsync(this);
return v;
}//end method onCreateView
#Override
public void onMapReady(GoogleMap googleMap){
mGoogleMap = googleMap;
ArrayList<PointOfInterest> pointOfInterests;
pointOfInterests = PointOfInterestLab.get(getActivity())
.getPointOfInterests();
for(PointOfInterest pointOfInterest : pointOfInterests){
//add marker and move camera
/*LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude()
, pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title(pointOfInterest.getName()));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));*/
Log.d(TAG, pointOfInterest.getName());
}
/*This is just for debugging, it is returning a null object
Meaning by the time the array list of the singleton class
is being populated this has been called I guess*/
PointOfInterest pointOfInterest = PointOfInterestLab.get(getActivity()).getPointOfInterest(3);
LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title("location"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
}
//Get locations from db
private void getPOISFromDB(){
// Tag used to cancel the request
String tag_string_req = "req_poi_list";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_POI_LIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(getActivity()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(getActivity()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity());
User user = sqLiteHandler.getUserDetails();
params.put("user_id", user.getUserID());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}//end method getPOISFromDB
}//end class
This is the part of the code that I am using to test for now. I am getting error PointOfInterest.getLocation()' on a null object reference on line LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
/*This is just for debugging, it is returning a null object
Meaning by the time the array list of the singleton class
is being populated this has been called I guess*/
PointOfInterest pointOfInterest = PointOfInterestLab.get(getActivity()).getPointOfInterest(3);
LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title("location"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
I have also tried calling the database api in the onCreate method of the hosting activity but doesn't seem to work
public class MainActivity extends AppCompatActivity {
......
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedometer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
User user = new User();
user.checkLogin(MainActivity.this);
tabLayout = (TabLayout)findViewById(R.id.tabs);
viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(2);
//runnable to get rid of bug
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
setTitle("Updates");
//get locations from db
getPOISFromDB();
}//end method onCreate
private class MyAdapter extends FragmentStatePagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 :
return new FirstFragment();
case 1 :
eturn new SecondFragment();
case 2 :
return new PointOfInterestMapFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return getResources().getString(R.string.fragment_1);
case 1 :
return getResources().getString(R.string.fragment_2);
case 2 :
return getResources().getString(R.string.fragment_3);
}
return null;
}
}//end class MyAdapter
private void getPOISFromDB(){
// Tag used to cancel the request
String tag_string_req = "req_poi_list";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_POI_LIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(AppController.getInstance()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(AppController.getInstance()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SQLiteHandler sqLiteHandler = new SQLiteHandler(AppController.getInstance());
User user = sqLiteHandler.getUserDetails();
params.put("user_id", user.getUserID());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}//end method getPOISFromDB
}
How do I display the markers in onMapReady method i.e populate the singleton before the onMapReady method executes?
Thanks to #soham, I changed to initialize my adapter after the response from the api. Removed this line of code in onCreate in the MainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
......
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
.......
}
Placed it in method getPOISFromDB()
......
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(AppController.getInstance()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(AppController.getInstance()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
}
.....

How to get Arraylist<HashMap<String, String>> from AsyncTask through onPostExecute

I am trying to put storelist into StoreList variable. But it is not working.
doInBackground method is working perfectly but onPostexecute is not working.
Here is my code,
public class guest_main extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Location mCurrentLocation, mDestination;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String currentLon, currentLat;
private ListView mListView = null;
private ListViewAdapter mAdapter = null;
public ArrayList<HashMap<String, String>> StoreList;
class BackgroundWorker3 extends AsyncTask<String, Void,ArrayList<HashMap<String, String>>> {
Context context;
AlertDialog alertDialog;
BackgroundWorker3(Context ctx) {
context = ctx;
}
JSONArray store = null;
ArrayList<HashMap<String, String>> storeList;
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
String type = params[0];
storeList = new ArrayList<HashMap<String, String>>();
if (type.equals("Select2")) {
try {
String link = "...";
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String json;
while ((json = reader.readLine()) != null) {
sb.append(json);
}
String s = sb.toString().trim();
JSONObject jsonObject = new JSONObject(s);
store = jsonObject.getJSONArray("result");
for (int i = 0; i < store.length(); i++) {
JSONObject c = store.getJSONObject(i);
String name = c.getString("name");
String tel = c.getString("tel");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
HashMap<String, String> stores = new HashMap<String, String>();
stores.put("name", name);
stores.put("tel", tel);
stores.put("latitude", latitude);
stores.put("longitude", longitude);
storeList.add(stores);
}
return storeList;
} catch (Exception e) {
return null;
}
}
return storeList;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guest_main, container, false);
StoreList = new ArrayList<HashMap<String, String>>();
getData();
buildGoogleApiClient();
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(this);
return v;
}
public void getData(){
BackgroundWorker3 bk2 = new BackgroundWorker3(getActivity());
bk2.execute("Select2");
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent = new Intent(getActivity().getApplicationContext(), gmenu_list.class);
startActivity(intent);
}
}
private class ViewHolder {
public ImageView mIcon;
public TextView mText;
public TextView mDate;
public TextView mDistance;
}
private class ListViewAdapter extends BaseAdapter {
private Context mContext = null;
private ArrayList<g_ListData> mListData = new ArrayList<g_ListData>();
public ListViewAdapter(Context mContext) {
super();
this.mContext = mContext;
}
#Override
public int getCount() {
return mListData.size();
}
#Override
public Object getItem(int position) {
return mListData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addItem(Drawable icon, String mTitle, String mDate, String mDistance){
g_ListData addInfo = null;
addInfo = new g_ListData();
addInfo.mIcon = icon;
addInfo.mTitle = mTitle;
addInfo.mDate = mDate;
addInfo.mDistance = mDistance;
mListData.add(addInfo);
}
public void remove(int position){
mListData.remove(position);
dataChange();
}
public void sort(){
Collections.sort(mListData, g_ListData.ALPHA_COMPARATOR);
dataChange();
}
public void dataChange(){
mAdapter.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.gmenu_list_item, null);
holder.mIcon = (ImageView) convertView.findViewById(R.id.mImage);
holder.mText = (TextView) convertView.findViewById(R.id.mText);
holder.mDate = (TextView) convertView.findViewById(R.id.mDate);
holder.mDistance = (TextView)convertView.findViewById(R.id.mDistance);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
g_ListData mData = mListData.get(position);
if (mData.mIcon != null) {
holder.mIcon.setVisibility(View.VISIBLE);
holder.mIcon.setImageDrawable(mData.mIcon);
}else{
holder.mIcon.setVisibility(View.GONE);
}
holder.mText.setText(mData.mTitle);
holder.mDate.setText(mData.mDate);
holder.mDate.setText(mData.mDistance);
return convertView;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100000); // Update location every second
try{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);}catch (SecurityException e){
}
if (mCurrentLocation != null) {
currentLat = String.valueOf(mCurrentLocation.getLatitude());
currentLon = String.valueOf(mCurrentLocation.getLongitude());
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
currentLat = String.valueOf(location.getLatitude());
currentLon = String.valueOf(location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}
Ok..The problem is in your case that the Async task runs on separate thread from UI thread So when you call BackgroundWorker3 in getData method then UI thread doesn't wait for Async task response(separte thread) and StoreList have null value. So you see StoreList doesn't have any value and in listView nothing will show.
Write this code in onPostExecute method not in onCreate..
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
}
Hope this will help you.

Android Cluster manager icon depending on type

I'm working on a small app and have implemented Google Maps and Places api. Currently i'm able to see all my markers on the map and clustering working fine. I'm able to zoom in the clusters open up and able to see the markers. I have a spinner that has different types and once selected that type is passed to the places search string.
This is my maps code that includes the clustering:
public class MapsActivity extends FragmentActivity implements LocationListener,ClusterManager.OnClusterItemInfoWindowClickListener<MyItem> {
GoogleMap mMap;
double myLatitude = 0;
double myLongitude = 0;
HashMap<String, String> mMarker = new HashMap<String, String>();
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
private ClusterManager<MyItem> mClusterManager;
protected MyItem clickedClusterItem;
String[] placeType;
String[] placeTypeName;
Spinner spinPlaceType;
#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);
mMap = mapFragment.getMap();
onMapReady();
// Array of place types
placeType = getResources().getStringArray(R.array.placeType);
// Array of place type names
placeTypeName = getResources().getStringArray(R.array.placeTypeName);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.spinner_item, R.id.textview, placeTypeName);
// Getting reference to the Spinner
spinPlaceType = (Spinner) findViewById(R.id.spinPlaceType);
// Setting adapter on Spinner to set place types
spinPlaceType.setAdapter(adapter);
spinPlaceType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int selectedPosition = spinPlaceType.getSelectedItemPosition();
final String type = placeType[selectedPosition];
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + myLatitude + "," + myLongitude);
sb.append("&type=" + type);
sb.append("&radius=4000");
sb.append("&key=PLACES_KEY");
// Creating a new non-ui thread task to download Google place json
// data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + myLatitude + "," + myLongitude);
sb.append("&type=restaurant");
sb.append("&radius=4000");
sb.append("&key=PLACES_KEY");
// Creating a new non-ui thread task to download Google place json
// data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
// Will display next 20 places returned form the next_page_token
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_more);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Finding you some more places.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("pagetoken=" + placeJsonParser.getNext_Page_token());
sb.append("&key=PLACES_KEY");
// Creating a new non-ui thread task to download Google place json
// data
if (placeJsonParser.getNext_Page_token() == null || placeJsonParser.getNext_Page_token() == ""){
Snackbar.make(view, "No more places left to find.", Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent detailsIntent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarker.get(marker.getId());
marker.getPosition();
detailsIntent.putExtra("reference", reference);
detailsIntent.putExtra("markerLat", myLatitude);
detailsIntent.putExtra("markerLong", myLongitude);
startActivity(detailsIntent);
}
});
}
public void onMapReady(){
// Enabling MyLocation in Google Map
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
// Getting LocationManager object from System Service
// LOCATION_SERVICE
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);
// onLocationChanged(location);
if (location != null) {
onLocationChanged(location);
}
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String referer ="";
StringBuilder jsonResults = new StringBuilder();
HttpURLConnection conn = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
conn = (HttpURLConnection) url.openConnection();
if (referer != null) {
conn.setRequestProperty("Referer", referer);
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
// Displays the list of places found in the terminal.
Log.i("Data", "Places Found: " + jsonResults);
} catch (MalformedURLException e) {
Log.i("Google Places Utility", "Error processing Places API URL");
return null;
} catch (IOException e) {
Log.i("Google Places Utility", "Error connecting to Places API");
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return jsonResults.toString();
}
/**
* A class, to download Google Places
*/
private class PlacesTask extends AsyncTask<String, Integer, String> {
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#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);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
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;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
// Clears all the existing markers
mMap.clear();
setUpClusterer(list);
}
}
private void setUpClusterer(List<HashMap<String, String>> list) {
// Position the map.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(myLatitude,myLongitude), 13));
// Initialize the manager with the context and the map.
// (Activity extends context, so we can pass 'this' in the constructor.)
mClusterManager = new ClusterManager<MyItem>(this, mMap);
// Point the map's listeners at the listeners implemented by the cluster
// manager.
mMap.setOnCameraChangeListener(mClusterManager);
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
mMap.setOnInfoWindowClickListener(mClusterManager);
mClusterManager.setOnClusterItemInfoWindowClickListener(this);
mClusterManager
.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
#Override
public boolean onClusterItemClick(MyItem item) {
clickedClusterItem = item;
return false;
}
});
// Add cluster items (markers) to the cluster manager.
addItems(list);
mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(
new MyCustomAdapterForItems());
}
public class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter {
private final View myContentsView;
MyCustomAdapterForItems() {
myContentsView = getLayoutInflater().inflate(
R.layout.info_window, null);
}
#Override
public View getInfoWindow(Marker marker) {
TextView tvTitle = ((TextView) myContentsView
.findViewById(R.id.txtTitle));
TextView tvSnippet = ((TextView) myContentsView
.findViewById(R.id.txtSnippet));
tvTitle.setText(clickedClusterItem.getTitle());
tvSnippet.setText(clickedClusterItem.getSnippet());
return myContentsView;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
}
private void addItems(List<HashMap<String, String>> list) {
double latitude;
double longitude;
for (int i = 0; i < list.size(); i++) {
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
latitude = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
longitude = Double.parseDouble(hmPlace.get("lng"));
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
MyItem offsetItem = new MyItem(latitude, longitude, hmPlace.get("reference"), name, vicinity);
mClusterManager.addItem(offsetItem);
}
}
public void onClusterItemInfoWindowClick(MyItem item) {
Intent placesIntent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = item.getReference();
placesIntent.putExtra("name", item.getTitle());
placesIntent.putExtra("reference", reference);
placesIntent.putExtra("sourcelat", myLatitude);
placesIntent.putExtra("sourcelng", myLongitude);
startActivity(placesIntent);
}
#Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
LatLng myLocation = new LatLng(myLatitude, myLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
my myItem class to get info for the markers:
package com.example.tariq.outandabout;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterItem;
public class MyItem implements ClusterItem {
LatLng mPosition;
private String reference,placeTitle,snippet;
public MyItem(double lat, double lng,String val,String title, String snip) {
mPosition = new LatLng(lat, lng);
reference=val;
placeTitle=title;
snippet = snip;
}
#Override
public LatLng getPosition() {
// TODO Auto-generated method stub
return mPosition;
}
public String getReference() {
// TODO Auto-generated method stub
return reference;
}
public String getTitle() {
// TODO Auto-generated method stub
return placeTitle;
}
public String getSnippet() {
// TODO Auto-generated method stub
return snippet;
}
}
Currently only red markers are getting displayed but I was wondering if there is a way to have a different markers depending on the type selected from the spinner, For example if I select Hospital then the markers are shown as little hospital icons, if I select ATM, then a little ATM icon appears.
Any help will be appreciated.
Firstly you have to store all the info you need (at this situation just LatLng and marker icon) insite ClusterItem object.
public class MarkerItem implements ClusterItem {
private String title;
private String snippet;
private LatLng latLng;
private BitmapDescriptor icon;
public MarkerItem(MarkerOptions markerOptions) {
this.latLng = markerOptions.getPosition();
this.title = markerOptions.getTitle();
this.snippet = markerOptions.getSnippet();
this.icon = markerOptions.getIcon();
}
#Override
public LatLng getPosition() {
return latLng;
}
public String getTitle() {
return title;
}
public String getSnippet() {
return snippet;
}
public void setLatLng(LatLng latLng) {
this.latLng = latLng;
}
public BitmapDescriptor getIcon() {
return icon;
}
public void setIcon(BitmapDescriptor icon) {
this.icon = icon;
}
}
The next step would be to make cluster renderer show your icon instead of default maker icon. To achieve that, you need to extend DefaultClusterRenderer object:
public class ClusterRenderer extends DefaultClusterRenderer<MarkerItem> {
public ClusterRenderer(Context context, GoogleMap map, ClusterManager<MarkerItem> clusterManager) {
super(context, map, clusterManager);
clusterManager.setRenderer(this);
}
#Override
protected void onBeforeClusterItemRendered(MarkerItem markerItem, MarkerOptions markerOptions) {
if (markerItem.getIcon() != null) {
markerOptions.icon(markerItem.getIcon()); //Here you retrieve BitmapDescriptor from ClusterItem and set it as marker icon
}
markerOptions.visible(true);
}
}
Finally, you have to initialize the clusterRenderer and markerItems
ClusterManager clusterManager = new ClusterManager<>(context, googleMap);
ClusterRenderer clusterRenderer = new ClusterRenderer<>(activity, googleMap, clusterManager); // not needed to use clusterManager.setRenderer method since i made it in constructor
MarkerOptions markerOptions = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.your_resource_icon));
MarkerItem markerItem = new MarkerItem(markerOptions);
clusterManager.addItem(markerItem);
You can implement your own logic, which icon you want to pass to markerItem here.
EDIT
To pass different icons, you could create a separate method for that
Example:
public MarkerOptions getMarkerOptions(LatLng latLng, String title, String snippet, int iconRes) {
return new MarkerOptions()
.title(title)
.snippet(snippet)
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(iconRes));
}
EDIT 2
I updated MarkerItem class to suit your needs, replace your MyItem class with MarkerItem class. Add your items using this class and update it to suit your needs

Google Map V2 API Directions : no error but not work well

I'm new in Android. I'm trying to make MAP project.. I find the code from some blog, and i edit it with the way that may work, but in the and the Output just keep doing progressDialog...never end
this is my code
public class LokasiActivity extends FragmentActivity{
public static final String USER_CURRENT_LAT = "user_current_lat";
public static final String USER_CURRENT_LONG = "user_current_long";
public static final String DESTINATION_LAT = "destination_lat";
public static final String DESTINATION_LONG = "destination_long";
public static final String DIRECTIONS_MODE = "directions_mode";
private static final LatLng AMSTERDAM = new LatLng(52.37518, 4.895439);
private static final LatLng PARIS = new LatLng(48.856132, 2.352448);
private Exception exception;
private ProgressDialog progressDialog;
private GoogleMap googleMap;
Button btnjalur;
ArrayList<LatLng> directionPoints;
SupportMapFragment fragment;
private Polyline newPolyline;
private int width, height;
private LatLngBounds latlngBounds;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lokasi_layout);
btnjalur = (Button)findViewById(R.id.btnJalur);
getSreenDimanstions();
fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
googleMap = fragment.getMap();
btnjalur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
findDirections( AMSTERDAM.latitude, AMSTERDAM.longitude, PARIS.latitude, PARIS.longitude, LokasiDirection.MODE_DRIVING );
}
});
}
public void handleGetDirectionsResult() {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED);
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
if (newPolyline != null)
{
newPolyline.remove();
}
newPolyline = googleMap.addPolyline(rectLine);
latlngBounds = createLatLngBoundsObject(AMSTERDAM, PARIS);
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
}
private void getSreenDimanstions()
{
Display display = getWindowManager().getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation)
{
if (firstLocation != null && secondLocation != null)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(firstLocation).include(secondLocation);
return builder.build();
}
return null;
}
public class GetDirectionsAsyncTask extends AsyncTask<Map<String, String>, Object, ArrayList<LatLng>>
{
public void onPreExecute()
{
progressDialog = new ProgressDialog(LokasiActivity.this);
progressDialog.setMessage("Calculating directions");
progressDialog.show();
}
#Override
protected ArrayList<LatLng> doInBackground(Map<String, String>... params)
{
Map<String, String> paramMap = params[0];
try
{
LatLng fromPosition = new LatLng(Double.valueOf(paramMap.get(USER_CURRENT_LAT)) , Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
LatLng toPosition = new LatLng(Double.valueOf(paramMap.get(DESTINATION_LAT)) , Double.valueOf(paramMap.get(DESTINATION_LONG)));
LokasiDirection md = new LokasiDirection();
Document doc = md.getDocument(fromPosition, toPosition, paramMap.get(DIRECTIONS_MODE));
directionPoints = md.getDirection(doc);
return directionPoints;
}
catch (Exception e)
{
exception = e;
return null;
}
}
public void onPostExecute()
{
progressDialog.dismiss();
if (exception == null)
{
handleGetDirectionsResult();
}
else
{
processException();
}
}
private void processException()
{
Toast.makeText(LokasiActivity.this, "Error retriving data", 3000).show();
}
}
public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
{
Map<String, String> resultdestination = new HashMap<String, String>();
resultdestination.put(USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
resultdestination.put(USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
resultdestination.put(DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
resultdestination.put(DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
resultdestination.put(DIRECTIONS_MODE, mode);
new GetDirectionsAsyncTask().execute(resultdestination);
}
#Override
protected void onResume() {
super.onResume();
latlngBounds = createLatLngBoundsObject(AMSTERDAM, PARIS);
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150));
}
}
there is something wrong with my code.... please tell me if u realize that..
Output just keep doing progressDialog...never end
You never dismiss the progress dialog. The code in onPostExecute() is never executed since the method signature is wrong.
Change
public void onPostExecute()
to
#Override
public void onPostExecute(ArrayList<LatLng> result)
The #Override annotation helps the compiler make sure you're in fact overriding a method by emitting an error in case you're not.

Trying to get the correct context

i am following this tutorial to implement google direction API. In the tutorial the onclick and all codes related to inputing data are in a fragmentActivity. But i would like to use a fragment. i would like to know how to change the asyncTask class in the tutorial so that it is using the right Context to find my fragment.
Here is my attempt.
public class GetDirectionsAsyncTask extends AsyncTask<Map<String, Object>, Object, ArrayList<LatLng>>
{
public static final String USER_CURRENT_LATLNG = "user_current_latlng";
public static final String DESTINATION_LATLNG = "destination_latlng";
public static final String DIRECTIONS_MODE = "directions_mode";
private MainActivity activity;
private Closest fragment;
private Exception exception;
private ProgressDialog progressDialog;
public GetDirectionsAsyncTask(Closest fragment, MainActivity activity)
{
super();
this.activity = activity;
}
public void onPreExecute()
{
progressDialog = new ProgressDialog(this.fragment.getActivity());
progressDialog.setMessage("Calculating directions");
progressDialog.show();
}
#Override
public void onPostExecute(ArrayList<LatLng> result)
{
progressDialog.dismiss();
if (exception == null)
{
fragment.handleGetDirectionsResult(result);
}
else
{
processException();
}
}
#Override
protected ArrayList<LatLng> doInBackground(Map<String, Object>... params)
{
Map<String, Object> paramMap = params[0];
try
{
LatLng fromPosition = (LatLng) paramMap.get(USER_CURRENT_LATLNG);
LatLng toPosition = (LatLng) paramMap.get(DESTINATION_LATLNG);
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(fromPosition, toPosition, (String)paramMap.get(DIRECTIONS_MODE));
ArrayList<LatLng> directionPoints = md.getDirection(doc);
return directionPoints;
}
catch (Exception e)
{
exception = e;
return null;
}
}
private void processException()
{
Toast.makeText(activity, "Error retriving data", Toast.LENGTH_LONG).show();
}
}
The minute it needs to know the Context, it crashes in logcat with a nullpointer exception. if u realise, the first time it needs the context is on progressDialog = new ProgressDialog(this.fragment.getActivity());
Simply replace this.fragment.getActivity() with this.activity since you already have reference to the activity.
Technically, to make it a more reusable and decoupled class I would replace the reference to MainActivity and simply call it Context since that's really all you need it for and don't really care if it's the MainActivity or some other Activity that this later lives on.
Instead
progressDialog = new ProgressDialog(this.fragment.getActivity());
use
progressDialog = new ProgressDialog(activity);

Categories

Resources