共享首选项不起作用,java android

3b6akqbq  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(426)

我无法保存或检索共享首选项中的数据。我有多种活动。我不知道我哪里出错了。当我运行的应用程序,它的工作正常,除了数据不是永久存储,因为我希望它。

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="";
    }
}
dzjeubhm

dzjeubhm1#

我不知道你在哪里读到你的偏好,你肯定不会写你的偏好。但我想你不必每次都写。

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中是)。并尝试替换上下文。

相关问题