at com.projects.fragments.MapFragment.refetch(MapFragment.java:207) - android

I am getting error at:
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200) at
com.projects.fragments.MapFragment.onMapReady(MapFragment.java:200)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown
Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown
Source)
Occurs in run time this the Mapfragment class
package com.projects.fragments;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.application.RealEstateApplication;
import com.config.Config;
import com.config.UIConfig;
import com.db.Queries;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.libraries.asynctask.MGAsyncTask;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.drawingview.DrawingView;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.sliding.MGSliding;
import com.libraries.usersession.UserAccessSession;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Favorite;
import com.models.Photo;
import com.models.PropertyType;
import com.models.RealEstate;
import com.projects.activities.DetailActivity;
import com.projects.realestatefinder.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by mg on 27/07/16.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback,
RealEstateApplication.OnLocationListener,
GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapClickListener,
DrawingView.OnDrawingViewListener {
private View viewInflate;
private GoogleMap googleMap;
private MGSliding frameSliding;
SwipeRefreshLayout swipeRefresh;
MGAsyncTaskNoDialog task;
ArrayList<RealEstate> realEstates;
private HashMap<String, RealEstate> markers;
private ArrayList<Marker> markerList;
private RealEstate selectedRealEstate;
private DrawingView drawingView;
private Unbinder unbinder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
viewInflate = inflater.inflate(R.layout.fragment_map, null);
unbinder = ButterKnife.bind(this, viewInflate);
return viewInflate;
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
if(task != null)
task.cancel(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
realEstates = new ArrayList<RealEstate>();
swipeRefresh = (SwipeRefreshLayout) viewInflate.findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
FragmentManager fManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
if(supportMapFragment == null) {
fManager = getChildFragmentManager();
supportMapFragment = ((SupportMapFragment) fManager.findFragmentById(R.id.googleMap));
}
supportMapFragment.getMapAsync(this);
frameSliding = (MGSliding) viewInflate.findViewById(R.id.frameSliding);
Animation animationIn = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_up2);
Animation animationOut = AnimationUtils.loadAnimation(this.getActivity(), R.anim.slide_down2);
frameSliding.setInAnimation(animationIn);
frameSliding.setOutAnimation(animationOut);
frameSliding.setVisibility(View.GONE);
markers = new HashMap<String, RealEstate>();
markerList = new ArrayList<Marker>();
}
#Override
public void onMapReady(GoogleMap _googleMap) {
googleMap = _googleMap;
googleMap.setOnInfoWindowClickListener(this);
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if(frameSliding.getVisibility() == View.VISIBLE)
frameSliding.setVisibility(View.INVISIBLE);
}
});
drawingView = (DrawingView) viewInflate.findViewById(R.id.drawingView);
drawingView.setBrushSize(5);
drawingView.setPolygonFillColor(getResources().getColor(R.color.colorPrimaryAlpha));
drawingView.setColor(getResources().getColor(R.color.colorAccent));
drawingView.setPolylineColor(getResources().getColor(R.color.colorAccent));
drawingView.setGoogleMap(googleMap);
drawingView.setOnDrawingViewListener(this);
if(!MGUtilities.isLocationEnabled(getActivity()) && RealEstateApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
showRefresh(false);
}
});
utils.showAlertView(
getActivity(),
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
showRefresh(true);
if(RealEstateApplication.currentLocation != null) {
getData();
}
else {
refetch();
}
}
}
public void refetch() {
showRefresh(true);
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(this, getActivity());
}
private void getData() {
showRefresh(true);
task = new MGAsyncTaskNoDialog(getActivity());
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) {
}
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
showRefresh(false);
addMarkers(realEstates);
// showBoundedMap();
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(RealEstateApplication.currentLocation != null && MGUtilities.hasConnection(getContext())) {
try {
UserAccessSession accessSession = UserAccessSession.getInstance(getActivity());
float radius = accessSession.getFilterDistance();
if(radius == 0)
radius = Config.DEFAULT_FILTER_DISTANCE_IN_KM;
String strUrl = String.format("%s?api_key=%s&lat=%f&lon=%f&radius=%f&get_propertytypes=1&default_count_to_find_distance=%d",
Config.GET_DATA_JSON_URL,
Config.API_KEY,
RealEstateApplication.currentLocation.getLatitude(),
RealEstateApplication.currentLocation.getLongitude(),
radius,
Config.DEFAULT_COUNT_TO_FIND);
Log.e("URL", strUrl);
DataParser parser = new DataParser();
DataResponse data = parser.getData(strUrl);
if (data == null)
return;
if(data.getMax_distance() > 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistanceMax(data.getMax_distance());
}
if(Config.AUTO_ADJUST_DISTANCE) {
if(UserAccessSession.getInstance(getActivity()).getFilterDistance() == 0) {
UserAccessSession.getInstance(getActivity()).setFilterDistance(data.getDefault_distance());
}
}
Queries q = RealEstateApplication.getQueriesInstance(getContext());
if (data.getProperty_types() != null && data.getProperty_types().size() > 0) {
for (PropertyType obj : data.getProperty_types()) {
q.deletePropertyType(obj.getPropertytype_id());
q.insertPropertyType(obj);
}
}
if (data.getReal_estates() != null && data.getReal_estates().size() > 0) {
for (RealEstate obj : data.getReal_estates()) {
double distance = obj.getDistance() * Config.CONVERSION_SERVER_DATA_DISTANCE_TO_KM;
obj.setDistance(distance);
q.deleteRealEstate(obj.getRealestate_id());
q.insertRealEstate(obj);
if (obj.getPhotos() != null && obj.getPhotos().size() > 0) {
for (Photo photo : obj.getPhotos()) {
q.deletePhoto(photo.getPhoto_id());
q.insertPhoto(photo);
}
}
if(obj.getAgent() != null) {
q.deleteAgent(obj.getAgent().getAgent_id());
q.insertAgent(obj.getAgent());
}
realEstates.add(obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
realEstates = RealEstateApplication.getQueriesInstance(getContext()).getRealEstates();
if(RealEstateApplication.currentLocation != null) {
for(RealEstate realEstate : realEstates) {
Location locStore = new Location("Store");
locStore.setLatitude(realEstate.getLat());
locStore.setLongitude(realEstate.getLon());
double userDistanceFromStore =
RealEstateApplication.currentLocation.distanceTo(locStore) *
Config.CONVERSION_OFFLINE_DATA_DISTANCE_TO_KM;
realEstate.setDistance(userDistanceFromStore);
}
Collections.sort(realEstates, new Comparator<RealEstate>() {
#Override
public int compare(RealEstate obj1, RealEstate obj2) {
if (obj1.getDistance() < obj2.getDistance())
return -1;
if (obj1.getDistance() > obj2.getDistance())
return 1;
return 0;
}
});
}
}
}
});
task.execute();
}
private void addMarkers(ArrayList<RealEstate> arrayList) {
if(googleMap != null)
googleMap.clear();
try {
markerList.clear();
markers.clear();
for(RealEstate entry: arrayList) {
if(entry.getLat() == 0 || entry.getLon() == 0)
continue;
Marker mark = createMarker(entry);
markerList.add(mark);
markers.put(mark.getId(), entry);
}
showBoundedMap();
}
catch(Exception e) {
e.printStackTrace();
}
}
private Marker createMarker(RealEstate realEstate) {
final MarkerOptions markerOptions = new MarkerOptions();
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
Spanned price = Html.fromHtml(strPrice);
price = Html.fromHtml(price.toString());
Spanned storeAddress = Html.fromHtml(realEstate.getAddress());
storeAddress = Html.fromHtml(storeAddress.toString());
markerOptions.title( price.toString() );
String address = storeAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = storeAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
markerOptions.snippet(address);
markerOptions.position(new LatLng(realEstate.getLat(), realEstate.getLon()));
markerOptions.icon(BitmapDescriptorFactory.fromResource(UIConfig.MAP_PIN_REAL_ESTATE));
Marker mark = googleMap.addMarker(markerOptions);
mark.setInfoWindowAnchor(Config.MAP_INFO_WINDOW_X_OFFSET, 0);
return mark;
}
private void showBoundedMap() {
if(markerList == null && markerList.size() == 0 ) {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
if(markerList.size() > 0) {
LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < markerList.size(); i++) {
Marker marker = markerList.get(i);
bld.include(marker.getPosition());
}
LatLngBounds bounds = bld.build();
googleMap.moveCamera(
CameraUpdateFactory.newLatLngBounds(bounds,
this.getResources().getDisplayMetrics().widthPixels,
this.getResources().getDisplayMetrics().heightPixels,
70));
}
else {
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
}
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
final RealEstate obj = markers.get(marker.getId());
selectedRealEstate = obj;
if(RealEstateApplication.currentLocation != null) {
Location loc = new Location("marker");
loc.setLatitude(marker.getPosition().latitude);
loc.setLongitude(marker.getPosition().longitude);
double meters = RealEstateApplication.currentLocation.distanceTo(loc);
double miles = meters * Config.METERS_TO_KM;
String str = String.format("%.1f %s",
miles,
MGUtilities.getStringFromResource(getActivity(), R.string.km));
TextView tvDistance = (TextView) viewInflate.findViewById(R.id.tvDistance);
tvDistance.setText(str);
}
frameSliding.setVisibility(View.VISIBLE);
Queries q = RealEstateApplication.getQueriesInstance(getContext());
ImageView imgViewThumb = (ImageView) viewInflate.findViewById(R.id.imgViewThumb);
Photo p = q.getPhotoByRealEstateId(obj.getRealestate_id());
if(p != null) {
RealEstateApplication.getImageLoaderInstance(
getActivity()).displayImage(p.getPhoto_url(),
imgViewThumb,
RealEstateApplication.getDisplayImageOptionsInstance());
}
else {
imgViewThumb.setImageResource(UIConfig.IMAGE_PLACEHOLDER);
}
imgViewThumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), DetailActivity.class);
i.putExtra("realestate", obj);
getActivity().startActivity(i);
}
});
String strPrice = String.format("%s %s", obj.getCurrency(), obj.getPrice());
Spanned spannedPrice = Html.fromHtml(strPrice);
spannedPrice = Html.fromHtml(spannedPrice.toString());
Spanned spannedAddress = Html.fromHtml(obj.getAddress());
spannedAddress = Html.fromHtml(spannedAddress.toString());
String address = spannedAddress.toString();
if(address.length() > Config.ELLIPSE_HOME_COUNT)
address = spannedAddress.toString().substring(0, Config.ELLIPSE_HOME_COUNT) + "...";
TextView tvTitle = (TextView) viewInflate.findViewById(R.id.tvTitle);
TextView tvSubtitle = (TextView) viewInflate.findViewById(R.id.tvSubtitle);
tvTitle.setText(spannedPrice);
tvSubtitle.setText(address);
ToggleButton toggleButtonFave = (ToggleButton) viewInflate.findViewById(R.id.toggleButtonFave);
toggleButtonFave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkFave(v, obj);
}
});
Favorite fave = q.getFavoriteByRealEstateId(obj.getRealestate_id());
toggleButtonFave.setChecked(true);
if(fave == null)
toggleButtonFave.setChecked(false);
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
frameSliding.setVisibility(View.INVISIBLE);
}
private void checkFave(View view, RealEstate realEstate) {
Queries q = RealEstateApplication.getQueriesInstance(getContext());
Favorite fave = q.getFavoriteByRealEstateId(realEstate.getRealestate_id());
if(fave != null) {
q.deleteFavorite(realEstate.getRealestate_id());
((ToggleButton) view).setChecked(false);
}
else {
fave = new Favorite();
fave.setRealestate_id(realEstate.getRealestate_id());
q.insertFavorite(fave);
((ToggleButton) view).setChecked(true);
}
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
ArrayList<Marker> markers1;
#SuppressLint("DefaultLocale")
#Override
public void onUserDidFinishDrawPolygon(PolygonOptions polygonOptions) {
// TODO Auto-generated method stub
googleMap.clear();
googleMap.addPolygon( polygonOptions );
markers1 = getMarkersInsidePoly(polygonOptions, null, markerList);
markerList.clear();
markers.clear();
for(Marker mark1 : markers1) {
for(RealEstate realEstate : realEstates) {
String strPrice = String.format("%s %s", realEstate.getCurrency(), realEstate.getPrice());
if(mark1.getPosition().latitude == realEstate.getLat() &&
mark1.getPosition().longitude == realEstate.getLon() &&
mark1.getTitle().compareTo(strPrice) == 0) {
Marker mark = createMarker(realEstate);
markerList.add(mark);
markers.put(mark.getId(), realEstate);
break;
}
}
}
drawingView.enableDrawing(false);
drawingView.resetPolygon();
drawingView.startNew();
if(markers1.size() == 0)
Toast.makeText(getContext(), R.string.no_results_found, Toast.LENGTH_SHORT).show();
}
#Override
public void onUserDidFinishDrawPolyline(PolylineOptions polylineOptions) { }
public ArrayList<Marker> getMarkersInsidePoly(PolygonOptions polygonOptions,
PolylineOptions polylineOptions, ArrayList<Marker> markers) {
ArrayList<Marker> markersFound = new ArrayList<Marker>();
for(Marker mark : markers) {
Boolean isFound = polygonOptions != null ?
drawingView.latLongContainsInPolygon(mark.getPosition(), polygonOptions) :
drawingView.latLongContainsInPolyline(mark.getPosition(), polylineOptions);
if(isFound) {
markersFound.add(mark);
}
}
return markersFound;
}
#OnClick(R.id.btnDraw)
public void drawMap() {
drawingView.enableDrawing(true);
drawingView.startDrawingPolygon(true);
}
#OnClick(R.id.btnRefresh)
public void refresh() {
showRefresh(true);
addMarkers(realEstates);
showRefresh(false);
}
#OnClick(R.id.btnRoute)
public void route() {
if(selectedRealEstate == null) {
MGUtilities.showAlertView(
getActivity(),
R.string.action_error,
R.string.cannot_proceed_route);
return;
}
String geo = String.format("http://maps.google.com/maps?f=d&daddr=%s&dirflg=d", selectedRealEstate.getAddress()) ;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(geo));
intent.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
startActivity(intent);
}
#OnClick(R.id.btnCurrentLocation)
public void currentLocation() {
Location loc = RealEstateApplication.currentLocation;
if(loc != null) {
googleMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(loc.getLatitude(), loc.getLongitude()),
70) );
}
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
RealEstateApplication app = (RealEstateApplication) getActivity().getApplication();
app.setOnLocationListener(null, getActivity());
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
getData();
}
}, Config.DELAY_SHOW_ANIMATION + 500);
googleMap.setMyLocationEnabled(true);
}
#Override
public void onLocationRequestDenied() {
showRefresh(false);
MGUtilities.showAlertView(getActivity(), R.string.permission_error, R.string.permission_error_details_location);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(getActivity()))
refetch();
else {
showRefresh(false);
Toast.makeText(getActivity(),
R.string.location_error_not_turned_on, Toast.LENGTH_LONG).show();
}
}
}
}

Related

Fetching location data using volley and creating multiple markers in Google maps

This is my first time working with google maps in android.I was able to create a map showing my current user location.
However, I would like to display multiple markers whose data I'm fetching using volley. To do this I'm using a backgroundTask class with a singleton class. The backgroundTask class is the one returning the arrayList of the location data.
For this reason I need to populate my BackgroungTask class with the arrayList before my MapActivity become active and access the arraylist of objects in onCreate but it seems the MapActivity loads very fast and a reference to the arrayList of objects from the BackgroungTask class is always null.
This is the BackgroundTask class which is fetching the data
package com.example.carwashplaces;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class BackgroundTask {
private Context context;
private ArrayList<ModelLocation> locationArrayList = new ArrayList<>();
String json_url = "http://histogenetic-exhaus.000webhostapp.com/location.php";
public BackgroundTask(Context context) {
this.context = context;
}
public ArrayList<ModelLocation> getLocationArrayList(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest (
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count<response.length()){
try {
JSONObject jsonObject = response.getJSONObject(count);
ModelLocation modelLocation = new ModelLocation(
jsonObject.getString("id"),
jsonObject.getString("name"),
jsonObject.getString("latitude"),
jsonObject.getString("longitude"),
jsonObject.getString("staff"),
jsonObject.getString("comment"),
jsonObject.getString("phone"));
locationArrayList.add(modelLocation);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error fetching car wash places... ", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestque(jsonArrayRequest);
return locationArrayList;
}
}
This is the MapActivity where I want to display the locations.
package com.example.carwashplaces;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AutocompletePrediction;
import com.google.android.libraries.places.api.model.AutocompleteSessionToken;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.FetchPlaceRequest;
import com.google.android.libraries.places.api.net.FetchPlaceResponse;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest;
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.mancj.materialsearchbar.adapter.SuggestionsAdapter;
import com.skyfishjy.library.RippleBackground;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlacesClient placesClient;
private List<AutocompletePrediction> predictionList;
private ArrayList<ModelLocation> locations;
private BackgroundTask backgroundTask;
private Location mLastKnownLocation;
private LocationCallback locationCallback;
private MaterialSearchBar materialSearchBar;
private View mapView;
private Button btnFind;
private RippleBackground rippleBg;
private final float DEFAULT_ZOOM = 18;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//init views
materialSearchBar = findViewById(R.id.searchBar);
btnFind = findViewById(R.id.btnFind);
rippleBg = findViewById(R.id.ripple_bg);
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "MY_KEY");
placesClient = Places.createClient(this);
final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString(), true, null, true);
}
#Override
public void onButtonClicked(int buttonCode) {
if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION){
//opening or closing a navigation drawer
}else if (buttonCode == MaterialSearchBar.BUTTON_BACK){
materialSearchBar.disableSearch();
}
}
});
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
.setCountry("ke")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(s.toString())
.build();
placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
#Override
public void onComplete(#NonNull Task<FindAutocompletePredictionsResponse> task) {
if (task.isSuccessful()){
//predictions found, find out what suggestions we have from google
FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
if (predictionsResponse != null){
predictionList = predictionsResponse.getAutocompletePredictions();
//converting predictionList into a list of string
List<String> suggestionsList = new ArrayList<>();
for (int i = 0; i < predictionList.size(); i++){
AutocompletePrediction prediction = predictionList.get(i);
suggestionsList.add(prediction.getFullText(null).toString());
}
//pass suggestion list to our MaterialSearchBar
materialSearchBar.updateLastSuggestions(suggestionsList);
if (!materialSearchBar.isSuggestionsVisible()){
materialSearchBar.showSuggestionsList();
}
}
}
else {
//some error
Log.i("mytag", "prediction fetching task failed");
}
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
#Override
public void OnItemClickListener(int position, View v) {
// seek the longitude and latitude of that suggestion
if (position >= predictionList.size()){
return;
}
AutocompletePrediction selectedPrediction = predictionList.get(position);
String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
materialSearchBar.setText(suggestion);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
materialSearchBar.clearSuggestions();
}
},1000);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null){
imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
String placeId = selectedPrediction.getPlaceId();
List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);// get latitude and longitude of a place
FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
#Override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
// place found, update camera Factory
Place place = fetchPlaceResponse.getPlace();
Log.i("mytag", "place found: "+place.getName());
LatLng latLngOfPlace = place.getLatLng();
if (latLngOfPlace != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngOfPlace, DEFAULT_ZOOM));
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException){
ApiException apiException = (ApiException) e;
apiException.printStackTrace();
int statusCode = apiException.getStatusCode();
Log.i("mytag", "place not found: " +e.getMessage());
Log.i("mytag", "status code: "+statusCode);
}
}
});
}
#Override
public void OnItemDeleteListener(int position, View v) {
}
});
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the current location of the marker
LatLng currentMarkerLocation = mMap.getCameraPosition().target;
rippleBg.startRippleAnimation();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
rippleBg.stopRippleAnimation();
Toast.makeText(MapActivity.this, "Nearest Car Wash", Toast.LENGTH_SHORT).show();
}
},3000);
}
});
}
//Called when the map is loaded
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null){
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 180);
}
//check if gps is enabled or not and then request user to enable it
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MapActivity.this);
Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
task.addOnSuccessListener(MapActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
getDeviceLocation();
setMarkersToCarWashes();
}
});
task.addOnFailureListener(MapActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException){
ResolvableApiException resolvable = (ResolvableApiException) e;
try {
resolvable.startResolutionForResult(MapActivity.this, 51);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
}
}
});
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (materialSearchBar.isSuggestionsVisible())
materialSearchBar.clearSuggestions();
if (materialSearchBar.isSearchEnabled())
materialSearchBar.disableSearch();
return false;
}
});
setMarkersToCarWashes();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 51) {
if (resultCode == RESULT_OK) {
getDeviceLocation();
setMarkersToCarWashes();
}
}
}
private void setMarkersToCarWashes() {
if (locations != null){
for(int i = 0; i < locations.size(); i++){
double lati = Double.parseDouble(locations.get(i).getLatitude());
double longLat = Double.parseDouble(locations.get(i).getLongitude());
//set markers to car wash places
mMap.addMarker(new MarkerOptions().position(
new LatLng(lati, longLat))
.title(locations.get(i).getName())
.snippet(locations.get(i).getComment()));
}
}
}
private void getDeviceLocation() {
mFusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()){
mLastKnownLocation = task.getResult();
if (mLastKnownLocation != null){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
}else {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null){
return;
}
mLastKnownLocation = locationResult.getLastLocation();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
}
};
mFusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
}else {
Toast.makeText(MapActivity.this, "Unable to get last Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
And This is the part of the code in MapActivity where I'm trying to get the arraylist from the BackgroundTask class
//an object of backgroung task
backgroundTask = new BackgroundTask(MapActivity.this);
locations = new ArrayList<>();
//getting location data from background task
locations = backgroundTask.getLocationArrayList();
How do I display the markers in onMapReady method i.e populate the BackgroundTask before the onMapReady method executes?
This is my approach, based off of this solution from related thread. First let's create an interface to handle the volley's response.
public interface LocationsCallback {
void onSuccess(ArrayList<ModelLocation> fetchedLocations);
}
Then modify your getLocationArrayList method as follows:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback)
Inside the onResponse method of getLocationArrayList, right at the end, add the callback:
public ArrayList<ModelLocation> getLocationArrayList(final LocationsCallback locationsCallback) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.POST,
json_url,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// your code here...
// Add this at the end here
ArrayList<ModelLocation> locations = locationArrayList;
locationsCallback.onSuccess(locations);
}
//...
Now assign your MapActivity's locations to the fetched array:
locations = new ArrayList<>();
backgroundTask = new BackgroundTask(MapActivity.this);
backgroundTask.getLocationArrayList(new LocationsCallback() {
#Override
public void onSuccess(ArrayList<ModelLocation> fetchedLocations) {
locations = fetchedLocations;
// Your other code goes here...
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
mapView = mapFragment.getView();
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);
Places.initialize(MapActivity.this, "KEY");
placesClient = Places.createClient(MapActivity.this);
//...
}
});
And the markers will now be displayed on the map. See screenshot below. :)

'Google Now' Voice Search in Android App

I'm not even sure if this is the right thing to do any more with Google not supporting 'Google Now', but I can't seem to find any suitable alternative.
Using this https://antonioleiva.com/voice_search_google_now/#comment-8611 as a guide I am trying o implement a voice search in my App, but not having much luck.
I already have a search facility for users. What I have done so far:-
GlobalApplication.java
public static Queries getQueriesInstance(Context context) {
if(q == null) {
dbHelper = new DbHelper(context);
q = new Queries(db, dbHelper);
}
return q;
}
Then in MainActivity.java
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Intent i;
int id = item.getItemId();
...
...
if(id == R.id.nav_search) {
i = new Intent(this, SearchActivity.class);
startActivity(i);
}
...
...
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And finally, before adding anything, my SearchActivity.java file
package com.projects.activities;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableString;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.application.GlobalApplication;
import com.config.Config;
import com.db.Queries;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.libraries.asynctask.MGAsyncTaskNoDialog;
import com.libraries.dataparser.DataParser;
import com.libraries.location.MGLocationManagerUtils;
import com.libraries.utilities.MGUtilities;
import com.models.DataResponse;
import com.models.Deal;
import com.models.DealCategory;
import com.models.Status;
import com.projects.adapp.R;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity implements
GlobalApplication.OnLocationListener{
private AsyncTaskNoDialog task;
SeekBar seekBarRadius;
SwipeRefreshLayout swipeRefresh;
Queries q;
Button btnSearch;
ArrayList<DealCategory> selectedCategories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setContentView(R.layout.activity_list_swipe_search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.search);
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefresh.setClickable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
swipeRefresh.setProgressViewOffset(false, 0,100);
}
swipeRefresh.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
showRefresh(false);
q = GlobalApplication.getQueriesInstance(this);
seekBarRadius = (SeekBar) findViewById(R.id.seekBarRadius);
seekBarRadius.setMax(Config.SEARCH_RADIUS_MAX_VALUE);
seekBarRadius.setProgress(Config.SEARCH_RADIUS_DEFAULT_VALUE);
seekBarRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) { }
#Override
public void onStartTrackingTouch(SeekBar arg0) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
updateRadius(progress);
}
});
updateRadius(seekBarRadius.getProgress());
selectedCategories = new ArrayList<DealCategory>();
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
FrameLayout frameCategory = (FrameLayout) findViewById(R.id.frameCategory);
frameCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SearchActivity.this, CategorySearchActivity.class);
startActivityForResult(i, Config.RESULT_CODE_CATEGORY);
}
});
seekBarRadius.setEnabled(false);
btnSearch.setEnabled(false);
if(!MGUtilities.isLocationEnabled(this) && GlobalApplication.currentLocation == null) {
MGLocationManagerUtils utils = new MGLocationManagerUtils();
utils.setOnAlertListener(new MGLocationManagerUtils.OnAlertListener() {
#Override
public void onPositiveTapped() {
startActivityForResult(
new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS),
Config.PERMISSION_REQUEST_LOCATION_SETTINGS);
}
#Override
public void onNegativeTapped() {
Toast.makeText(SearchActivity.this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
});
utils.showAlertView(
this,
R.string.location_error,
R.string.gps_not_on,
R.string.go_to_settings,
R.string.cancel);
}
else {
refetch();
}
GlobalApplication app = (GlobalApplication)getApplication();
app.sendScreenView(Config.kGAIScreenNameSearch);
}
public void refetch() {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(this, this);
}
#Override
public void onLocationChanged(Location prevLoc, Location currentLoc) {
GlobalApplication app = (GlobalApplication) getApplication();
app.setOnLocationListener(null, this);
seekBarRadius.setEnabled(true);
btnSearch.setEnabled(true);
}
#Override
public void onLocationRequestDenied() {
MGUtilities.showAlertView(this, R.string.permission_error, R.string.permission_error_details_location);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == Config.RESULT_CODE_CATEGORY && resultCode == RESULT_OK) {
selectedCategories = (ArrayList<DealCategory>) data.getSerializableExtra("categories");
if(selectedCategories != null && selectedCategories.size() > 0) {
TextView tvCategory = (TextView) findViewById(R.id.tvCategory);
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += cat.getCategory();
if(x < selectedCategories.size() - 1)
cats += ", ";
}
if(!cats.isEmpty()) {
tvCategory.setText(cats);
}
else {
tvCategory.setText(R.string.all_categories);
}
}
}
if (requestCode == Config.PERMISSION_REQUEST_LOCATION_SETTINGS) {
if(MGUtilities.isLocationEnabled(this))
refetch();
else {
Toast.makeText(this, R.string.location_error_not_turned_on_search, Toast.LENGTH_LONG).show();
}
}
}
public void updateRadius(int progress){
String strSeekVal = String.format("%d %s",
progress,
MGUtilities.getStringFromResource(SearchActivity.this, R.string.km));
TextView tvRadius = (TextView) findViewById(R.id.tvRadius);
tvRadius.setText(strSeekVal);
}
public void showRefresh(boolean show) {
swipeRefresh.setRefreshing(show);
swipeRefresh.setEnabled(show);
}
public void search() {
showRefresh(true);
beginParsing();
}
public ArrayList<Deal> searchLocal() {
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
int radius = seekBarRadius.getProgress();
int countParams = 0;
countParams += searchStr.length() > 0 ? 1 : 0;
countParams += radius > 0 ? 1 : 0;
countParams += selectedCategories != null && selectedCategories.size() > 0 ? 1 : 0;
ArrayList<Deal> array = q.getDeals();
ArrayList<Deal> results = new ArrayList<>();
for(Deal event : array) {
try {
int qualifyCount = 0;
if(searchStr.length() > 0) {
boolean isFound = searchStr.contains(event.getTitle()) ||
searchStr.contains(event.getAddress()) ||
searchStr.contains(event.getDesc()) ||
event.getTitle().contains(searchStr) ||
event.getAddress().contains(searchStr) ||
event.getDesc().contains(searchStr);
if(isFound)
qualifyCount += 1;
}
if(GlobalApplication.currentLocation != null) {
Location loc1 = new Location("Loc1");
loc1.setLatitude(event.getLat());
loc1.setLongitude(event.getLon());
Location loc2 = new Location("Loc2");
loc2.setLatitude(GlobalApplication.currentLocation.getLatitude());
loc2.setLongitude(GlobalApplication.currentLocation.getLongitude());
double distance = loc1.distanceTo(loc2) * Config.METERS_TO_KM;
event.setDistance(distance);
if(distance <= radius)
qualifyCount += 1;
}
ObjectMapper mapper = new ObjectMapper();
DataResponse categories = mapper.readValue(event.getCategories(), DataResponse.class);
if(categories != null && categories.getCategories() != null) {
for(DealCategory cat : categories.getCategories()) {
boolean isFound = false;
for(DealCategory selectedCat : selectedCategories) {
if(selectedCat.getCategory_id() == cat.getCategory_id()) {
isFound = true;
break;
}
}
if(isFound) {
qualifyCount += 1;
break;
}
}
}
if(qualifyCount == countParams)
results.add(event);
}
catch(Exception e) {
e.printStackTrace();
}
}
return results;
}
public void beginParsing() {
if(task != null)
task.cancel(true);
task = new MGAsyncTaskNoDialog(this);
task.setMGAsyncTaskListener(new MGAsyncTaskNoDialog.OnMGAsyncTaskListenerNoDialog() {
DataResponse response;
ArrayList<Deal> events;
#Override
public void onAsyncTaskProgressUpdate(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPreExecute(MGAsyncTaskNoDialog asyncTask) { }
#Override
public void onAsyncTaskPostExecute(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
updateData(response, events);
}
#Override
public void onAsyncTaskDoInBackground(MGAsyncTaskNoDialog asyncTask) {
// TODO Auto-generated method stub
if(MGUtilities.hasConnection(SearchActivity.this)) {
response = syncData();
}
else{
events = searchLocal();
}
}
});
task.execute();
}
public DataResponse syncData() {
String cats = "";
for(int x = 0; x < selectedCategories.size(); x++) {
DealCategory cat = selectedCategories.get(x);
cats += String.valueOf(cat.getCategory_id());
if (x < selectedCategories.size() - 1)
cats += ",";
}
EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
String filterSearch = Html.toHtml(new SpannableString(txtSearch.getText().toString()));
String searchStr = MGUtilities.filterInvalidChars(filterSearch);
double radius = seekBarRadius.getProgress() * Config.KM_TO_MILES;
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keywords", searchStr ));
params.add(new BasicNameValuePair("lat", String.valueOf(GlobalApplication.currentLocation.getLatitude()) ));
params.add(new BasicNameValuePair("lon", String.valueOf(GlobalApplication.currentLocation.getLongitude()) ));
params.add(new BasicNameValuePair("category_ids", cats) );
params.add(new BasicNameValuePair("radius", String.valueOf(radius)) );
params.add(new BasicNameValuePair("api_key", Config.API_KEY ));
GlobalApplication.params = params;
DataResponse response = DataParser.getJSONFromUrlWithPostRequest(Config.SEARCH_DEALS_JSON_URL, params);
return response;
}
public void updateData(DataResponse response, ArrayList<Deal> deals) {
showRefresh(false);
if(response != null) {
Status status = response.getStatus();
if(status.getStatus_code() == -1 && response.getDeals() != null ) {
if(response.getDeals().size() == 0) {
Toast.makeText(SearchActivity.this, R.string.no_results_found, Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", response.getDeals());
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, status.getStatus_text());
}
}
else if(deals != null && deals.size() > 0) {
GlobalApplication.params = null;
Intent i = new Intent(this, SearchResultsActivity.class);
i.putExtra("deals", deals);
startActivity(i);
}
else {
MGUtilities.showAlertView(this, R.string.network_error, R.string.problems_encountered_while_syncing);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
// Handle action bar actions click
switch (item.getItemId()) {
default:
finish();
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(android.view.Menu menu) {
// if nav drawer is opened, hide the action items
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onDestroy() {
super.onDestroy();
if(task != null)
task.cancel(true);
}
}
Taken from the tutorial link above, I then added the following to my Manifest
AndroidManifest.xml
<activity
android:name="com.projects.activities.SearchActivity">
<intent-filter>
<action android:name="com.google.android.gms.actions.SEARCH_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I then added the following to my SearchActivity.java file
private static final String ACTION_VOICE_SEARCH =
"com.google.android.gms.actions.SEARCH_ACTION";
private void handleVoiceSearch(Intent intent) {
if (intent != null && ACTION_VOICE_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
setSearchViewVisible(true);
searchView.setQuery(query, true);
}
}
The in various places and in slightly different ways, I have tried adding
handleVoiceSearch(getIntent());
to the SearchActivity.java file, but I don't seem to be having much luck. I am testing from an Alpha version uploaded to Play Store.
Is there anything obvious anyone can see I am missing?
Thanks

Only 10 Users Show Up In List Of Users

I'm developing a messaging app using quickblox, the activity where all the users in the database show, only 10 users show up when there's more users than just 10. Any help would be much appreciated!! Got to add more details, but this should explain the problem enough
ListUsers Class
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ListUsersAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.QBSystemMessagesManager;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.utils.DialogUtils;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import org.jivesoftware.smack.SmackException;
import java.util.ArrayList;
import java.util.List;
public class ListUsers extends AppCompatActivity {
ListView lstUsers;
Button btnCreate;
String mode="";
QBChatDialog qbChatDialog;
List<QBUser> userAdd=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_users);
Toolbar toolbar = (Toolbar)findViewById(R.id.chatusers_toolbar);
toolbar.setTitle("Users");
setSupportActionBar(toolbar);
mode = getIntent().getStringExtra(Common.UPDATE_MODE);
qbChatDialog=(QBChatDialog)getIntent().getSerializableExtra(Common.UPDATE_DIALOG_EXTRA);
lstUsers = (ListView)findViewById(R.id.lstUsers);
lstUsers.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btnCreate = (Button)findViewById(R.id.btn_create_chat);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mode == null) {
int countChoice = lstUsers.getCount();
if (lstUsers.getCheckedItemPositions().size() == 1)
createPrivateChat(lstUsers.getCheckedItemPositions());
else if (lstUsers.getCheckedItemPositions().size() > 1)
createGroupChat(lstUsers.getCheckedItemPositions());
else
Toast.makeText(ListUsers.this, "Select a friend to chat with", Toast.LENGTH_SHORT).show();
} else if (mode.equals(Common.UPDATE_ADD_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.addUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Add user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
} else if (mode.equals(Common.UPDATE_REMOVE_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.removeUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Remove user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
}
});
if (mode == null && qbChatDialog == null)
retrieveAllUser();
else{
if (mode.equals(Common.UPDATE_ADD_MODE))
loadListAvailableUser();
else if (mode.equals(Common.UPDATE_REMOVE_MODE))
loadListUserInGroup();
}
}
private void loadListUserInGroup() {
btnCreate.setText("Remove User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser> listUserAlreadyInGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
ArrayList<QBUser> users = new ArrayList<QBUser>();
users.addAll(listUserAlreadyInGroup);
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),users);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = users;
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadListAvailableUser() {
btnCreate.setText("Add User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
ArrayList<QBUser> listUsers = QBUsersHolder.getInstance().getAllUsers();
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser>listUserAlreadyInChatGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
for (QBUser user:listUserAlreadyInChatGroup)
listUsers.remove(user);
if (listUsers.size() > 0){
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),listUsers);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = listUsers;
}
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void createGroupChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
ArrayList<Integer> occupantIdsList = new ArrayList<>();
for (int i =0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
occupantIdsList.add(user.getId());
}
}
QBChatDialog dialog = new QBChatDialog();
dialog.setName(Common.createChatDialogName(occupantIdsList));
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setBody(qbChatDialog.getDialogId());
for (int i=0;i<qbChatDialog.getOccupants().size();i++) {
qbChatMessage.setRecipientId(qbChatDialog.getOccupants().get(i));
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
private void createPrivateChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
for(int i=0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
final QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
QBChatDialog dialog = DialogUtils.buildPrivateDialog(user.getId());
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Private chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setRecipientId(user.getId());
qbChatMessage.setBody(qbChatDialog.getDialogId());
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
}
}
private void retrieveAllUser() {
QBUsers.getUsers(null).performAsync(new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
QBUsersHolder.getInstance().putUsers(qbUsers);
ArrayList<QBUser> qbUserWithoutCurrent = new ArrayList<QBUser>();
for (QBUser user : qbUsers){
if (!user.getLogin().equals(QBChatService.getInstance().getUser().getLogin()))
qbUserWithoutCurrent.add(user);
}
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),qbUserWithoutCurrent);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR", e.getMessage());
}
});
}
}
ListUsersAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
public class ListUsersAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBUser> qbUserArrayList;
public ListUsersAdapter(Context context, ArrayList<QBUser> qbUserArrayList){
this.context = context;
this.qbUserArrayList = qbUserArrayList;
}
#Override
public int getCount() {
return qbUserArrayList.size();
}
#Override
public Object getItem(int position) {
return qbUserArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(android.R.layout.simple_list_item_multiple_choice,null);
TextView textView = (TextView)view.findViewById(android.R.id.text1);
textView.setText(qbUserArrayList.get(position).getLogin());
}
return view;
}
}
QBUserHolder Class
import android.util.SparseArray;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.List;
public class QBUsersHolder {
private static QBUsersHolder instance;
private SparseArray<QBUser> qbUserSparseArray;
public static synchronized QBUsersHolder getInstance(){
if (instance == null)
instance = new QBUsersHolder();
return instance;
}
private QBUsersHolder(){
qbUserSparseArray = new SparseArray<>();
}
public void putUsers(List<QBUser> users){
for (QBUser user:users)
putUser(user);
}
public void putUser(QBUser user) {
qbUserSparseArray.put(user.getId(),user);
}
public QBUser getUserById(int id){
return qbUserSparseArray.get(id);}
public List<QBUser> getUsersByIds(List<Integer> ids){
List<QBUser> qbUser = new ArrayList<>();
for(Integer id:ids) {
QBUser user = getUserById(id);
if (user != null)
qbUser.add(user);
}
return qbUser;
}
public ArrayList<QBUser> getAllUsers() {
ArrayList<QBUser> result = new ArrayList<>();
for (int i=0;i<qbUserSparseArray.size();i++)
result.add(qbUserSparseArray.valueAt(i));
return result;
}
}
By default you could retrieve only 10 users per page. You should change JSON request which retrieve users

Error inflating class fragment with supportMapFragment and fragmentactivity

This question is asked here many times,I tried all the answers but none of them worked.
I'm getting this error: Error inflating class fragment.
Mapsactivity:
package com.example.gio.autostop;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class MapsActivity extends FragmentActivity implements LocationListener,
GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener,
GoogleApiClient.ConnectionCallbacks {
public int permissionRequestCounter;
public GoogleApiClient mGoogleApiClient;
public Boolean startedLocationUpdate;
public LocationRequest locationRequest;
public Location mCurrentLocation;
public LocationManager mLocationManager;
public final static int MILISECONDS_PER_SECOND = 1000;
public final static int REQUEST_FINE_LOCATION = 0;
public final static int MINUTE = 60 * MILISECONDS_PER_SECOND;
protected String mLastUpdateTime;
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected static final String ADDRESS_REQUESTED_KEY = "address-request-pending";
protected static final String LOCATION_ADDRESS_KEY = "location-address";
protected static final String TAG = "main-activity";
public address_fragment address_fragment;
private GoogleMap mMap;// Might be null if Google Play services APK is not available.
private Button checkInButton,checkOutButton;
private ArrayList<Marker> markerCollection = new ArrayList<>();
private Marker markerForDeletion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
checkInButton = (Button) findViewById(R.id.button2);
checkOutButton=(Button)findViewById(R.id.button3);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
address_fragment address_fragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.address_fragment);
address_fragment.setMapsActivity(this);
startedLocationUpdate = false;
permissionRequestCounter = 0;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(MINUTE);
locationRequest.setFastestInterval(15 * MILISECONDS_PER_SECOND);
locationRequest.setPriority(com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
checkGps();
}
deviceUniqueNumber();
updateValuesFromBundle(savedInstanceState);
checkInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkInCurrentPosition();
checkInButton.setClickable(false);
checkOutButton.setClickable(true);
}
});
checkOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePosition();
markerForDeletion.remove();
checkOutButton.setClickable(false);
checkInButton.setClickable(true);
}
});
checkOutButton.setClickable(false);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mGoogleApiClient.isConnected() && !startedLocationUpdate)
startLocationUpdates();
}
#Override
public void onConnected(Bundle bundle) {
if (!startedLocationUpdate)
startLocationUpdates();
if (mCurrentLocation != null) {
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_SHORT).show();
return;
}
address_fragment gettingAddressFragment=(address_fragment)getSupportFragmentManager().findFragmentById(R.id.map);
if (gettingAddressFragment.mAddressRequested) {
gettingAddressFragment.startIntentService();
}
}
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
startedLocationUpdate = false;
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected() && startedLocationUpdate)
stopLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, MapsActivity.this);
startedLocationUpdate = true;
} else {
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
public void enableMyLocation() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
if (permissionRequestCounter == 0) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
permissionRequestCounter++;
}
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
if (grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocation();
checkGps();
} else {
Toast.makeText(MapsActivity.this, "Permission was blocked", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public boolean onMyLocationButtonClick() {
checkGps();
return false;
}
public void checkGps() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
address_fragment.fetchAddressHandler();
}
private void setUpMap() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse = new JSONObject(s);
boolean success = jsonResponse.getBoolean("success");
if (success) {
JSONArray jsonArray = jsonResponse.getJSONArray("data");
JSONObject jsonObject;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String mac = jsonObject.getString("mac");
String android_id = jsonObject.getString("android_id");
Double latitude = jsonObject.getDouble("latitude");
Double longitude = jsonObject.getDouble("longitude");
if (!isMarkerOnArray(markerCollection, latitude, longitude))
markerCollection.add(mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))));
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("Downloading position failed")
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DownloadPosition downloadPosition = new DownloadPosition(responseListener);
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(downloadPosition);
}
private boolean isMarkerOnArray(ArrayList<Marker> array, Double Latitude, Double Longitude) {
Marker current;
for (int c = 0; c < array.size(); c++) {
current = array.get(c);
if ((current.getPosition().latitude == Latitude) && (current.getPosition().longitude == Longitude))
return true;
}
return false;
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, startedLocationUpdate);
savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
savedInstanceState.putBoolean(ADDRESS_REQUESTED_KEY, address_fragment.mAddressRequested);
savedInstanceState.putString(LOCATION_ADDRESS_KEY, address_fragment.mAddressOutput);
super.onSaveInstanceState(savedInstanceState);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY))
startedLocationUpdate = savedInstanceState.getBoolean(REQUESTING_LOCATION_UPDATES_KEY);
if (savedInstanceState.keySet().contains(LOCATION_KEY))
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
if (savedInstanceState.keySet().contains(ADDRESS_REQUESTED_KEY)) {
address_fragment.mAddressRequested = savedInstanceState.getBoolean(ADDRESS_REQUESTED_KEY);
}
if (savedInstanceState.keySet().contains(LOCATION_ADDRESS_KEY)) {
address_fragment.mAddressOutput = savedInstanceState.getString(LOCATION_ADDRESS_KEY);
address_fragment.displayAddressOutput();
}
}
}
public void checkInCurrentPosition() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location;
long GPSLocationTime = 0;
if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if ( 0 < GPSLocationTime - NetLocationTime ) {
location=locationGPS;
}
else {
location=locationNet;
}
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
markerForDeletion=mMap.addMarker(new MarkerOptions().position(newLatLng).title(newLatLng.toString()));
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Positions position=new Positions(newLatLng.latitude,newLatLng.longitude,getWifiMacAddress(),deviceId);
Response.Listener<String> responseListener= new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UploadPosition upload=new UploadPosition(position,responseListener);
RequestQueue queue= Volley.newRequestQueue(MapsActivity.this);
queue.add(upload);
}
public void deletePosition(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
String mac=getWifiMacAddress();
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String s) {
try {
JSONObject jsonResponse= new JSONObject(s);
boolean success=jsonResponse.getBoolean("success");
if(!success){
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setMessage("uploading position failed")
.setNegativeButton("retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
DeletePosition delete=new DeletePosition(mac,deviceId,responseListener);
RequestQueue queue=Volley.newRequestQueue(MapsActivity.this);
queue.add(delete);
}
public void deviceUniqueNumber(){
String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Toast.makeText(this,deviceId+" "+getWifiMacAddress(),Toast.LENGTH_SHORT).show();
}
public static String getWifiMacAddress() {
try {
String interfaceName = "wlan0";
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (!intf.getName().equalsIgnoreCase(interfaceName)){
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null){
return "";
}
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length()>0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
} catch (Exception ex) {
Log.i("getWifiMacAddress","exception in getWifiMacAddress");
}
return "";
}
}
activity_maps.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<fragment class="com.example.gio.autostop.address_fragment"
android:id="#+id/address_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/map"
tools:context="com.example.gio.autostop.MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment"
>
<include layout="#layout/map_interface"/>
</fragment>
</LinearLayout>
address_fragment.java:
package com.example.gio.autostop;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
public class address_fragment extends Fragment {
protected TextView mLocationAddressTextView;
protected String mAddressOutput;
private AddressResultReceiver mResultReceiver;
private ProgressBar mProgressBar;
protected boolean mAddressRequested;
private MapsActivity mapsActivity;
public address_fragment() {
// Required empty public constructor
}
class AddressResultReceiver extends ResultReceiver{
private int CREATOR;
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
mAddressRequested = false;
updateUIWidgets();
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_address_fragment, container, false);
}
public void setMapsActivity(MapsActivity mapsActivity){
this.mapsActivity=mapsActivity;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("mAddressOutput",mAddressOutput);
outState.putBoolean("mAddressRequested",mAddressRequested);
}
#Override
public void onStart() {
super.onStart();
View view = getView();
if(view!=null){
mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
mLocationAddressTextView=(TextView) view.findViewById(R.id.address);
displayAddressOutput();
}
}
public void displayAddressOutput(){
mLocationAddressTextView.setText(mAddressOutput);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mResultReceiver = new AddressResultReceiver(new Handler());
mAddressRequested = false;
mAddressOutput = " ";
updateUIWidgets();
}
public void startIntentService() {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mapsActivity.mCurrentLocation);
mapsActivity.startService(intent);
}
public void fetchAddressHandler() {
if (mapsActivity.mGoogleApiClient.isConnected() && mapsActivity.mCurrentLocation != null) {
startIntentService();
}
mAddressRequested = true;
updateUIWidgets();
}
private void updateUIWidgets() {
if (mAddressRequested) {
mProgressBar.setVisibility(ProgressBar.VISIBLE);
} else {
mProgressBar.setVisibility(ProgressBar.GONE);
}
}
}
fragment_address_fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gio.autostop.address_fragment"
android:background="#android:color/transparent">
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text=""
android:layout_centerHorizontal="true"
android:textSize="22sp"/>
</FrameLayout>
map_interface.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_in"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_alignParentBottom="true"
android:layout_weight="1"
/>
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check_out"
android:layout_marginTop="#dimen/layout_marginTop_button"
android:layout_gravity="end"
android:layout_weight="1"
/>
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>
what is causing error?
update:
full project: https://github.com/giusha/Autostop
Perhaps the "Error inflating fragment" message is misleading somewhat - but a closer examination of your error stacktrace shows that it is caused by NullPointerException (because you are calling mProgressBar.setVisibility) whereas mProgressBar is actually NULL - because you assigned it to view.findViewById(R.id.progress_bar); which returns null because the view R.id.progress_bar does not exist in the layout file (fragment_address_fragment). So my suggestion would be to move :
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
into the fragment_address_fragment layout file - and then run your code again and see if it works.

my In app billing dialog disapears when i tap outside it

I have made a demo in app purchase for android,I have created a test product and purchase it for testing purpose,all is working very fine,But Only issue is when i tap outside the in app billing Dialog,it disappears,I want to do something like "setCancellable(false)" on it,Please suggest me,I need help,My code is as below:
code
package com.medicineqod.activity;
import inapUtils.IabHelper;
import inapUtils.IabHelper.OnConsumeFinishedListener;
import inapUtils.IabHelper.OnIabPurchaseFinishedListener;
import inapUtils.IabHelper.OnIabSetupFinishedListener;
import inapUtils.IabHelper.QueryInventoryFinishedListener;
import inapUtils.IabResult;
import inapUtils.Inventory;
import inapUtils.Purchase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.drm.DrmStore.ConstraintsColumns;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.medicineqod.FragmentAbstractActivity;
import com.medicineqod.R;
import com.medicineqod.DBAdapter.DataBaseHelper;
import com.medicineqod.model.Question;
import com.medicineqod.utility.CommonVariables;
/**
* Created by basheer on 4/26/14.
*/
public class QuestionOFDayActivity extends FragmentAbstractActivity
/* OnIabSetupFinishedListener, OnIabPurchaseFinishedListener */{
// When requested, this adapter returns a WallpaperCollectionFragment,
// representing an object in the collection.
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
ImageView btnNext, btnPrev;
static TextView tvError;
TextView tvDate;
TextView btnHome;
TextView tvTitle;
int mTotalCount;
int mPosition = 0;
int mActivity = 0;
ArrayList<Question> qusList = new ArrayList<Question>();
// edited by jigar
private static final String TAG = "com.medicineqod.inappbilling";
static IabHelper mHelper;
static final String ITEM_SKU = "com.medicineqod.product.one";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizoftheday);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
// Edited by jigar,....
showCustomeAlertValidation(QuestionOFDayActivity.this);
DataBaseHelper bBase = new DataBaseHelper(this);
mActivity = getIntent().getIntExtra(CommonVariables.ACTIVITY, 0);
if (mActivity == CommonVariables.FavQusAct) {
qusList = bBase.getFavQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.PastQusAct) {
qusList = bBase.getPastQuestions();
mTotalCount = qusList.size();
} else if (mActivity == CommonVariables.QusOfTheDay) {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
} else {
qusList = bBase.getQuestions();
mTotalCount = qusList.size();
}
if (qusList.size() == 0) {
return;
}
mPosition = getIntent().getIntExtra("postion", 0);
Collections.reverse(qusList);
if (mPosition == -1) {
mPosition = qusList.size() - 1;
}
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(mPosition);
tvError = (TextView) findViewById(R.id.error_tv);
tvDate = (TextView) findViewById(R.id.topbar_date_tv);
tvTitle = (TextView) findViewById(R.id.topbar_title_tv);
btnNext = (ImageView) findViewById(R.id.bottom_next_img);
btnPrev = (ImageView) findViewById(R.id.bottom_prev_img);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTotalCount - 1 > mPosition) {
mPosition++;
mViewPager.setCurrentItem(mPosition);
}
}
});
btnPrev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (0 < mPosition) {
mPosition--;
mViewPager.setCurrentItem(mPosition);
}
}
});
mViewPager
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mPosition = position;
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
tvDate.setText("" + qusList.get(position).getDate());
setTiltle(qusList.get(mPosition).getDate());
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
tvDate.setText("" + qusList.get(mPosition).getDate());
setTiltle(qusList.get(mPosition).getDate());
btnHome = (TextView) findViewById(R.id.topbar_left_tv);
if (mActivity == CommonVariables.FavQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.PastQusAct) {
btnHome.setText("Back");
btnHome.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_back,
0, 0, 0);
} else if (mActivity == CommonVariables.QusOfTheDay) {
// btnHome.setText("Back");
// btnHome.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
// null);
}
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
}
});
// System.out.println(mPosition + "::::" + (mTotalCount - 1));
if (qusList.size() == 0 || qusList.size() == 1) {
btnPrev.setVisibility(View.INVISIBLE);
btnNext.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
private void setTiltle(String date) {
if (mActivity == CommonVariables.FavQusAct) {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_fav_qus));
} else if (getCurrentDate().equals(date)) {
tvTitle.setText(""
+ getApplication().getResources().getString(R.string.qod));
} else {
tvTitle.setText(""
+ getApplication().getResources().getString(
R.string.title_past_qus));
}
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
fragment = new QuizCollectionFragment();
Bundle args = new Bundle();
args.putSerializable(QuizCollectionFragment.ARG_OBJECT,
(Serializable) qusList.get(position));
args.putInt(QuizCollectionFragment.QUZI_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return mTotalCount;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return "good".toUpperCase(l);
}
}
public void setOnAnswer(String mPerformance, String mAswerView,
String mAswerQue, String mFavourite, int mPosition,
String mPercentage) {
if (qusList.size() > 0 && mPosition < qusList.size()) {
Question mQuizQuestion = qusList.get(mPosition);
mQuizQuestion.setAnsque(mAswerQue);
mQuizQuestion.setPerformance(mPerformance);
mQuizQuestion.setAnsview(mAswerView);
mQuizQuestion.setFavourite(mFavourite);
mQuizQuestion.setPercentage(mPercentage);
qusList.set(mPosition, mQuizQuestion);
}
}
public void refreshTheViewPage(int position) {
if (mActivity == CommonVariables.FavQusAct) {
tvDate.setText("");
qusList.remove(mPosition);
mTotalCount = qusList.size();
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setAdapter(mSectionsPagerAdapter);
if (mTotalCount - 1 < mPosition) {
mPosition = mTotalCount - 1;
}
mViewPager.setCurrentItem(mPosition);
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
if (qusList.size() == 0 || qusList.size() == 1) {
btnNext.setVisibility(View.INVISIBLE);
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == 0) {
btnPrev.setVisibility(View.INVISIBLE);
} else if (mPosition == mTotalCount - 1) {
btnNext.setVisibility(View.INVISIBLE);
} else {
btnNext.setVisibility(View.VISIBLE);
btnPrev.setVisibility(View.VISIBLE);
}
}
}
// Popup of subscribing app..
public void showCustomeAlertValidation(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
final Button btn_subscribe = (Button) dialog
.findViewById(R.id.btn_subscribe);
btn_subscribe.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Subscribing code here...!!!
mHelper.launchPurchaseFlow(QuestionOFDayActivity.this,
ITEM_SKU, 10001, mPurchaseFinishedListener,
"mypurchasetoken");
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
String base64EncodedPublicKey = "MIIBIjANyOvuqXSF8qd4NAapQdRohAajUA3/N/L9XoD21B7lVqZnICXh1dFEnnVvNyhK+ws1Cr5YsPvIAprHvsQNJ2xtEGypNivk/AA6N91OY0r2dtZJZHGpSxDSsfHTfKk5/4CaW1itbdIo+JiGTieJyHIvMFdWSkLqaxR3JWy+0KwTHvzMrR15oClM9v8fKjNT6M8qxlhnyzLDd7G2/ifBIPTJjfdvWHoXaP/rHa2MbN2acPwvbbwIDAQAB";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
} else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
System.out
.println(":::::::::::::::::::::Purchase consumed successfuly::::::::::::::::::::");
}
}
};
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess()) {
System.out
.println("::::::::::::::::::::::::Purchase consumehas been finished successfully:::::::::::::::::::::");
} else {
// handle error
System.out
.println("::::::::::::::::::::::::Purchase consumehas failed:::::::::::::::::::::");
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mHelper != null)
mHelper.dispose();
mHelper = null;
}
}
this is what you need to do in order to ristrict that.
dialog.setCanceledOnTouchOutside(false);
this will make sure dialog is not dismissed when touched outside of dialog box area.

Categories

Resources