簡體   English   中英

共享首選項不起作用,Java android

[英]Shared Preferences not working, Java android

我無法在共享首選項中保存或檢索數據。 我有多個活動。 我不確定我哪里出錯了。 當我運行應用程序時,它工作正常,只是數據沒有像我想要的那樣永久存儲。

package com.obhan.weather;


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMapLongClickListener {

    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;

    public void centerMapOnLocation(Location location, String title) {
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
        //  mMap.clear();
        if(title != "Your Location"){
            mMap.addMarker(new MarkerOptions().position(userLocation).title(title));

        }
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 10));

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                centerMapOnLocation(lastKnownLocation,"Your Location");
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // 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;
        mMap.clear();
        mMap.setOnMapLongClickListener((GoogleMap.OnMapLongClickListener) this);
        Intent intent = getIntent();
        if (intent.getIntExtra("PlaceNumber", 0) == 0) {
            //zoom in to users location
            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    centerMapOnLocation(location, "Your Location");

                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            };
            if (Build.VERSION.SDK_INT < 23) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }else
            {
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
                }else{
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);

                    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    centerMapOnLocation(lastKnownLocation,"Your Location");
                }
            }



        }
        else{

            Location placelocation = new Location(LocationManager.GPS_PROVIDER);
            placelocation.setLatitude(MemorablePlaces.locations.get(intent.getIntExtra("PlaceNumber",0)).latitude);
            placelocation.setLongitude(MemorablePlaces.locations.get(intent.getIntExtra("PlaceNumber",0)).longitude);

            centerMapOnLocation(placelocation,MemorablePlaces.places.get(intent.getIntExtra("PlaceNumber",0)));
            //mMap.addMarker(new MarkerOptions().position(MainActivity.locations.get(intent.getIntExtra("placeNumber",0))).title(MainActivity.places.get(intent.getIntExtra("placeNumber",0))));
        }
       // Toast.makeText(this, intent.getStringExtra("PlaceNumber"), Toast.LENGTH_SHORT).show();
        // Add a marker in Sydney and move the camera
      /*  LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
        String address="";
        try {
            List<Address> listAddress =geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
            if(listAddress!=null && listAddress.size()>0){
                if(listAddress.get(0).getThoroughfare()!=null){
                    Log.i("Address",listAddress.get(0).toString());
                    address += listAddress.get(0).getThoroughfare();
                    // address = "";
                    Log.i("SubThrough", listAddress.get(0).getThoroughfare());
                }
                if(listAddress.get(0).getSubThoroughfare()!=null){
                    address +=listAddress.get(0).getSubThoroughfare();
                }
                // address +=listAddress.get(0).getThoroughfare();
                // Log.i("Through",address);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        if(address==""){
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
            address = sdf.format(new Date());

        }
       /* if(address=="Unnamed Road"){
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
            address = sdf.format(new Date());
        }*/


        mMap.addMarker(new MarkerOptions().position(latLng).title(address));


        MemorablePlaces.places.add(address);
        MemorablePlaces.locations.add(latLng);
        MemorablePlaces.arrayAdapter.notifyDataSetChanged();

         SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.obhan.memorableplaces", Context.MODE_PRIVATE);
        try {
            ArrayList<String> latitudes = new ArrayList<>();
            ArrayList<String > longitudes = new ArrayList<>();
            for(LatLng coordinates: MemorablePlaces.locations){
                latitudes.add(Double.toString(coordinates.latitude));
                longitudes.add(Double.toString(coordinates.longitude));
            }
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("places",ObjectSerializer.serialize(MemorablePlaces.places)).apply();
            editor.putString("latitudes",ObjectSerializer.serialize(latitudes)).apply();
            editor.putString("longitudes",ObjectSerializer.serialize      (longitudes)).apply();
            editor.commit();

        } catch (IOException e) {
            e.printStackTrace();
        }

        Toast.makeText(this, "Location saved", Toast.LENGTH_SHORT).show();
        ///address="";
    }
}

我看不到您在哪里閱讀您的偏好,而且您肯定不會寫下您的偏好。 但我認為你不必每次都寫 apply()。

   SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("places",ObjectSerializer.serialize(MemorablePlaces.places));
                editor.putString("latitudes",ObjectSerializer.serialize(latitudes));
editor.putString("longitudes",ObjectSerializer.serialize(longitudes));

    editor.commit(); // or editor.apply()

如果它不好,請參閱 getApplicationContext()。 我不記得在 Java 中是否有 requireContext() (在 kotlin 中是)。 並嘗試替換上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM