【问题标题】:Shared Preferences not working, Java android共享首选项不起作用,Java android
【发布时间】:2020-11-19 20:15:53
【问题描述】:

我无法在共享首选项中保存或检索数据。我有多项活动。 我不确定我哪里出错了。 当我运行该应用程序时,它工作正常,只是数据没有按照我的意愿永久存储。

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

【问题讨论】:

    标签: java android maps sharedpreferences


    【解决方案1】:

    我看不到您在哪里阅读了您的偏好,并且您肯定不会写下您的偏好。 但我认为你不必每次都写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 中是的)。并尝试替换上下文。

    【讨论】:

    • sharedPreferences = getSharedPreferences("com.obhan.weather", Context.MODE_PRIVATE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_memorable_places);
    • 尝试 {places =(ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString("places",ObjectSerializer.serialize(new ArrayList())));纬度 =(ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes",ObjectSerializer.serialize(new ArrayList()))); longitudes =(ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes",ObjectSerializer.serialize(new ArrayList()))); } catch (IOException e) { e.printStackTrace(); }
    • @PavanObhan : 你用 ""com.obhan.memorableplaces" 写下你的偏好,在你用 "com.obhan.weather" 阅读之后,你必须使用相同的名字。
    猜你喜欢
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2021-10-16
    • 1970-01-01
    • 2016-09-05
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多