I'm doing app Google Map android.
I want draw a short path betweent 2 point in map.
But I don't know How do i need?
Please help me .Thank you very much.
new class util.java
public class Util {
private DataBaseHelper dbHelper;
private GeoFencApplicationDataset Dataset;
private int getId;
public static boolean checkConnection(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
public void DrawPath(Context c, GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
Dataset = (GeoFencApplicationDataset) c.getApplicationContext();
dbHelper = Dataset.getDbHelper();
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) src.getLongitudeE6() / 1.0E6));
urlString.append("&daddr=");// to
urlString
.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString
.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6));
urlString.append("&ie=UTF8&0&om=0&output=kml");
Log.d("xxx", "URL=" + urlString.toString());
Document doc = null;
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
final String path = doc.getElementsByTagName("GeometryCollection")
.item(0).getFirstChild().getFirstChild()
.getFirstChild().getNodeValue();
final String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(",");
final GeoPoint startGP = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) {
lngLat = pairs[i].split(",");
gp1 = gp2;
gp2 = new GeoPoint(
(int) (Double.parseDouble(lngLat[1]) * 1E6),
(int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(
new PathOverLay(gp1, gp2, 2, color));
if (getId != 0) {
dbHelper.insertTempLatLong(lngLat[1], lngLat[0], getId);
}
Log.d("xxx", "pair:" + pairs[i]);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public double[] getLocation(Context c) {
Criteria criteria;
String provider;
LocationManager locManager = (LocationManager) c
.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locManager.getBestProvider(criteria, true);
double[] loca = new double[2];
// For Latitude & Longitude
Location location = locManager.getLastKnownLocation(provider);
if (location != null) {
loca[0] = location.getLatitude();
loca[1] = location.getLongitude();
} else {
loca[0] = 0.0;
loca[1] = 0.0;
}
return loca;
}
public void setId(int id) {
// TODO Auto-generated method stub
getId = id;
}
}
new class PathOverLay.java
public class PathOverLay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius = 6;
private int mode = 0;
private int defaultColor;
private String text = "";
private Bitmap img = null;
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode) // GeoPoint is a
// int. (6E)
{
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode, int defaultColor) {
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t) {
this.text = t;
}
public void setBitmap(Bitmap bitmap) {
this.img = bitmap;
}
public int getMode() {
return mode;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if (mode == 1) {
if (defaultColor == 999)
paint.setColor(Color.BLUE);
else
paint.setColor(defaultColor);
// RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
// point.x + mRadius, point.y + mRadius);
RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
canvas.drawOval(oval, paint);
}
// mode=2:path
else if (mode == 2) {
if (defaultColor == 999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(70);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
}
/* mode=3:end */
else if (mode == 3) {
/* the last path */
if (defaultColor == 999)
paint.setColor(Color.GREEN);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
RectF oval = new RectF(point2.x - mRadius, point2.y - mRadius,
point2.x + mRadius, point2.y + mRadius);
/* end point */
paint.setAlpha(120);
canvas.drawOval(oval, paint);
}
}
return super.draw(canvas, mapView, shadow, when);
}
// Read more:
// http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html#ixzz1hte9kGoi
}
final call method ...
util = new Util();
mapOverlays = mapView.getOverlays();
util = new Util();
util.setId(id);
GeoPoint srcGeoPoint = new GeoPoint((int) (destLat * 1E6),
(int) (destLong * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (srcLat * 1E6),
(int) (srcLong * 1E6));
progrDialog = ProgressDialog.show(AddFenceActivity.this,
"", "Please Wait..", true);
mapView.getOverlays().add(
new PathOverLay(srcGeoPoint,destGeoPoint, 2,Color.RED));
util.DrawPath(AddFenceActivity.this, srcGeoPoint,
destGeoPoint, Color.RED, mapView);
mapView.getController().animateTo(srcGeoPoint);
public class MapOverLayItem extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public MapOverLayItem(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public MapOverLayItem(Drawable defaultMarker, Context context) {
super(defaultMarker);
mContext = context;
}
}
Related
2021-08-10 10:21:03.685 4272-4288/com.hamid.almusabaha E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found
2021-08-10 10:21:05.530 4272-4272/com.hamid.almusabaha E/ActivityThread: Failed to find provider info for com.google.android.gms.chimera
2021-08-10 10:21:06.564 4272-4343/com.hamid.almusabaha E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
2021-08-10 10:21:06.570 4272-4332/com.hamid.almusabaha E/cr_SBApiBridge: Failed to init handler: Attempt to invoke virtual method 'java.lang.reflect.Constructor java.lang.Class.getDeclaredConstructor(java.lang.Class[])' on a null object reference
2021-08-10 10:21:11.302 4272-4272/com.hamid.almusabaha E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hamid.almusabaha, PID: 4272
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at com.hamid.almusabaha.Musbiha_Large$7.run(Musbiha_Large.java:185)
at android.app.Activity.runOnUiThread(Activity.java:5866)
at com.hamid.almusabaha.Musbiha_Large.showFloatView(Musbiha_Large.java:179)
at com.hamid.almusabaha.MainActivity$20.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
This is my activity
public class Musbiha_Large {
private static boolean mIsFloatViewShowing;
private Activity mActivity;
private WindowManager mWindowManager;
private View mFloatView;
private WindowManager.LayoutParams mFloatViewLayoutParams;
private boolean mFloatViewTouchConsumedByMove = false;
private int mFloatViewLastX;
private int mFloatViewLastY;
private int mFloatViewFirstX;
private int mFloatViewFirstY;
static LinearLayout coverLargeL;
private int numpr = 0;
boolean isDark = false;
boolean isPha = false;
public
Musbiha_Large(final Activity activity) {
mActivity = activity;
LayoutInflater inflater = LayoutInflater.from(activity);
mFloatView = inflater.inflate(R.layout.musbiha_large, null);
final TextView textNbrLarge = mFloatView. findViewById ( R.id.textNbrLarge );
final ImageView PlayLarge = mFloatView. findViewById ( R.id.PlayLarge );
final ImageView lightLarge = mFloatView. findViewById ( R.id.lightLarge );
final ImageView ResetLarge = mFloatView. findViewById ( R.id.ResetLarge );
final LinearLayout lirarlightLarge = mFloatView. findViewById ( R.id.lirarlightLarge );
final ImageButton exetLarge = mFloatView.findViewById(R.id.exetLarge);
final ImageButton plph = mFloatView.findViewById(R.id.plph);
coverLargeL = mFloatView.findViewById(R.id.
coverLargeF);
exetLarge.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismissFloatView();
}
});
mFloatView.setOnClickListener(mFloatViewOnClickListener);
mFloatView.setOnTouchListener(mFloatViewOnTouchListener);
mFloatViewLayoutParams = new WindowManager.LayoutParams();
mFloatViewLayoutParams.format = PixelFormat.TRANSLUCENT;
mFloatViewLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mFloatViewLayoutParams.type = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
: WindowManager.LayoutParams.TYPE_TOAST;
mFloatViewLayoutParams.gravity = Gravity.CENTER;
mFloatViewLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mFloatViewLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
public void dismissFloatView() {
if (mIsFloatViewShowing) {
mIsFloatViewShowing = false;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (mWindowManager != null) {
mWindowManager.removeViewImmediate(mFloatView);
}
}
});
}
}
public void showFloatView() {
if (!mIsFloatViewShowing) {
mIsFloatViewShowing = true;
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (!mActivity.isFinishing()) {
mWindowManager = (WindowManager) mActivity.getSystemService(WINDOW_SERVICE);
if (mWindowManager != null) {
mWindowManager.addView(mFloatView, mFloatViewLayoutParams);
}
}
}
});
}
}
private View.OnClickListener mFloatViewOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Toast.makeText(mActivity, "Float view is clicked!", Toast.LENGTH_SHORT).show();
// sbha.setBackgroundResource ( R.drawable.green );
}
});
}
};
private View.OnTouchListener mFloatViewOnTouchListener = new View.OnTouchListener() {
#TargetApi(Build.VERSION_CODES.FROYO)
#Override
public boolean onTouch(View v, MotionEvent event) {
WindowManager.LayoutParams prm = mFloatViewLayoutParams;
int totalDeltaX = mFloatViewLastX - mFloatViewFirstX;
int totalDeltaY = mFloatViewLastY - mFloatViewFirstY;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
mFloatViewFirstX = mFloatViewLastX;
mFloatViewFirstY = mFloatViewLastY;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - mFloatViewLastX;
int deltaY = (int) event.getRawY() - mFloatViewLastY;
mFloatViewLastX = (int) event.getRawX();
mFloatViewLastY = (int) event.getRawY();
if (Math.abs(totalDeltaX) >= 5 || Math.abs(totalDeltaY) >= 5) {
if (event.getPointerCount() == 1) {
prm.x += deltaX;
prm.y += deltaY;
mFloatViewTouchConsumedByMove = true;
if (mWindowManager != null) {
mWindowManager.updateViewLayout(mFloatView, prm);
}
} else {
mFloatViewTouchConsumedByMove = false;
}
} else {
mFloatViewTouchConsumedByMove = false;
}
break;
default:
break;
}
return mFloatViewTouchConsumedByMove;
}
};
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");
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();
}
If I comment the onPause compass.disable and onResume compass.Enable apps start and work but I don't have the compass on my Google map.
On the other hand if I uncomment these two line the apps don't even show. Like is blocked, then I again comment this two line and emulator again work. So somewhere is problem with compass but I don't see where, any help.
MapView map;
MyLocationOverlay compass;
MapController controller;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
long start;
long stop;
int x, y;
int latit;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);// dodao za favicon
setContentView(R.layout.activity_main);
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.logo);
map = (MapView) findViewById(R.id.mvMain);
map.setBuiltInZoomControls(true);
this.setTitle("EasyMaps=QRZ");
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(MainActivity.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint((int) (47.975 * 1E6), (int) (17.056 * 1E6));
controller.animateTo(point);
controller.setZoom(17);
d = getResources().getDrawable(R.drawable.icon);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null) {
latit = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(latit, longi);
OverlayItem overlayitem = new OverlayItem(ourLocation, "Location", "Location");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
} else {
Toast.makeText(MainActivity.this, "Provider not avaiable!", Toast.LENGTH_SHORT).show();
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
compass.enableCompass();//Problem
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
protected void onPause() {
super.onPause();
compass.disableCompass();//Problem
lm.removeUpdates(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX() + 11;
y = (int) e.getY() - 15;
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}
if (stop - start > 1500) {
// to do action
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Option panel");
alert.setMessage("Choose an option!");
alert.setButton("Put flag", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint, "Flag", "Flag");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6, 1);
if (address.size() > 0) {
String display = "";
for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++) {
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t3 = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t3.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// Nista
}
}
});
alert.setButton3("View", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (map.isSatellite()) {
map.setSatellite(false);
map.setStreetView(true);
} else {
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
latit = (int) (l.getLatitude() * 1E6);
longi = (int) (l.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(latit, longi);
OverlayItem overlayitem = new OverlayItem(ourLocation, "Location", "LOcation");
CustomPinpoint custom = new CustomPinpoint(d, MainActivity.this);
custom.insertPinpoint(overlayitem);
overlayList.add(custom);
}
#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
}
}
You may want to use different names. What you call "compass" is actually your location, and it will certainly behave differently from a compass - it will mostly point in a different direction, for starters.
Before you try to enable or disable the MyLocation overlay, you need to check if it is actually non-null.
if (mMyLocationOverlay != null)
mMyLocationOverlay.disableMyLocation();
public class show extends MainScreen {
private String date1;
private long date1l;
private long date2l;
private LabelField curDate = new LabelField();
private LabelField toDate = new LabelField();
private LabelField diffe = new LabelField();
// private LabelField info;
// private LabelField empty;
// private InvokeBrowserHyperlinkField hello;
ButtonField activate = null;
ButtonField disactivate = null;
Timer timer;
Timer timer2;
public String date1s[];
int d, m, y;
int x = 1;
String day, hour, minute;
Date date = new Date();
Calendar calendar = Calendar.getInstance();;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy HH mm");
public show() {
add(curDate);
add(toDate);
add(new SeparatorField());
add(diffe);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTick(), 0, 1000);
}
private class TimerTick extends TimerTask {
public void run() {
if (x != 0) {
date1l = date.getTime();
try {
date1 = dateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.YEAR, 2012);
date2l = cal.getTime().getTime();
date1s = StringUtilities.stringToWords(date1);
d = Integer.parseInt(date1s[0]);
m = Integer.parseInt(date1s[1]);
y = Integer.parseInt(date1s[2]);
display();
} else {
timer.cancel();
}
}
}
public void display() {
String monw = convertToWords(m);
curDate.setText("Current Date = " + d + " " + monw + " " + y + " "
+ date1s[3] + ":" + date1s[4]);
toDate.setText("To Date = 1 February 2012 00:00");
long diffms = date2l - date1l;
long ds = diffms / 1000;
long dm = ds / 60;
long dh = dm / 60;
long dd = dh / 24;
long q = dd;
long h = (ds - (dd * 24 * 60 * 60)) / (60 * 60);
long m = (ds - (dh * 60 * 60)) / 60;
diffe.setText("Remaining Time : \n" + Long.toString(q) + " day(s) "
+ Long.toString(h) + " hour(s) " + Long.toString(m)
+ " minute(s)");
day = Long.toString(q);
hour = Long.toString(h);
minute = Long.toString(m);
showMessage();
}
/*
* private void link() { empty = new LabelField("\n\n"); add(empty); hello =
* new InvokeBrowserHyperlinkField("Click here",
* "http://indri.dedicated-it.com/wordpress/?page_id=17"); add(hello); info
* = new LabelField("\n\nPress menu then choose \"Get Link\" to access");
* add(info); }
*/
void showMessage() {
activate = new ButtonField("Activate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (activate.isFocus()) {
Dialog.alert("Started!!");
Start();
}
return true;
}
};
add(activate);
disactivate = new ButtonField("Disactivate", FIELD_HCENTER) {
protected boolean navigationClick(int action, int time) {
if (disactivate.isFocus()) {
Dialog.alert("Stopped!!");
timer2.cancel();
}
return true;
}
};
add(disactivate);
/*
* UiEngine ui = Ui.getUiEngine(); Screen screen = new
* Dialog(Dialog.D_OK, data, Dialog.OK,
* Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
* Manager.VERTICAL_SCROLL); ui.queueStatus(screen, 1, true);
*/
}
public void Start() {
timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTick2(), 0, 6000);
}
private class TimerTick2 extends TimerTask {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
Screen screen = new Dialog(Dialog.D_OK, "Hello!",
Dialog.OK,
Bitmap.getPredefinedBitmap(Bitmap.EXCLAMATION),
Manager.VERTICAL_SCROLL);
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
});
}
}
private String convertToWords(int m) {
String w = "";
switch (m) {
case 1:
w = "January";
break;
case 2:
w = "February";
break;
case 3:
w = "March";
break;
case 4:
w = "April";
break;
case 5:
w = "May";
break;
case 6:
w = "June";
break;
case 7:
w = "July";
break;
case 8:
w = "August";
break;
case 9:
w = "September";
break;
case 10:
w = "October";
break;
case 11:
w = "November";
break;
case 12:
w = "December";
break;
}
return w;
}
public boolean onClose() {
UiApplication.getUiApplication().requestBackground();
return true;
}
}
What actually is JVM 104 IllegalStateException? This program is a countdown program, which counts the remaining time from today until February 1st. Also, I implement a timer function that appears even if the application is closed. Can u please help me locate the problem? Thank you
As Richard said, you are trying to update LabelField from another thread. Try the following code snippet:
synchronized (UiApplication.getEventLock()) {
labelField.setText();
}
Try this below code and change according to your requirement;
public class FirstScreen extends MainScreen implements FieldChangeListener
{
LabelField label;
Timer timer;
TimerTask timerTask;
int secs=0;
long start,end;
String startDate="2012-01-28",endDate="2012-01-29";
ButtonField startCountDown;
public FirstScreen()
{
createGUI();
}
private void createGUI()
{
startCountDown=new ButtonField("Start");
startCountDown.setChangeListener(this);
add(startCountDown);
}
public void fieldChanged(Field field, int context)
{
if(field==startCountDown)
{
start=System.currentTimeMillis();
//this is the current time milliseconds; if you want to use two different dates
//except current date then put the comment for "start=System.currentTimeMillis();" and
//remove comments for the below two lines;
//Date date=new Date(HttpDateParser.parse(startDate));
//start=date.getTime();
Date date=new Date(HttpDateParser.parse(endDate));
end=date.getTime();
int difference=(int)(end-start);
difference=difference/1000;//Now converted to seconds;
secs=difference;
Status.show("Seconds: "+secs,100);
callTheTimer();
}
}
public void callTheTimer()
{
label=new LabelField();
add(label);
timer=new Timer();
timerTask=new TimerTask()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
if(secs!=0)
{
label.setText(""+(secs--)+" secs");
}
else
{
timer.cancel();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
label.setText("");
Dialog.alert("Times Up");
}
});
}
}
}
};
timer.schedule(timerTask, 0, 1000);
}
protected boolean onSavePrompt()
{
return true;
}
public boolean onMenu(int instance)
{
return true;
}
public boolean onClose()
{
UiApplication.getUiApplication().requestBackground();
return super.onClose();
}
}
In this code I am taking taking two different dates and start the countdown by taking their difference(in seconds); See the comments in the code;