Pass List<> to a Fragment - java

I'm creating an Android map app by getting venue from Foursquare and using Google Map.
I have set my MainActivity to get the venue results, a MapFragmentClass and a VenueModel.
I keep all the JSON result from Foursquare into a List venueModelList in the MainActivity.
What I want to do is to add markers in the MapFragmentClass based on the coordinates received from Foursquare.
However, I am stuck trying to pass the venueModelList to the MapFragmentClass.
Any help is appreciated. Thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
private final String VENUE_URL = "https://api.foursquare.com/v2/venues/search?ll=";
private final int LIMIT = 40;
private final double RADIUS = 50000;
private String MOSQUE_URL;
private String RES_URL;
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
private static final long MIN_TIME_BW_UPDATES = 20000;
private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private LocationManager locationManager;
private Location lastLocation;
private Location location;
private boolean receivedLocation = false;
private double lt;
private double lg;
private boolean canGetLocation;
private boolean isGPSEnabled;
private boolean isNetworkEnabled;
private boolean updateSettings = false;
private String TAG = "TAG";
private ListView lvVenues;
private Bundle bundle;
private ArrayList<VenueModel> venueModelList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvVenues = (ListView) findViewById(R.id.lvVenues);
String t = timeMilisToString(System.currentTimeMillis());
Bundle extras = getIntent().getExtras();
if (extras != null)
{
lt = extras.getDouble("LATITUDE");
lg = extras.getDouble("LONGITUDE");
receivedLocation = true;
}
else
{
receivedLocation = false;
}
location = getLocation();
if (location != null)
{
if(receivedLocation)
{
location.setLatitude(lt);
location.setLongitude(lg);
}
else
{
lt = location.getLatitude();
lg = location.getLongitude();
Log.d("LAT", "Latitude: " + lt);
Log.d("LONG", "Longitude: " + lg);
}
}
double lt = 3.142182;
double lg = 101.710602;
MOSQUE_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=4bf58dd8d48988d138941735"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
RES_URL = VENUE_URL + lt + "," + lg
+ "&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET
+ "&v=" + t
+ "&categoryId=52e81612bcbc57f1066b79ff"
+ "&radius=" + RADIUS
+ "&limit=" + LIMIT;
}
public class JSONTask extends AsyncTask<String, String, List<VenueModel>>
{
#Override
public List<VenueModel> doInBackground(String... params)
{
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondObject = parentObject.getJSONObject("response");
JSONArray parentArray = secondObject.getJSONArray("venues");
venueModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++)
{
JSONObject finalObject = parentArray.getJSONObject(i);
JSONObject thirdObject = finalObject.getJSONObject("location");
try {
VenueModel venueModel = new VenueModel();
venueModel.setId(finalObject.getString("id"));
venueModel.setName(finalObject.getString("name"));
venueModel.setAddress(thirdObject.optString("address"));
venueModel.setPostalCode(thirdObject.optString("postalCode"));
venueModel.setCity(thirdObject.optString("city"));
venueModel.setState(thirdObject.optString("state"));
venueModel.setDistance(thirdObject.getInt("distance"));
venueModel.setLat(thirdObject.getDouble("lat"));
venueModel.setLng(thirdObject.getDouble("lng"));
LatLng coordinate = new LatLng(thirdObject.getDouble("lat"), thirdObject.getDouble("lng"));
venueModel.setCoordinate(coordinate);
venueModelList.add(venueModel);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Collections.sort(venueModelList);
return venueModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<VenueModel> result)
{
super.onPostExecute(result);
VenueAdapter adapter = new VenueAdapter(getApplicationContext(), R.layout.row, result);
lvVenues.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_mosque)
{
new JSONTask().execute(MOSQUE_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
if (id == R.id.action_restaurant)
{
new JSONTask().execute(RES_URL);
FragmentManager fmanager = getSupportFragmentManager();
FragmentTransaction FT = fmanager.beginTransaction();
MapFragmentClass mfc = new MapFragmentClass();
FT.add(R.id.mapLayout, mfc);
FT.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
private String timeMilisToString(long milis)
{
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milis);
return sd.format(calendar.getTime());
}
public Location getLocation()
{
try
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
Log.v(TAG, "No network provider enabled");
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "Network Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d(TAG, "GPS Enabled");
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider)
{
Log.v(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider)
{
Log.v(TAG, "onProviderDisabled");
}
public LatLng setCoordinate()
{
LatLng coordinate = new LatLng(getLocation().getLatitude(), getLocation().getLongitude());
LatLng coordinate = new LatLng(lt, lg);
return coordinate;
}
}
VenueModel.java
public class VenueModel implements Comparable<VenueModel>, Parcelable
{
private String id;
private String name;
private String address;
private String postalCode;
private String city;
private String state;
private Integer distance;
private double lat;
private double lng;
private LatLng coordinate;
private List<VenueModel> venueModelList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public void setVenueModelList(List<VenueModel> venueModelList)
{
this.venueModelList = venueModelList;
}
public List<VenueModel> getVenueModelList()
{
return venueModelList;
}
public LatLng getCoordinate() {
return coordinate;
}
public void setCoordinate(LatLng coordinate)
{
this.coordinate = coordinate;
}
#Override
public int compareTo(VenueModel venueModel) {
return this.distance.compareTo(venueModel.distance);
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.postalCode);
dest.writeString(this.city);
dest.writeString(this.state);
dest.writeValue(this.distance);
dest.writeDouble(this.lat);
dest.writeDouble(this.lng);
dest.writeParcelable(this.coordinate, flags);
dest.writeList(this.venueModelList);
}
public VenueModel() {
}
protected VenueModel(Parcel in) {
this.id = in.readString();
this.name = in.readString();
this.address = in.readString();
this.postalCode = in.readString();
this.city = in.readString();
this.state = in.readString();
this.distance = (Integer) in.readValue(Integer.class.getClassLoader());
this.lat = in.readDouble();
this.lng = in.readDouble();
this.coordinate = in.readParcelable(LatLng.class.getClassLoader());
this.venueModelList = new ArrayList<VenueModel>();
in.readList(this.venueModelList, VenueModel.class.getClassLoader());
}
public static final Parcelable.Creator<VenueModel> CREATOR = new Parcelable.Creator<VenueModel>() {
#Override
public VenueModel createFromParcel(Parcel source) {
return new VenueModel(source);
}
#Override
public VenueModel[] newArray(int size) {
return new VenueModel[size];
}
};
}
MapFragmentClass.java
public class MapFragmentClass extends Fragment implements OnMapReadyCallback
{
private MainActivity mA;
private GoogleMap gmap;
private static final LatLng coordinate = new LatLng(3.152182, 101.710602);
private LatLng coordinate2;
private ArrayList<VenueModel> venueModelList;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
gmap = googleMap;
gmap.addMarker(new MarkerOptions().position(coordinate).title("Your location").draggable(true));
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 14));
}
}

Convert that Object to JSON string using GSON and then reconvert that string again to Object of list again.
MapFragment.getInstance(new Gson().toJson(venuList));
public static final getInstance(String venusStringListObj) {}
Bundle argument = new Bundle();
argument.putString("VENUES", venusStringListObj);
MapFragment fragment = new MapFragment();
fragment.setArgument(argument);
return fragment;
}
onCreate(...) {
private List<VenueModel> venueList;
Type listType = new TypeToken<ArrayList<VenueModel>>() {}.getType();
String venueStringRecvFromFragArg = getArguments().getString("VENUES");
venueList = new Gson().fromJson(venueStringRecvFromFragArg, listType);
}

MapFragmentClass mfc = new MapFragmentClass();
Bundle b = new Bundle();
b.putParcelableArrayList("Parcel", list);
mfc.setArguments(b);
FT.add(R.id.mapLayout, mfc);
FT.commit();
To access arrayList in MapFragment use this
ArrayList<VenueModel> myList = getArguments().getParcelableArrayList("Parcel");

Related

How to save like button state in android?

I am using jd-alexander/LikeButton https://github.com/jd-alexander/LikeButton instead of normal buttons in the android app. The code works fine while enabling and disabling switches. But I want to save the state of the like button. Suppose I enable the like button and swap the list the background code will run fine but the like button state will change to unliked.
Every time when I swap the list the like button state becomes unliked. Is there any way to save the like button State??
Activity codes:
public class CollectorListAdapter extends ArrayAdapter<Collector> {
private static final String TAG = "CollectorListAdapter";
private Context mContext;
private int mResource;
public CollectorListAdapter(Context context, int resource, ArrayList<Collector> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
public View getView(final int position, View convertView, ViewGroup parent) {
//Get the Shop information
String Shopname = getItem(position).getName();
String Specialoffers = getItem(position).getSpecialoffers();
int Price = getItem(position).getPrice();
final Double startLatitude = getItem(position).getLatitude();
final Double startLongitude = getItem(position).getLongitude();
final String user_id = String.valueOf(getItem(position).getUserid());
final String shop_id = String.valueOf(getItem(position).getShopid());
final String product_id = String.valueOf(getItem(position).getProductid());
//create the view result for showing the animation
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView sname = (TextView) convertView.findViewById(R.id.textView);
TextView tvname = (TextView) convertView.findViewById(R.id.textView7);
TextView Location = (TextView) convertView.findViewById(R.id.textView9);
TextView tvdescription = (TextView) convertView.findViewById(R.id.textView10);
sname.setText(Shopname);
tvdescription.setText(Specialoffers);
tvname.setText(CurrencyFormatting(Integer.toString(Price)) + " EGP");
Location.setText(format(results[0]) + " km");
LikeButton heart;
heart = convertView.findViewById(R.id.favBtn);
heart.setOnLikeListener(new OnLikeListener() {
// Add Data to the Saved Shop Table by like
#Override
public void liked(LikeButton likeButton) {
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq);
Toast.makeText(getContext(),
"Shop Saved Successfully", Toast.LENGTH_LONG).show();
}
// Delete Data to the Saved Shop Table by Unlike
#Override
public void unLiked(LikeButton likeButton) {
StringRequest strReq10 = new StringRequest(Request.Method.POST, AppConfig.URL_Delete_SAVED_SHOPS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("shop_id", shop_id);
params.put("product_id", product_id);
return params;
}
};
Volley.newRequestQueue(getContext()).add(strReq10);
Toast.makeText(getContext(),
"Shop Saved Deleted Successfully", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Collector Class:
public class Collector implements java.io.Serializable {
private String specialoffers, name;
private Double latitude, longitude;
private int price,userid,shopid,productid;
public Collector() {
}
//Sorting by Price method
public static Comparator<Collector> PriceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
int rollno1 = s1.getPrice();
int rollno2 = s2.getPrice();
/*For ascending order*/
return rollno1 - rollno2;
/*For descending order*/
//rollno2-rollno1;
}
};
//Sorting by Distance method
public static Comparator<Collector> DistanceSort = new Comparator<Collector>() {
public int compare(Collector s1, Collector s2) {
float[] results1 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s1.getLatitude(),
s1.getLongitude(),
results1);
float[] results2 = new float[3];
Location.distanceBetween(
LocationActivity.currentLocation.getLatitude(),
LocationActivity.currentLocation.getLongitude(),s2.getLatitude(),
s2.getLongitude(),
results2);
/*For ascending order*/
return Float.compare(results1[0], results2[0]);
/*For descending order*/
//rollno2-rollno1;
}
};
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getShopid() {
return shopid;
}
public void setShopid(int shopid) {
this.shopid = shopid;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public String toString() {
return ("Shop Name:" + getName() +
" Price : " + getPrice() +
" SpecialOffers : " + getSpecialoffers() +
" latitude : " + getLatitude()) +
" longitude : " + getLongitude();
}
public String getSpecialoffers() {
return specialoffers;
}
public void setSpecialoffers(String specialoffers) {
this.specialoffers = specialoffers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
This is the normal behaviour in ArrayAdapter, the whole list gets recreated again so you lose the state of the button. You should save the boolean of the button in the local list variable.
Add a field like isLiked = true/false in the Collector class and update the value at the particular position every time user click like/unlike buttons.

NullPointerException whiling trying to cluster markers google maps [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm building a map on my app and everything works fine until I add my ClusterItem to my ClusterManager throwing the exception:
Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.longitude' on a null object reference
public class MapaActivity extends FragmentActivity implements OnMapReadyCallback {
BancoDadosController bancoDadosController;
private List<Obra> listaPlot;
private String numObra, numeroObra, tipoObra, descricao;
private double latitude;
private double longitude;
private String geoPonto;
private GoogleMap gMap;
private LatLng pontoFinal;
private ClusterManager<ItemCluster> mClusterManager;
private ItemCluster itemCluster;
private SharedPreferences pegaIdJurisdicionado;
private static final String USER_AUTH = "Autentication";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
bancoDadosController = new BancoDadosController(this);
pegaIdJurisdicionado = getSharedPreferences(USER_AUTH,0);
String idJurisdicionado = pegaIdJurisdicionado.getString("idJurisdicionado", null);
listaPlot = bancoDadosController.buscarListaMapa("3", "5527");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapaDespesa);
mapFragment.getMapAsync(this);
}
private void setUpClusterer(GoogleMap googleMap) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-7.116289, -34.850414), 4.5f));
mClusterManager = new ClusterManager<ItemCluster>(this, googleMap);
mClusterManager.setRenderer(new IconePersonalizado(MapaActivity.this, googleMap,mClusterManager));
final IconePersonalizado iconePersonalizado = new IconePersonalizado(this,gMap,mClusterManager);
mClusterManager.setRenderer(iconePersonalizado);
mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(new InfoWindowMapa(LayoutInflater.from(this)));
gMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
googleMap.setOnCameraIdleListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
googleMap.setOnInfoWindowClickListener(mClusterManager);
addItemsCluster();
}
private void addItemsCluster() {
for (int i = 0; i < listaPlot.size(); i++) {
geoPonto = listaPlot.get(i).getGeoReferenciamento();
pontoFinal = tratamentoGeoPonto(geoPonto);
numObra = listaPlot.get(i).getNumeroObra();
tipoObra = listaPlot.get(i).getTipoObra();
descricao = listaPlot.get(i).getDescricaoObra();
itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
try{
mClusterManager.addItem(itemCluster);
}catch (NullPointerException e){
Log.d("Andre", String.valueOf(itemCluster.getPosition()));
e.printStackTrace();
}
}
}
private LatLng tratamentoGeoPonto(String valor){
String geoPontoFormatado = "";
geoPontoFormatado = valor.substring(1, (valor.length()-1));
String[] pontos = geoPontoFormatado.split(",");
double lat = Double.parseDouble(pontos[0]);
double lngt = Double.parseDouble(pontos[1]);
LatLng pontoTratado = new LatLng(lat, lngt);
return pontoTratado;
}
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.getUiSettings().setRotateGesturesEnabled(false);
gMap.getUiSettings().setZoomControlsEnabled(true);
setUpClusterer(gMap);
mClusterManager.setOnClusterItemInfoWindowClickListener(new ClusterManager.OnClusterItemInfoWindowClickListener<ItemCluster>() {
#Override
public void onClusterItemInfoWindowClick(ItemCluster itemCluster) {
numeroObra = itemCluster.getNumeroObra();
Intent passarObra = new Intent(MapaActivity.this,CardObraActivity.class);
passarObra.putExtra("obraDigitada",numeroObra);
startActivity(passarObra);
}
});
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<ItemCluster>() {
#Override
public boolean onClusterItemClick(ItemCluster itemCluster) {
return false;
}
});
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener<ItemCluster>() {
#Override
public boolean onClusterClick(Cluster<ItemCluster> cluster) {
float teste = gMap.getCameraPosition().zoom;
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(teste+6).build();
gMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
return false;
}
});
}
}
And here is my ClusterItem class:
public class ItemCluster implements ClusterItem{
private LatLng mPosition;
private String numeroObra;
private String descricao;
private String tipoObra;
public ItemCluster(LatLng mPosition, String numeroObra, String descricao, String tipoObra) {
this.mPosition = mPosition;
this.numeroObra = numeroObra;
this.descricao = descricao;
this.tipoObra = tipoObra;
}
public LatLng getmPosition() {
return mPosition;
}
public String getNumeroObra() {
return numeroObra;
}
public String getDescricao() {
return descricao;
}
public String getTipoObra() {
return tipoObra;
}
#Override
public LatLng getPosition() {
return null;
}
#Override
public String getTitle() {
return null;
}
#Override
public String getSnippet() {
return null;
}
}
all my variables have values and it's all ok until reach on this function
private void addItemsCluster() {
for (int i = 0; i < listaPlot.size(); i++) {
geoPonto = listaPlot.get(i).getGeoReferenciamento();
pontoFinal = tratamentoGeoPonto(geoPonto);
numObra = listaPlot.get(i).getNumeroObra();
tipoObra = listaPlot.get(i).getTipoObra();
descricao = listaPlot.get(i).getDescricaoObra();
itemCluster = new ItemCluster(pontoFinal, numObra, tipoObra, descricao);
try{
mClusterManager.addItem(itemCluster);
}catch (NullPointerException e){
Log.d("Andre", String.valueOf(itemCluster.getPosition()));
e.printStackTrace();
}
}
}
And that's my Select function to return my list to plot the map
public List<Obra> buscarListaMapa(String tipoGeoReferenciamentoFiltro, String idJurisdicionadoFiltro) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + BancoDadosHelper.TABELA_OBRA + " WHERE "+ BancoDadosHelper.COLUNA_ID_TIPO_GEOREFERENCIAMENTO + " = '"+tipoGeoReferenciamentoFiltro+"' and "+
BancoDadosHelper.COLUNA_ID_JURISDICIONADO+" = '"+idJurisdicionadoFiltro+"'", null);
List<Obra> listaMapa = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
String numObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_NUM_OBRA));
String descObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_DESCRICAO_OBRA));
String geoReferenciamento = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_GEOREFERENCIAMENTO));
String tipoObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_TIPO_OBRA));
Obra novaObra = new Obra(numObra, descObra, tipoObra, geoReferenciamento);
listaMapa.add(novaObra);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return listaMapa;
}
The problem may be in your ItemCluster.class, In your case getPosition() returns null.
#Override
public LatLng getPosition() {
return new LatLng(getSLatitude(), getSLongitude());
}

How do you do pojo with asynctask json

I take https://jsonplaceholder.typicode.com/users with asynctask but i take to use pojo object .
What should I add code between ? What line should I write and how should i write ?
DataRetriever.java
public DataRetriever(Activity activity) {
activityWeakReference = new WeakReference<>(activity);
current_activity = activityWeakReference.get();
}
#Override
protected void onPreExecute() {
imageView = (ImageView) current_activity.findViewById(R.id.imageView);
if (current_activity != null) {
recyclerView = (RecyclerView) current_activity.findViewById(R.id.recyclerView);
swipeRefreshLayout = (SwipeRefreshLayout) current_activity.findViewById(R.id.swipe_container);
swipeRefreshLayout.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);
recyclerView.setHasFixedSize(true);
} else {
Log.d(TAG, "unable to get current activity");
Toast.makeText(current_activity, "unable to get current activity", Toast.LENGTH_SHORT).show();
}
super.onPreExecute();
progressDialog = new ProgressDialog(current_activity);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#SafeVarargs
#Override
protected final Integer doInBackground(List<String>... integers) {
HttpURLConnection httpURLConnection = null;
URL url;
List<String> local_list = integers[0];
type = Integer.parseInt(local_list.get(0));
String jsonString, jsonData;
return_status = 0;
switch (type) {
case 1:
url_string = "https://jsonplaceholder.typicode.com/users";
break;
case 2:
url_string = "https://jsonplaceholder.typicode.com/albums";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
case 3:
url_string = "https://jsonplaceholder.typicode.com/photos";
recieved_id = Integer.parseInt(local_list.get(1));
title = local_list.get(2);
break;
}
try {
url = new URL(url_string);
httpURLConnection = (HttpURLConnection) url.openConnection();
int statusCode = httpURLConnection.getResponseCode();
if (statusCode == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((jsonData = bufferedReader.readLine()) != null) {
stringBuilder.append(jsonData);
}
jsonString = stringBuilder.toString();
jsonParser(jsonString);
return_status = 1;
} else {
Log.d(TAG, "Some error occurred could'nt fetch data");
Toast.makeText(current_activity, "Some error occurred could'nt fetch data", Toast.LENGTH_SHORT).show();
return_status = 0;
}
publishProgress(local_list);
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return return_status;
}
private void jsonParser(String jsonString) {
int names_count, id;
String name;
try {
JSONArray jsonArray = new JSONArray(jsonString);
names_count = jsonArray.length();
if (!listValues.isEmpty())
listValues.clear();
if (!pictureValues.isEmpty())
pictureValues.clear();
for (int i = 0; i < names_count; i++) {
JSONObject array_items = jsonArray.getJSONObject(i);
ListValues jsonValues, pictureValue;
switch (type) {
case 1:
id = array_items.optInt("id");
name = array_items.optString("name");
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
break;
case 2:
id = array_items.optInt("userId");
name = array_items.optString("title");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
listValues.add(jsonValues);
}
break;
case 3:
id = array_items.optInt("albumId");
name = array_items.optString("title");
String pictureURL = array_items.getString("url");
if (id == recieved_id) {
jsonValues = new ListValues(id, name);
pictureValue = new ListValues(id, pictureURL);
listValues.add(jsonValues);
pictureValues.add(pictureValue);
}
break;
}
}
} catch (JSONException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
#Override
protected void onProgressUpdate(final List<String>... values) {
List<String> progressList = values[0];
Log.d(TAG, progressList.get(0));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
switch (type) {
case 1:
new DataRetriever(current_activity).execute(values[0]);
case 2:
new DataRetriever(current_activity).execute(values[0]);
case 3:
new DataRetriever(current_activity).execute(values[0]);
}
}
});
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(final Integer integer) {
if (integer != 0) {
recyclerAdapter = new RecyclerAdapter(listValues);
recyclerView.addItemDecoration(new ListItemDecorator(current_activity.getApplicationContext()));
recyclerView.setAdapter(recyclerAdapter);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(current_activity);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
if (swipeRefreshLayout.isRefreshing())
swipeRefreshLayout.setRefreshing(false);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(current_activity.getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
String pictureURL = null;
ListValues feed = listValues.get(position);
if (!pictureValues.isEmpty()) {
ListValues feed2 = pictureValues.get(position);
pictureURL = feed2.getValue();
}
String value = feed.getValue();
switch (type) {
case 1:
intent = new Intent(current_activity, AlbumActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 2:
intent = new Intent(current_activity, PhotosActivity.class);
intent.putExtra("id", (position + 1));
intent.putExtra("value", value);
current_activity.startActivity(intent);
break;
case 3:
intent = new Intent(current_activity, ImageDisplay.class);
intent.putExtra("imageUrl", pictureURL);
current_activity.startActivity(intent);
break;
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
} else {
// Log.d(TAG, "unable to get data");
if (swipeRefreshLayout.isRefreshing()) {
Toast.makeText(current_activity, "Unable to refresh data! Try opening application again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(current_activity, "Failed to fetch data! try again", Toast.LENGTH_SHORT).show();
}
}
super.onPostExecute(integer);
progressDialog.dismiss();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Post.java
public class Post implements Serializable {
#SerializedName("userId")
private int userId;
#SerializedName("name")
#Expose
public String name;
#SerializedName("id")
private int id;
#SerializedName("title")
private String title;
#SerializedName("body")
private String body;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Your important advice for me
Thank you!
You can easily do that with GSON and POJO
first.. you need to create several model
Post.java
public class Post
{
private String id;
private String phone;
private String username;
private String website;
private Address address;
private String email;
private Company company;
private String name;
//setter and getter
}
Company.java
public class Company
{
private String catchPhrase;
private String name;
private String bs;
//setter and getter
}
Address.java
public class Address
{
private Geo geo;
private String zipcode;
private String street;
private String suite;
private String city;
//setter and getter
}
Geo.java
public class Geo
{
private String lng;
private String lat;
//setter and getter
}
After that, json string you get from the API. parse it using Gson..
List<Post> post = new Gson().fromJson(YOUR_JSON_STRING,new TypeToken<List<Post>>() {}.getType());

How to handle java.lang.NumberFormatException: Invalid double: "" error in Android Studio?

I'm trying to run an application and it crashes because of this error:
FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 4201
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""
It had some Gradle errors, but I had solved them, and now it still crashed when I tried to run the app. It looks like that problem is in the class below, at line 252. Tried everything possible to check data and to solve this error, but nothing so far. What should I do? Thanks!
CitiesListFragment:
public class CitiesListFragment extends Fragment {
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Variables
//-------------------------------------------------------------------------------------------------------------------------------------
private RecyclerView mRecyclerView;
private ProgressWheel progressWheel;
private CityAdapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private TextView display_message;
private ArrayList<PCityData> pCityDataList;
private ArrayList<PCityData> pCityDataSet;
private NestedScrollView singleLayout;
private TextView scCityName;
private TextView scCityLocation;
private TextView scCityAbout;
private TextView scCityCatCount;
private TextView scCitySubCatCount;
private TextView scCityItemCount;
private ImageView scCityPhoto;
private Button scCityExplore;
private String jsonStatusSuccessString;
private String connectionError;
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Public Variables
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
public CitiesListFragment() {
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cities_list, container, false);
initUI(view);
initData();
return view;
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initUI(View view){
initSingleUI(view);
initSwipeRefreshLayout(view);
initProgressWheel(view);
initRecyclerView(view);
startLoading();
}
private void initSingleUI(View view) {
singleLayout =(NestedScrollView) view.findViewById(R.id.single_city_layout);
scCityName = (TextView) view.findViewById(R.id.sc_city_name);
scCityLocation = (TextView) view.findViewById(R.id.sc_city_loc);
scCityAbout = (TextView) view.findViewById(R.id.sc_city_desc);
scCityCatCount = (TextView) view.findViewById(R.id.txt_cat_count);
scCitySubCatCount = (TextView) view.findViewById(R.id.txt_sub_cat_count);
scCityItemCount = (TextView) view.findViewById(R.id.txt_item_count);
scCityPhoto = (ImageView) view.findViewById(R.id.sc_city_photo);
scCityExplore = (Button) view.findViewById(R.id.button_explore);
int screenWidth = Utils.getScreenWidth();
int rlWidth = (screenWidth/3) - 20;
RelativeLayout r1 = (RelativeLayout) view.findViewById(R.id.rl_count1);
RelativeLayout r2 = (RelativeLayout) view.findViewById(R.id.rl_count2);
RelativeLayout r3 = (RelativeLayout) view.findViewById(R.id.rl_count3);
r1.setMinimumWidth(rlWidth);
r2.setMinimumWidth(rlWidth);
r3.setMinimumWidth(rlWidth);
scCityPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
scCityExplore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
}
private void initSwipeRefreshLayout(View view) {
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
requestData(Config.APP_API_URL + Config.GET_ALL);
}
});
}
private void initProgressWheel(View view) {
progressWheel = (ProgressWheel) view.findViewById(R.id.progress_wheel);
}
private void initRecyclerView(View view) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(llm);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setVisibility(view.GONE);
pCityDataSet = new ArrayList<>();
adapter = new CityAdapter(getActivity(), pCityDataSet);
mRecyclerView.setAdapter(adapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initData(){
requestData(Config.APP_API_URL + Config.GET_ALL);
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
connectionError = getResources().getString(R.string.connection_error);
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals(jsonStatusSuccessString)) {
progressWheel.setVisibility(View.GONE);
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
Utils.psLog("City Count : " + pCityDataList.size());
if(pCityDataList.size() > 1) {
singleLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
updateDisplay();
}else{
mRecyclerView.setVisibility(View.GONE);
singleLayout.setVisibility(View.VISIBLE);
stopLoading();
updateSingleDisplay();
}
updateGlobalCityList();
} else {
stopLoading();
Utils.psLog("Error in loading CityList.");
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading CityList.", e);
stopLoading();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
progressWheel.setVisibility(View.GONE);
stopLoading();
/* NetworkResponse response = ex.networkResponse;
if (response != null && response.data != null) {
} else {*/
try {
display_message.setVisibility(View.VISIBLE);
display_message.setText(connectionError);
}catch (Exception e){
Utils.psErrorLogE("Error in Connection Url.", e);
}
//}
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void updateSingleDisplay() {
try {
if (pCityDataList.size() > 0) {
display_message.setVisibility(View.GONE);
singleLayout.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in));
scCityName.setText(pCityDataList.get(0).name);
scCityLocation.setText(pCityDataList.get(0).address);
scCityAbout.setText(pCityDataList.get(0).description);
scCityCatCount.setText(pCityDataList.get(0).category_count + " Categories");
scCitySubCatCount.setText(pCityDataList.get(0).sub_category_count + " Sub Categories");
scCityItemCount.setText(pCityDataList.get(0).item_count + " Items");
Picasso.with(getActivity()).load(Config.APP_IMAGES_URL + pCityDataList.get(0).cover_image_file).into(scCityPhoto);
}
}catch(Exception e){
Utils.psErrorLogE("Error in single display data binding.", e);
}
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : pCityDataList) {
GlobalData.cityDatas.add(cd);
}
}
private void updateDisplay() {
if (swipeRefreshLayout.isRefreshing()) {
pCityDataSet.clear();
adapter.notifyDataSetChanged();
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
} else {
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
}
stopLoading();
adapter.notifyItemInserted(pCityDataSet.size());
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void onItemClicked(int position) {
Utils.psLog("Position : " + position);
Intent intent;
intent = new Intent(getActivity(),SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(position);
intent.putExtra("selected_city_id", pCityDataList.get(position).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void startLoading(){
try{
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}catch (Exception e){}
}
private void stopLoading(){
try {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}catch (Exception e){}
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
Line 252:
pCityDataList = gson.fromJson(response.getString("data"), listType);
PCityData.class:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 6/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
public ArrayList<PCategoryData> categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
if (in.readByte() == 0x01) {
categories = new ArrayList<PCategoryData>();
in.readList(categories, PCategoryData.class.getClassLoader());
} else {
categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
if (categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
L.E:
data:
[{"id":"1","name":"MaramureČ™","description":"MaramureČ™ is a mountainous .","address":"MaramureČ™, Romania","lat":"0","lng":"0","admin_id":"3","is_approved":"1","paypal_trans_id":"0","added":"2016-07-1420:45:50","status":"1","item_count":85,"category_count":49,"sub_category_count":0,"follow_count":0,"cover_image_file":"singapore.png","cover_image_width":"600","cover_image_height":"400","cover_image_description":"Singapore","categories":
L.E:
PCategoryData.java:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 8/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCategoryData implements Parcelable {
public int id;
public int shop_id;
public String name;
public int is_published;
public int ordering;
public String added;
public String updated;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public ArrayList<PSubCategoryData> sub_categories;
public Double value;
protected PCategoryData(Parcel in) {
id = in.readInt();
shop_id = in.readInt();
name = in.readString();
is_published = in.readInt();
ordering = in.readInt();
added = in.readString();
updated = in.readString();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
if (in.readByte() == 0x01) {
sub_categories = new ArrayList<PSubCategoryData>();
in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
} else {
sub_categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(shop_id);
dest.writeString(name);
dest.writeInt(is_published);
dest.writeInt(ordering);
dest.writeString(added);
dest.writeString(updated);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
if (sub_categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(sub_categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCategoryData> CREATOR = new Parcelable.Creator<PCategoryData>() {
#Override
public PCategoryData createFromParcel(Parcel in) {
return new PCategoryData(in);
}
#Override
public PCategoryData[] newArray(int size) {
return new PCategoryData[size];
}
};
}
I guess that PCategoryData has double field, and guess that json value of that double field is "";
UPDATE
Your code will be like this:
public class CitiesListFragment extends Fragment {
...
private void requestData(String uri) {
...
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PCategoryData.class, new PCategoryDataTypeAdapter());
final Gson gson = gsonBuilder.create();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
...
}
...
class PCategoryDataTypeAdapter extends TypeAdapter<PCategoryData> {
#Override
public PCategoryData read(JsonReader in) throws IOException {
final PCategoryData data = new PCategoryData();
in.beginObject();
while (in.hasNext()) {
switch (in.nextName()) {
case "value": //Please change "value" to your field name.
try {
data.value = Double.valueOf(in.nextString());
} catch (NumberFormatException e) {
data.value = 0;
}
break;
}
}
in.endObject();
return data;
}
#Override
public void write(JsonWriter out, PCategoryData data) throws IOException {
out.beginObject();
out.name("value").value(data.value); //Please change "value" to your field name.
out.endObject();
}
}
...
}

Confusion regarding Getting Latitude and Longitude from Activity to Fragment

I am now working on a online rent car finder apk. I want this program TO fetch database from server and sort it based on the location (distance from user current location of rent car garage).
But i am confuse here on how to sort the list view base on the distance ? I mean, i know how to calculate the distance but i am blank about how to get the user's current latitude and longitude inside an Activity without opening mapActivity?
This my condition right now :
1. My result list is inside ResultListFragment.java and my google map activity is on MapActivity.java.
2. I have to try and get the longitude,latitude using getLatitude and getLongitude method which i create on MapActivity.java, but it just returning zero (not null).
3. I tried to separate the gps listener on GPStracker class, but still it doesn't work.
Please help me, how do i get the latitude and longitude of the current user position.
NB. This is my ResultListFragment.java
public class ResultListFragment extends Fragment implements InternetConnectionListener,
LocationChangeListener {
public static String catId;
public static String titleId;
public static String searchTerm;
public static LocationChangeListener locationChangeListener;
private final int RESULT_ACTION = 1;
private final int RESULT_LIMIT = 100;
private ArrayList<Item> searchResultList;
private ResultListCallbacks mCallbacks;
private InternetConnectionListener internetConnectionListener;
private ArrayList<Item> resultList;
private ListView resultListView;
private LatLng itemLocation;
GPSTrackStandAlone gTrack = new GPSTrackStandAlone(getContext());
MapActivity mAct = new MapActivity();
public HomeActivity hAct = new HomeActivity();
public ResultListFragment() {
}
public static ResultListFragment newInstance(String id, String title) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = "";
locationChangeListener = fragment;
return fragment;
}
public static ResultListFragment newInstance(String id, String title,String term) {
ResultListFragment fragment = new ResultListFragment();
catId = id;
titleId = title;
searchTerm = term;
locationChangeListener = fragment;
return fragment;
}
public void getGPSLoc(){
double latitude = mAct.getLatitudeSend();
double longitude = mAct.getLongitudeSend();
Log.d("LatitudeCurrGPSLoc",String.valueOf(latitude));
Log.d("LongCur",String.valueOf(longitude));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (ResultListCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement ResultListCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_result_list, container, false);
resultListView = (ListView) rootView.findViewById(R.id.resultListView);
setHasOptionsMenu(true);
return rootView;
}
#Override
public void onResume() {
super.onResume();
isHomeOpened = false;
isResultListFragmentOpened = true;
if (UtilMethods.isConnectedToInternet(getActivity())) {
if (!TextUtils.isEmpty(catId))
initResultList();
else if (!TextUtils.isEmpty(searchTerm))
getSearchResults(searchTerm);
} else {
internetConnectionListener = (InternetConnectionListener) ResultListFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener, getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), RESULT_ACTION);
}
}
private void initResultList() {
Log.d("Pembuktian", catId);
if(Integer.parseInt(catId)>100 && Integer.parseInt(catId)<200 ){
new getCarRent().execute();
}else if(Integer.parseInt(catId)>199 && Integer.parseInt(catId)<300){
new getCarBrand().execute();
}else if(Integer.parseInt(catId)>299 && Integer.parseInt(catId)<400){
new getCarType().execute();
}
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_RESULT_LIST_WITH_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
// String jsonString = loadJSONFromAsset(getActivity(), "get_result_list");
//parseJson(jsonString);
}
private void getSearchResults(String query) {
/**
* json is populating from text file. To make api call use ApiHandler class
* pass parameter using ContentValues (values)
*
* <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_SEARCH_LIST_AD, values);</CODE> <BR>
* <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done.
*/
String jsonString = loadJSONFromAsset(getActivity(), "get_search_list");
parseJson(jsonString);
}
public class getCarRent extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
URL hp = null;
try {
hp = new URL(getString(R.string.liveurl)
+ "getCarRent.php?value=" + catId);
// hp = new URL(
// "http://192.168.1.106/restourant/foodtype.php?value="
// + id);
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
Log.d("input", "" + input);
BufferedReader r = new BufferedReader(new InputStreamReader(
input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("URL", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
Item[] itemList = new Item[j.length()];
resultList = new ArrayList<Item>();
for (int i = 0; i < j.length(); i++) {
Item item = new Item();// buat variabel category
//JSONObject Obj;
JSONObject Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
item.setId(Obj.getString(JF_ID));
//item.setTitle(Obj.getString(JF_TITLE));
item.setAddress(Obj.getString(JF_ADDRESS));
item.setTelephoneNumber(Obj.optString(JF_TELEPHONE, NO_DATA_FOUND));
item.setEmailAddress(Obj.optString(JF_EMAIL, NO_DATA_FOUND));
item.setWebUrl(Obj.optString(JF_WEB, NO_DATA_FOUND));
item.setFacebookUrl(Obj.optString(JF_FACEBOOK, NO_DATA_FOUND));
item.setLatitude(Obj.optDouble(JF_LATITUDE, NULL_LOCATION));
item.setLongitude(Obj.optDouble(JF_LONGITUDE, NULL_LOCATION));
try {
item.setRating(Float.parseFloat(Obj.optString(JF_RATING, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRating(0.0f);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATING_COUNT, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATINGSCORE, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
item.setTagLine(Obj.optString(JF_TAG_LINE, NO_DATA_FOUND));
item.setDescription(Obj.optString(JF_DESCRIPTION, NO_DATA_FOUND));
item.setVerification(Obj.optString(JF_VERIFICATION, NO_DATA_FOUND).equals("1") ? true : false);
item.setCarId(Obj.optString(JF_CARID, NO_DATA_FOUND));
item.setTitle(Obj.optString(JF_CARTITLE, NO_DATA_FOUND));
item.setCarRentalId(Obj.optString(JF_CARRENTALID, NO_DATA_FOUND));
item.setCarPrice(Obj.optString(JF_CARPRICE, NO_DATA_FOUND));
item.setCarYear(Obj.optString(JF_CARYEAR, NO_DATA_FOUND));
JSONArray imgArr = Obj.getJSONArray("thumbImage");
String[] imageThumb = new String[imgArr.length()];
// String[] imageLarge = new String[imgArr.length()];
for (int k = 0; k < imgArr.length(); k++) {
imageThumb[k] = imgArr.getString(k);
// imageLarge[k] = imgArr.getJSONObject(k).getString(JF_TITLE);
}
for(int l = 0; l <imgArr.length(); l++) {
item.setImageLargeUrls(imageThumb);
}
item.setImageThumbUrls(imageThumb);
// item.setImageLargeUrls(imageLarge);
// JSONArray imgArr = Obj.getJSONArray("thumbImage");
/*String[] imgCount = new String[imgArr.length()];
for(int k = 0 ; k < imgCount.length; k++) {
imgCount[k] = imgArr.getString(k);
item.setImageThumbUrls(imgCount);
}*/
Location trgtLocation = new Location("trgtLocation");
trgtLocation.setLatitude(item.getLatitude());
trgtLocation.setLongitude(item.getLongitude());
Location crntLocation = new Location("crntlocation");
crntLocation.setLatitude(gTrack.getLatitude());
crntLocation.setLongitude(gTrack.getLongitude());
Log.d("latitudeCurr", String.valueOf(gTrack.getLatitude()));
Log.d("curLocLong", String.valueOf(gTrack.getLongitude()));
//LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
item.setDistance(crntLocation.distanceTo(trgtLocation) / 1000);
Log.d("distance", String.valueOf(item.getDistance()));
Log.d("URL1", "" + Obj.getString(JF_TITLE));
resultList.add(item);
itemList[i]=item;
Log.d("itemList",String.valueOf(itemList[i]));
Arrays.sort(itemList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return 0;
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
resultListView.setAdapter(new ResultListAdapterRental(getActivity(), mCallbacks, resultList));
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
}
return null;
}
}
I try to take the Lng and Lat from a System service like this one, but it's still doesn't work. Is this code right ?
GPSTracker.java
public class GPSTrackStandAlone extends Service implements LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
private double mLatitude;
private double mLongitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 60000;
private LocationManager mLocationManager;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
public GPSTrackStandAlone(Context mContext) {
this.mContext = mContext;
}
/**
* #return location
*/
public Location getLocation() {
try {
mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
/*getting status of the gps*/
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
/*getting status of network provider*/
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
/*no location provider enabled*/
} else {
this.canGetLocation = true;
/*getting location from network provider*/
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("Perms", "Permission for GPS Granted");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
/*if gps is enabled then get location using gps*/
if (isGpsEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_FOR_UPDATE,
MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
/**
* call this function to stop using gps in your application
*/
public void stopUsingGps() {
if (mLocationManager != null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager.removeUpdates(GPSTrackStandAlone.this);
}
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
Toast.makeText(GPSTrackStandAlone.this, "isGooglePlayServiceAvailable = False", Toast.LENGTH_SHORT).show();
return false;
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* #return latitude
* <p/>
* function to get latitude
*/
public double getLatitude() {
getLocation();
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* #return longitude
* function to get longitude
*/
public double getLongitude() {
getLocation();
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
Log.d("MGPS", String.valueOf(mLocation.getLatitude()));
}
return mLongitude;
}
/**
* #return to check gps or wifi is enabled or not
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Have you consider to use the Google Maps API ? With it you can simply do the following to get the user's current location :
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();
Do you mean that you can getLng and getLat in activity ?
Try to use a public static to describe your values,and use MyActivity.value in Fragment.
when you want to pass the data from activity to fragment you should use bundle .
I will give you the example.
public class CompleteJobFragment extends Fragment {
private final static String PICKUP_TIME="pickup time";
public static CompleteJobFragment newInstance(String pickUpTime) {
CompleteJobFragment fragment = new CompleteJobFragment();
Bundle bundle = new Bundle();
bundle.putString(PICKUP_TIME, pickUpTime);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pickUpTime = getArguments().getString(PICKUP_TIME);
}
}
Activity file
public class ActiveJobActivity extends AppCompatActivity {
String x1;
public void loadData()
{
CompleteJobFragment completeJobFragment = CompleteJobFragment.newInstance(x1);
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.activez, completeJobFragment, COMPLETE_FRAGMENT);
fragmentTransaction.addToBackStack(COMPLETE_FRAGMENT);
completeJobFragment.setCommunicator(this);
fragmentTransaction.commit();
}

Categories