-1

Here, I'm using the current location of the user as well as the a location which is stored previously and showing path between them. I'm able to get the correct current location but the location I'm trying to store permanently in Shared Preferences are just getting stored until application is running. Once the application is removed and opened again the saved location gets initialised back to 0.0.

I want to store latitude and longitude permanently once after user press save/change location button.

Here's the code:

public class Fragment_ReachHome extends Fragment {

WebView wv;
ProgressDialog pg;
Background bg;
AlertDialog.Builder alert;
ConnectionDetector cd;
MediaPlayer exceptionNotifier;
boolean isInternetPresent = false;



LocationManager locationManager;
LocationListener locationListener;
float latitude;
float longitude;
Location loc;


public static float savelati, savelongi;
Boolean islocationmanagerrequested = false;
Button bsaveorchangeloc, bshowsavedloc;
SharedPreferences pref;
SharedPreferences.Editor edit;
Boolean islocsaved = false, isbpressed = false;

public  Fragment_ReachHome() {}

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_reach_home, container, false);

        wv=(WebView)rootView.findViewById(R.id.webView1);
        alert = new AlertDialog.Builder(getActivity());
        cd = new ConnectionDetector(getActivity());

        locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);






        Toast.makeText(getActivity(), "Loading... Please Wait..", Toast.LENGTH_LONG).show();


    locationListener = new LocationListener() { //-----X0-- THIS SHOULD ALWAYS COME FIRST THEN X1 SHOULD BE WRITTEN

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            } 

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                loc = location;

                latitude = Float.valueOf((float) loc.getLatitude());
                longitude = Float.valueOf((float) loc.getLongitude());

                if(isbpressed){
                    Toast.makeText(getActivity(), "on loc change", Toast.LENGTH_LONG).show();


                }

                bg = new Background();
                bg.execute();


            }
        };
         try {
                isInternetPresent = cd.isConnectingToInternet();
            } catch (Exception e) {
                Toast.makeText(getActivity(), e.toString(),
                        Toast.LENGTH_LONG).show();
            }

        if(isInternetPresent){
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListener);



            }else{

                 exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
                    exceptionNotifier.start();
                    alert.setTitle("Alert!"); 

                    alert.setMessage("Internet Not Present..! ");
                    alert.setCancelable(true);
                    alert.setPositiveButton("Ok!",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    exceptionNotifier.release();

                                }
                            }).show();

            }





        pref = this.getActivity().getSharedPreferences("", 0);
        edit=pref.edit();
        bsaveorchangeloc =(Button)rootView.findViewById(R.id.button1);
        bshowsavedloc =(Button)rootView.findViewById(R.id.button2);
        islocsaved = pref.getBoolean("locsaved", false);
        bsaveorchangeloc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                progress();
                 try {
                        isInternetPresent = cd.isConnectingToInternet();
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), e.toString(),
                                Toast.LENGTH_LONG).show();
                    }

                if(isInternetPresent){
                    //ONLY AFTER X0 THIS MUST BE WRITTEN

                Toast.makeText(getActivity(), "Saving Location!!", Toast.LENGTH_LONG).show();
                locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, 0, 0,
                            locationListener);
                isbpressed = true;
                islocationmanagerrequested = true;

                savelati = pref.getFloat("latestlati", Float.valueOf((float) loc.getLatitude())); //giving default value as 0
                savelongi= pref.getFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));


                edit.putBoolean("locsaved", true);
                edit.commit();


                if(islocationmanagerrequested){
                    locationManager.removeUpdates(locationListener);
                    }
                 pg.dismiss();


                    }else{

                         exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
                            exceptionNotifier.start();
                            alert.setTitle("Alert!"); 

                            alert.setMessage("Internet Not Present..! ");
                            alert.setCancelable(true);
                            alert.setPositiveButton("Ok!",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                int which) {
                                            // TODO Auto-generated method stub
                                            exceptionNotifier.release();

                                        }
                                    }).show();


                    }

            }
        });

        bshowsavedloc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(getActivity(), savelati+","+savelongi, Toast.LENGTH_LONG).show();

            }
        });


        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setUseWideViewPort(true);
        wv.getSettings().setBuiltInZoomControls(true);
        wv.setWebViewClient(new MyWebClient());


        return rootView;
    }


 public void progress(){
        pg = new ProgressDialog(getActivity());
        pg.setTitle("");
        pg.setMessage("Please Wait.........");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }

 class Background extends AsyncTask<Void, Void, Void>
    {

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub


                try{
                    if(islocsaved){
                    wv.loadUrl("http://maps.google.com/maps?saddr="+savelati+","+savelongi+"&daddr="+loc.getLatitude()+","+loc.getLongitude());
                    }else{
                         pg.dismiss();

                        exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
                        exceptionNotifier.start();
                        alert.setTitle("Alert!"); 

                        alert.setMessage("Your home location is not saved yet..! ");
                        alert.setCancelable(true);
                        alert.setPositiveButton("Ok!",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        exceptionNotifier.release();

                                    }
                                }).show();
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }




            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            Toast.makeText(getActivity(), latitude+","+longitude, Toast.LENGTH_LONG).show();
            locationManager.removeUpdates(locationListener);

        }

        @Override
        protected void onPreExecute() {

            progress();

        }
    }
     public class MyWebClient extends WebViewClient
        {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub

                view.loadUrl(url);
                return true;

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
            super.onPageFinished(view, url);

                         pg.dismiss();

            }
        }





}

Please let me know the correct changes in the code to get store the location permanently...

Siddharth Sachdeva
  • 1,812
  • 1
  • 20
  • 29

3 Answers3

1

You can saved value in preference on onPause() or any Button click event where you want using below code.

 edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
 edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude())); 

 edit.putBoolean("locsaved", true);
 edit.commit();

You can get saved value from preference on onResume() using below code.

  savelati = pref.getFloat("latestlati", 0.0); 
  savelongi= pref.getFloat("latestlongi", 0.0);

  islocsaved=edit.getBoolean("locsaved", true);

and for more information go to Android Shared preferences example or http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html

Community
  • 1
  • 1
M D
  • 47,665
  • 9
  • 93
  • 114
0

You need to save the value of longitide and latitude first in the shareprefrences.

 edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude());
 edit.putFloat("latestlongi", Float.valueOf((float) loc.getLongitude);
duggu
  • 37,851
  • 12
  • 116
  • 113
0

For the better suggestion you have to take your SharedPreferance instance globally

then in your onLocationChanged(Location location) change method you can do this code

edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude())); 

edit.putBoolean("locsaved", false);
edit.commit();

So, that every location change your value for the location is updated and after come to your activity you always get the refresh/latest value.

with onCreate() or onResume() you can get the

savelati = pref.getFloat("latestlati", 0.0); 
savelongi= pref.getFloat("latestlongi", 0.0);

islocsaved=edit.getBoolean("locsaved", false);
GovindRathod
  • 867
  • 1
  • 8
  • 22