i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.
The CurrentPosition works.
But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.
Would be really thankful if someone could find the problem
MapsActivity.java
package androfenix.currentpositionandplacesnearby;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng latLng;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onPause()
{
super.onPause();
//Unregister for location callbacks:
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Create a LatLng object for the current location
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public StringBuilder sbMethod() throws SecurityException
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=50000");
sb.append("&sensor=true");
sb.append("&keyword=" + "bar|cafe");
sb.append("&key= SERVER API KEY ");
Log.d("Map", "url: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParserTask
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
//mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Placing a marker on the touched position
Marker m = mMap.addMarker(markerOptions);
// ZZZZZZZZZZZZZZZZZZZ
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
}
Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.
If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.
The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(TAG, String.format("Place '%s' has likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});
The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.
The following code snippet retrieves the place that the user has selected:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
Related
logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)
Someone please help me why my result always error parsing data ?
My app run smoothly but does not display anything. i feel so stuck here.
this is my code
Sorry for bad english
API JSON
public function getkategori2(){
$data = array();
$token = $this->input->post('f_token');
$tabel = $this->input->post('f_tabel');
if ($token == '' || $tabel == ''){
$data['result'] = false;
$data['msg'] = "Data Kosong";
echo json_encode($data);
return;
}
$sql = 'SELECT * FROM '.$tabel.'_kategori INNER JOIN files WHERE '.$tabel.'_kategori.id_kategori = files.id_kategori';
$q = $this->db->query($sql);
if ($q->num_rows()>0) {
foreach ($q->result() as $value) {
$kategori = array(
'nama_kategori' => $value->nama_kategori,
'file_name' => $value->file_name,
);
};
$data['result'] = true;
$data['kategori_data'] = $kategori;
$data['msg'] = '';
} else {
$data['result'] = false;
$data['msg'] = 'error';
}
echo json_encode($data);
}
JSON Result
{
"result":true,
"kategori_data":
{
"nama_kategori":"Pasta",
"file_name":"1_Pasta.jpg"
},
"msg":""
}
KategoriAdapter
public class KategoriAdapter extends RecyclerView.Adapter<KategoriAdapter.ViewHolder> {
private ArrayList<Kategori> mData;
private Context context;
private SessionManager sesi;
public KategoriAdapter (Context context, ArrayList<Kategori> mData){
this.context = context;
this.mData = mData;
}
#Override
public KategoriAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context)
.inflate(R.layout.item_list_kategori, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(KategoriAdapter.ViewHolder holder, int position) {
Kategori k = mData.get(position);
String kategori = k.getKategoriNama();
String gambar = k.getImg();
//masukan kedalam object viewholder
holder.tvKategori.setText(kategori);
Picasso.with(context)
.load(Constant.BASE_IMAGE + sesi.getTabel() + "/kategori/" + gambar)
.into(holder.ivKategori);
}
//buta object interface onAdapterjabatanListener
private OnAdapterListener listener;
//buat method untuk mendefiniskan listenernya
public void setListener(OnAdapterListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
//buat class yang extend dari ViewHolder
class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout container;
public TextView tvKategori;
public ImageView ivKategori;
public ViewHolder(View v){
super(v);
//baru hubungkan variablenya dengan item yang ada di class layout item
container = v.findViewById(R.id.container);
tvKategori = v.findViewById(R.id.tvKategori);
ivKategori = v.findViewById(R.id.ivKategori);
}
}
KategoriFragment
public class KategoriFragment extends Fragment {
SessionManager sesi;
private ArrayList<Kategori> data;
private OkHttpClient okClient;
private RecyclerView rvData;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_kategori, container, false);
sesi = new SessionManager(getActivity());
data = new ArrayList<>();
okClient = new OkHttpClient();
rvData = rootView.findViewById(R.id.rvData);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
rvData.setLayoutManager(manager);
getData();
return rootView;
}
private void getData(){
data.clear();
String url = Constant.BASE_URL + "getkategori2";
FormBody parameters = new FormBody.Builder()
.add("f_token", sesi.getToken())
.add("f_tabel", sesi.getTabel())
.build();
//buat request untuk ambil data
Request request = new Request.Builder()
.url(url)
.post(parameters)
.build();
okClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
e.printStackTrace();
RbHelpers.pesan(getActivity(),
"error :" + e.getMessage());
}
});
}
#Override
public void onResponse(Call call,final Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//hilangkan dialognya
}});
final String responData = response.body().string();
RbHelpers.pre("respon data : " + responData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//debug hasilnya kedalam android monitor
try {
//parsing json
try {
JSONObject json = new JSONObject(responData);
Log.d("tagJSON",json.toString());
//check hasilnya apakah true or false
boolean hasil = json.getBoolean("result");
if (hasil){
//ada datanya
//buat object jsonArray
JSONArray jArray = json.getJSONArray("kategori_data");
//looping data dan masukkan kedalam arraylist
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
Kategori kategori = new Kategori();
kategori.setKategoriNama(jObj.getString("nama_kategori"));
kategori.setImg(jObj.getString("file_name"));
//tinggal masukan ke arraylist
data.add(kategori);
}
} else {
String msg = json.getString("msg");
RbHelpers.pesan(getActivity(), msg);
}
//tinggal masukin ke recylerview
//UserAdapter adapter = new UserAdapter
KategoriAdapter adapter = new KategoriAdapter(getActivity(), data);
rvData.setAdapter(adapter);
} catch (JSONException e){
RbHelpers.pesan(getActivity(), "Error parsing data");
e.printStackTrace();
}
} catch (Exception e) {
RbHelpers.pesan(getActivity(), "Error ambil data");
e.printStackTrace();
}
}
});
}
});
}
Think this is the wrong part "kategori_data" is a JSONObject , not a JSONArray, Check the correct format in jsonBlob as
Here you have an example of a mine working project where i have a model Articulo(Product) and I make a request to retrieve that object data
try{
// Get the JSON array
JSONObject result = response.getJSONObject("articulo");
int i ;
for(i=0;i<1;i++){
JSONObject articulo = result;
ListaArticulos item = new ListaArticulos(
articulo.getString("IdArticulo"),
articulo.getString("Precio"),
articulo.getString("Stock"),
articulo.getString("Consultas"),
articulo.getString("IdCategoria"),
articulo.getString("Descripcion"),
articulo.getString("Observacion"),
articulo.getString("Codigo"),
articulo.getString("Imagen")
);
So in conclusion what you need to do is change JSONArray jArray = json.getJSONArray("kategori_data");
for
JSONObject jsonOb = json.getJSONObject("kategori_data");
Started running my google maps project and encountered this NullPointerException error in the
Logcat ->
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.sachiewerk.smart_healthcare.pharma2.onMapReady(pharma2.java:100)
at com.google.android.gms.maps.zzak.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:504)
at fr.b(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):20)
at com.google.android.gms.maps.internal.bg.a(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_dynamitemodulesb#12688021#12.6.88 (040306-197970725):5)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
The app finds and displays nearby pharmacies, This class show details of nearby pharmacy details like(address, phone numbers, website URI and price ratings) in a custom info window.
this is the class java code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sachiewerk.smart_healthcare.models.PlaceInfo;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
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.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.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class pharma2 extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready..");
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.getUiSettings().setMyLocationButtonEnabled(false);
buildGoogleApiClient();
init();
}
/*
------------------------------------------------------------------------
*/
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){
String search = "pharmacy";
#Override
public void onClick (View v){
mMap.clear();
String url = getUrl(latitude, longitude, search);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
GetNearbyBanksData getNearbyPlacesData = new GetNearbyBanksData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(pharma2.this, "These are your Nearby Pharmacies! ",
Toast.LENGTH_LONG).show();
}
});
/*
------------------------------------------------------------------------
*/
}
private static final String TAG = "pharma2";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 20f;
private static final int PLACE_PICKER_REQUEST = 1;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136));
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
private ImageView mInfo;
private ImageView mPlacePicker;
//vars
private boolean mLocationPermissionGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private Marker mMarker;
private Location mLastLocation;
LocationRequest mLocationRequest;
double latitude, longitude;
private int PROXIMITY_RADIUS = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hosp2);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
mInfo = (ImageView) findViewById(R.id.place_info);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
getLocationPermission();
}
private void init() {
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, Places.getGeoDataClient(this, null),
LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutocompleteAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute our method for searching
geolocate();
}
return false;
}
});
}
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
mInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked place Info");
try {
if (mMarker.isInfoWindowShown()) {
mMarker.hideInfoWindow();
} else {
Log.d(TAG, "onClick: place info: " + mPlace.toString());
mMarker.showInfoWindow();
}
} catch (NullPointerException e) {
Log.e(TAG, "onClick: NullPointerException: " + e.getMessage());
}
}
});
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(pharma2.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick: GooglePlayServicesRepairableException: " + e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick: GooglePlayServicesNotAvailableException: " + e.getMessage());
}
}
});
hideSoftKeyboard();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, place.getId());
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
}
}
private void geolocate() {
Log.d(TAG, "geolocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(pharma2.this);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString, 2);
} catch (IOException e) {
Log.d(TAG, "geolocate: IOException: " + e.getMessage());
}
if (list.size() > 0) {
Address address = list.get(0);
Log.d(TAG, "geolocate: found a location: " + address.toString());
//Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM,
address.getAddressLine(0));
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new
StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAvxiw4FVJzY-XGx9mW8fNde4bjvc8mlbo");
return (googlePlacesUrl.toString());
}
/*
------------------------------------------------------------------------
*/
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting device's current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "Your Device's Location");
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(pharma2.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom, PlaceInfo placeInfo) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
mMap.clear();
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(pharma2.this));
if (placeInfo != null) {
try {
String snippet = "Address: " + placeInfo.getAddress() + "\n" +
"Phone Number: " + placeInfo.getPhoneNumber() + "\n" +
"Website: " + placeInfo.getWebsiteUri() + "\n" +
"Rating: " + placeInfo.getRating() + "\n";
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(placeInfo.getName())
.snippet(snippet);
mMarker = mMap.addMarker(options);
} catch (NullPointerException e) {
Log.e(TAG, "moveCamera: NullPointerException: " + e.getMessage());
}
} else {
mMap.addMarker(new MarkerOptions().position(latLng));
}
hideSoftKeyboard();
}
private void moveCamera(LatLng latLng, float zoom, String title) {
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if (!title.equals("My Location")) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap() {
Log.d(TAG, "initMap: initializing map..");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(pharma2.this);
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionGranted = true;
//initialize map
initMap();
}
}
}
}
private void hideSoftKeyboard() {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/*---------------------------------------------------------------------------------------------------------- */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
/*---------------------------------------------------------------------------------------------------------- */
/*
----------------------Google Places Autocomplete suggesstions-------------------------------------------------------------
*/
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutocompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient ,placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(TAG, "onResult: PLace query did not complete successfully: " + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
// mPlace.setAttribution(place.getAttributions().toString());
// Log.d(TAG, "onResult: attribution: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id: " + place.getId());
mPlace.setLatLng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: Phone Number:" + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: Website: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch(NullPointerException e){
Log.d(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace);
places.release();
}
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mMarker != null) {
mMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("You are Here!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(pharma2.this, "Your Current Location",
Toast.LENGTH_LONG).show();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
Really want to get this app to work because it is my end of year project for my java class.
Any help will much appreciated.
I think it's not working because you're calling the method OnMapReady() before creating the view in the OnCreate() method. Besides, you're not calling the method initMap() anywhere.
i think you got error on this part.
Button btnPharma = (Button) findViewById(R.id.btnPharma);
btnPharma.setOnClickListener(new View.OnClickListener(){});
Your activity_hosp2.xml doesn't have btnPharma id, thus it got
Attempt to invoke virtual method on a null object reference
when you try to listener to null object.
I'm making an App that implements this slide-out Menu and i'm pretty much satisfied about the implementation.
I divided my app in multiple Fragment for one Activity so for each section of the menu there is a Fragment.
The point is that i have an OnItemClickListener that allow me to switch beetween Fragments, so I'd tried two methods :
replace() : it works fine for all fragment except for one of them that load a XML which contains a map (code below). On first load there's no problem but when I switch to another fragment and came back to the one with the map, the app crash.
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/refreshButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="63dp"
android:src="#drawable/refresh"
android:text="Rafraichir" />
</RelativeLayout>
public class MapFragment extends Fragment implements
OnInfoWindowClickListener, LocationListener {
private GoogleMap gMap;
Geocoder geocoder;
private LocationManager locationManager;
private Location userLocation;
private String provider;
private ImageButton refreshButton;
ArrayList<Parking> Parkings;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragmen_map,
container, false);
gMap = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
gMap.setOnInfoWindowClickListener(this);
context = getActivity();
geocoder = new Geocoder(context);
refreshButton = (ImageButton) view.findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getParkingsConnection = new GetParkingsConnection(context);
getParkingsConnection.execute(null, null, null);
myParkings = new ArrayList<Parking>();
}
});
// Geolocaliation
LocationManager service = (LocationManager) getActivity()
.getSystemService(getActivity().LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Get the location manager
locationManager = (LocationManager) getActivity().getSystemService(
getActivity().LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
return view;
}
private Double[] getLatAndLong(String addresse) {
List<Address> addresses = null;
Double latALng[] = new Double[2];
try {
addresses = geocoder.getFromLocationName(addresse, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses.size() > 0) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
latALng[0] = latitude;
latALng[1] = longitude;
}
return latALng;
}
private GetParkingsConnection getParkingsConnection;
JSONObject json;
// Non-Statice inner class : connection au serveur
private class GetParkingsConnection extends AsyncTask<String, Void, String> {
Context mContext;
private ProgressDialog mDialog;
GetParkingsConnection(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(mContext);
mDialog.setMessage("Mise à jour de la carte...");
mDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String resultat;
resultat = getParkings();
return resultat;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("JSON", result);
JSONArray jArray;
try {
json = new JSONObject(result);
jArray = json.getJSONArray("parking");
System.out.println("*****Parkings*****" + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.d("adresse :",
json_data.getString("adresse") + ", nom :"
+ json_data.getString("nom")
+ ", latitude :"
+ json_data.getDouble("latitude")
+ ", longitude :"
+ json_data.getDouble("longitude"));
String adresse = json_data.getString("adresse");
Double latALng[] = getLatAndLong(adresse);
Double lat = latALng[0]; // json_data.getDouble("latitude");
Double lng = latALng[1]; // json_data.getDouble("longitude");
String nom = json_data.getString("nom");
LatLng parkingLocation = new LatLng(lat, lng);
Marker parking = gMap.addMarker(new MarkerOptions()
.position(parkingLocation)
.title(nom)
.snippet(adresse)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_marker)));
Parking park = new Parking(parking.getId(), adresse, nom,
"", lat, lng);
myParkings.add(park);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mDialog.dismiss();
}
// Fonction effectuant uenrequête de type GET sur le fichier
// getParking.php
protected String getParkings() {
HttpResponse response = null;
String res = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
// request.setURI(new
// URI("http://pkdom.1x.biz/getParkings.php"));
request.setURI(new URI(
"http://glennsonna.fr/webService/getParkings"));
response = client.execute(request);
HttpEntity entity = response.getEntity();
// JSONObject json = new JSONObject();
res = EntityUtils.toString(entity);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
Parking parkingToSend = null;
// TOAST
/*
* int p = 0;
*
* while(myParkings.get(p).idMarker != marker.getId() && p <
* myParkings.size()){ Log.d("Marker :" + marker.getId(),
* myParkings.get(p).idMarker);
*
* if(myParkings.get(p).idMarker.equals(marker.getId()) ){
* parkingToSend = myParkings.get(p); Context context =
* getApplicationContext(); CharSequence text = "Match" +
* parkingToSend.adresse; int duration = Toast.LENGTH_SHORT; Toast toast
* = Toast.makeText(context, text, duration); toast.show(); }
*
* p++; }
*/
for (int p = 0; p < myParkings.size(); p++) {
Log.d("Marker :" + marker.getId(), myParkings.get(p).idMarker);
if (myParkings.get(p).idMarker.equals(marker.getId())) {
parkingToSend = myParkings.get(p);
}
}
if (parkingToSend != null) {
Intent i = new Intent(context.getApplicationContext(),
ParkingDetail.class);
i.putExtra("id", parkingToSend.idMarker);
i.putExtra("adresse", parkingToSend.adresse);
i.putExtra("nom", parkingToSend.nom);
i.putExtra("descri", parkingToSend.description);
i.putExtra("latitude", parkingToSend.lat);
i.putExtra("longitude", parkingToSend.lng);
startActivity(i);
}
}
#Override
public void onLocationChanged(Location user) {
// TODO Auto-generated method stub
Log.d("Latitude", ":" + user.getLatitude());
Log.d("Longitude", ":" + user.getLongitude());
this.gMap.setMyLocationEnabled(true);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
hide() & show() : I can switch beetween fragment but excepted for the first screen (the map) all the other show a blank screen without content.
private MenuDrawer mMenuDrawer;
private MenuAdapter mAdapter;
private ListView mList;
private GoogleMap gMap;
private int mActivePosition = -1;
List<Object> mmyFragment;
Fragment currentFragment;
myMapFragment mmyMapFragment;
myMonCompteFragment mmyMonCompteFragment;
myPaiementFragment mmyPaiementFragment;
myReservationsFragment mmyReservationsFragment;
myFavorisFragment mmyFavorisFragment;
myCodePromoFragment mmyCodePromoFragment;
myAboutFragment mmyAboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_my_map);
ActionBar actionBar = this.getActionBar();
actionBar.setSubtitle("Trouvez votre parking");
actionBar.setTitle("my");
actionBar.setDisplayHomeAsUpEnabled(true);
setupMenu();
setupFragments();
}
private void setupMenu() {
mMenuDrawer = MenuDrawer.attach(this, Position.LEFT);
mMenuDrawer.setContentView(R.layout.activity_my_map);
List<Object> items = new ArrayList<Object>();
items.add(new Item("Carte", R.drawable.ic_action_refresh_dark));
items.add(new Item("Mon Compte", R.drawable.ic_action_refresh_dark));
items.add(new Item("Paiement", R.drawable.ic_action_select_all_dark));
items.add(new Item("Mes Réservations",
R.drawable.ic_action_select_all_dark));
items.add(new Item("Mes favoris", R.drawable.ic_action_refresh_dark));
// items.add(new Category(" "));
items.add(new Item("Code Promo", R.drawable.ic_action_refresh_dark));
items.add(new Item("A propos", R.drawable.ic_action_select_all_dark));
// A custom ListView is needed so the drawer can be notified when it's
// scrolled. This is to update the position
// of the arrow indicator.
mList = new ListView(this);
mAdapter = new MenuAdapter(items);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(mItemClickListener);
mMenuDrawer.setMenuView(mList);
}
private void setupFragments() {
mmyMapFragment = new myMapFragment();
mmyMonCompteFragment = new myMonCompteFragment();
mmyPaiementFragment = new myPaiementFragment();
mmyReservationsFragment = new myReservationsFragment();
mmyFavorisFragment = new myFavorisFragment();
mmyCodePromoFragment = new myCodePromoFragment();
mmyAboutFragment = new myAboutFragment();
mmyFragment = new ArrayList<Object>();
mmyFragment.add(mmyMapFragment);
mmyFragment.add(mmyMonCompteFragment);
mmyFragment.add(mmyPaiementFragment);
mmyFragment.add(mmyReservationsFragment);
mmyFragment.add(mmyFavorisFragment);
mmyFragment.add(mmyCodePromoFragment);
mmyFragment.add(mmyAboutFragment);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.myContenu, mmyMapFragment);
fragmentTransaction.commit();
currentFragment = mmyMapFragment;
}
private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mActivePosition = position;
mMenuDrawer.setActiveView(view, position);
mMenuDrawer.closeMenu();
if ((mmyFragment.get(position) != null)
/*&& (mmyFragment.get(position).getClass() != currentFragment
.getClass())*/) {
Fragment nexFragment = (Fragment) mmyFragment
.get(position);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.hide(currentFragment);
if (!nexFragment.isHidden()) {
//fragmentTransaction.add(nexFragment, nexFragment.getTag());
Toast.makeText(
getApplicationContext(),
""
+ nexFragment.getClass().toString()
+ " : "
+ mmyFragment.indexOf(mmyFragment
.get(position)), Toast.LENGTH_SHORT).show();
}
//fragmentTransaction.addToBackStack(nexFragment.getTag());
fragmentTransaction.attach(nexFragment);
fragmentTransaction.replace(R.id.myContenu, nexFragment);
//fragmentTransaction.show(nexFragment);
currentFragment = nexFragment;
fragmentTransaction.commit();...}
After one day i finaly found the answer here
So i just implemented the code below. But I have to use replace(); so I'll find a way to save my map state.
public void onDestroyView ()
{
try{
SupportMapFragment fragment = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}catch(Exception e){
}
super.onDestroyView();
}
How to parse a JSON object in LWUIT,give me some example or some link from where i can read this.Suppose i have the objects given below.
"{'guild': 'Crimson', 'region': 'us', 'realm': 'Caelestrasz', 'timestamp': 1311860040}"
Json Example Code:This Code will work for json.
package com.ndtv.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.ndtv.callback.jsonActivelistener;
import com.ndtv.datatype.StockActiveItem;
import json.me.JSONArray;
import json.me.JSONException;
import json.me.JSONObject;
public class StockActiveParser {
public Vector jsonObjVector = new Vector();
public JSONArray arrayObj = null;
public String name,LastPrice;
protected jsonActivelistener mjsonListener;
public static boolean ParserCanceled = false;
public void setjsonListener(jsonActivelistener listener) {
mjsonListener = listener;
}
// Non-blocking.
public void parser(final String url) {
Thread t = new Thread() {
public void run() {
// set up the network connection
try {
jsonParse(url);
}
catch (Exception e) {
mjsonListener.parserExceptionListing(e);
}
mjsonListener.parseDidFinishListing();
}
};
t.start();
}
protected void jsonParse(String url) {
StringBuffer stringBuffer = new StringBuffer();
InputStream is = null;
HttpConnection hc = null;
System.out.println(url);
try {
hc = (HttpConnection)Connector.open(url);
is = hc.openInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
}
catch (SecurityException se) {
System.out.println("security exception:"+se);
}
catch (NullPointerException npe) {
System.out.println("null pointer excception:"+npe);
}
catch (IOException ioe) {
System.out.println("io exception:"+ioe);
}
try{
hc.close();
is.close();
}catch(Exception e) {
System.out.println("Error in MostActivePareser Connection close:"+e);
e.printStackTrace();
}
String jsonData = stringBuffer.toString();
try {
JSONObject js = new JSONObject(jsonData);
JSONArray js2 = js.getJSONArray("values");
System.out.println(js2.length());
for (int i = 0; i < js2.length(); i++) {
StockActiveItem item = new StockActiveItem();
JSONObject jsObj = js2.getJSONObject(i);
item.name = jsObj.getString("name");
item.last_traded_price = jsObj.getString("last_traded_price");
item.change = jsObj.getString("change");
item.price_diff = jsObj.getString("price_diff");
item.chart=jsObj.getString("chart");
item.company_id=jsObj.getString("company_id");
mjsonListener.itemParsedListing(item);
}
} catch (JSONException e1) {
System.out.println("Json Data error:"+e1);
e1.printStackTrace();
}
catch (NullPointerException e) {
System.out.println("null error:"+e);
}
}
}
public class StockActiveItem
{
public String name ="";
public String last_traded_price ="";
public String change="";
public String price_diff ="";
public String chart="";
public String company_id="";
public String year_high="";
public String year_low="";
}
you just replace name, for example guild replacing name.If any doubt ask me.
Use LWUIT JSONParser and parser the JSON format string. Just use MIDP_IO.jar from latest LWUIT 1.5 for this.
I was able to use sample code provided in below given links successfully in my app.
http://jimmod.com/blog/2010/03/java-me-j2me-json-implementation-tutorialsample/
http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
BTW, Latest JSON ME library can be found here : https://github.com/upictec/org.json.me/
You can use JSON jar and and import that in your project. After that create a JSON object and you can use optString or getString methods of that object accordingly to get the values.