无法正确使用 SharedPreferences
Can't use SharedPreferences properly
我正在尝试制作一个应用程序来保存一些令人难忘的地方的位置。我正在使用 SharedPreferences
来保存位置,但它没有被保存。每当用户长按
地图位置被保存。应用程序运行一切正常,但当它重新打开时,它会丢失位置。
主要活动:
public class MainActivity extends AppCompatActivity {
TextView textView;
static ArrayList<String> addresses = new ArrayList<String>();
static ArrayList<LatLng> positions = new ArrayList<LatLng>();
static ArrayAdapter<String> arrayAdapter;
ListView listView;
static int count =0;
static int flag =0;
static int pos;
String countString;
public void add(View view) {
flag=0;
Intent intent = new Intent(this,MapsActivity.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = this.getSharedPreferences(" com.example.memorableplaces",MODE_PRIVATE);
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
try {
countString = sharedPreferences.getString("count","0");
} catch (Exception e) {
e.printStackTrace();
}
count = Integer.parseInt(countString);
Log.i("count",countString);
addresses.clear();
positions.clear();
latitudes.clear();
longitudes.clear();
try {
addresses = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("addresses", ObjectSerializer.serialize(new ArrayList<>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("lats", ObjectSerializer.serialize(new ArrayList<>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("lons", ObjectSerializer.serialize(new ArrayList<>())));
} catch (Exception e) {
e.printStackTrace();
}
Log.i("size",Integer.toString(addresses.size()));
i f(addresses.size() > 0) {
Log.i("ok","ok");
for (int i = 0; i < latitudes.size(); i++) {
positions.add(new LatLng(Double.parseDouble(latitudes.get(i)), Double.parseDouble(longitudes.get(i))));
}
}
textView = findViewById(R.id.textView);
listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, addresses);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
flag=1;
pos = position;
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
Log.i("check","see");
}
});
}
}
地图活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
Marker previous,current;
int flag;
int pos;
String countString;
@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);
}
}
}
@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.setOnMapLongClickListener(this);
if(MainActivity.flag==0) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i("Location", location.toString());
previous.remove();
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
current = mMap.addMarker(new MarkerOptions().position(position).title("You are here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
previous = current;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
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);
LatLng position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
previous = mMap.addMarker(new MarkerOptions().position(position).title("You are here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
}
else
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
LatLng position = MainActivity.positions.get(MainActivity.pos);
mMap.addMarker(new MarkerOptions().position(position).title(MainActivity.addresses.get(MainActivity.pos)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
}
@Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String address = "";
try {
List<Address> listAdddresses = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (listAdddresses != null && listAdddresses.size() > 0) {
if (listAdddresses.get(0).getThoroughfare() != null) {
if (listAdddresses.get(0).getSubThoroughfare() != null) {
address += listAdddresses.get(0).getSubThoroughfare() + " ";
}
address += listAdddresses.get(0).getThoroughfare();
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (address.equals("")) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address += sdf.format(new Date());
}
Log.i("yes","all good");
mMap.addMarker(new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
Log.i("done","good");
addresses.add(address);
positions.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.memorableplaces", Context.MODE_PRIVATE);
try {
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
for (LatLng coord : positions) {
latitudes.add(Double.toString(coord.latitude));
longitudes.add(Double.toString(coord.longitude));
}
sharedPreferences.edit().putString("places", ObjectSerializer.serialize(addresses)).apply();
sharedPreferences.edit().putString("lats", ObjectSerializer.serialize(latitudes)).apply();
sharedPreferences.edit().putString("lons", ObjectSerializer.serialize(longitudes)).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ObjectSerializer class :
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
在你的 MainActivity 中
SharedPreferences sharedPreferences = this.getSharedPreferences(" com.example.memorableplaces",MODE_PRIVATE);
(注意包裹前的space)
在你的 MapsActivity 中
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.memorableplaces", Context.MODE_PRIVATE);
我看到你没有使用相同的 SharedPreferences 键来:
主要活动
adresses, lats, lons
MapsActivity
places, lats, lons
您还可以检查首选项是否已正确保存到设备文件资源管理器中的以下位置:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
我正在尝试制作一个应用程序来保存一些令人难忘的地方的位置。我正在使用 SharedPreferences
来保存位置,但它没有被保存。每当用户长按
地图位置被保存。应用程序运行一切正常,但当它重新打开时,它会丢失位置。
主要活动:
public class MainActivity extends AppCompatActivity {
TextView textView;
static ArrayList<String> addresses = new ArrayList<String>();
static ArrayList<LatLng> positions = new ArrayList<LatLng>();
static ArrayAdapter<String> arrayAdapter;
ListView listView;
static int count =0;
static int flag =0;
static int pos;
String countString;
public void add(View view) {
flag=0;
Intent intent = new Intent(this,MapsActivity.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = this.getSharedPreferences(" com.example.memorableplaces",MODE_PRIVATE);
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
try {
countString = sharedPreferences.getString("count","0");
} catch (Exception e) {
e.printStackTrace();
}
count = Integer.parseInt(countString);
Log.i("count",countString);
addresses.clear();
positions.clear();
latitudes.clear();
longitudes.clear();
try {
addresses = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("addresses", ObjectSerializer.serialize(new ArrayList<>())));
latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("lats", ObjectSerializer.serialize(new ArrayList<>())));
longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("lons", ObjectSerializer.serialize(new ArrayList<>())));
} catch (Exception e) {
e.printStackTrace();
}
Log.i("size",Integer.toString(addresses.size()));
i f(addresses.size() > 0) {
Log.i("ok","ok");
for (int i = 0; i < latitudes.size(); i++) {
positions.add(new LatLng(Double.parseDouble(latitudes.get(i)), Double.parseDouble(longitudes.get(i))));
}
}
textView = findViewById(R.id.textView);
listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, addresses);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
flag=1;
pos = position;
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
Log.i("check","see");
}
});
}
}
地图活动:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
Marker previous,current;
int flag;
int pos;
String countString;
@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);
}
}
}
@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.setOnMapLongClickListener(this);
if(MainActivity.flag==0) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i("Location", location.toString());
previous.remove();
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
current = mMap.addMarker(new MarkerOptions().position(position).title("You are here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
previous = current;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
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);
LatLng position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
previous = mMap.addMarker(new MarkerOptions().position(position).title("You are here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
}
else
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
LatLng position = MainActivity.positions.get(MainActivity.pos);
mMap.addMarker(new MarkerOptions().position(position).title(MainActivity.addresses.get(MainActivity.pos)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
}
@Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
String address = "";
try {
List<Address> listAdddresses = geocoder.getFromLocation(latLng.latitude,latLng.longitude,1);
if (listAdddresses != null && listAdddresses.size() > 0) {
if (listAdddresses.get(0).getThoroughfare() != null) {
if (listAdddresses.get(0).getSubThoroughfare() != null) {
address += listAdddresses.get(0).getSubThoroughfare() + " ";
}
address += listAdddresses.get(0).getThoroughfare();
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (address.equals("")) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address += sdf.format(new Date());
}
Log.i("yes","all good");
mMap.addMarker(new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
Log.i("done","good");
addresses.add(address);
positions.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.memorableplaces", Context.MODE_PRIVATE);
try {
ArrayList<String> latitudes = new ArrayList<>();
ArrayList<String> longitudes = new ArrayList<>();
for (LatLng coord : positions) {
latitudes.add(Double.toString(coord.latitude));
longitudes.add(Double.toString(coord.longitude));
}
sharedPreferences.edit().putString("places", ObjectSerializer.serialize(addresses)).apply();
sharedPreferences.edit().putString("lats", ObjectSerializer.serialize(latitudes)).apply();
sharedPreferences.edit().putString("lons", ObjectSerializer.serialize(longitudes)).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ObjectSerializer class :
public class ObjectSerializer {
public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}
}
在你的 MainActivity 中
SharedPreferences sharedPreferences = this.getSharedPreferences(" com.example.memorableplaces",MODE_PRIVATE);
(注意包裹前的space)
在你的 MapsActivity 中
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.memorableplaces", Context.MODE_PRIVATE);
我看到你没有使用相同的 SharedPreferences 键来:
主要活动
adresses, lats, lons
MapsActivity
places, lats, lons
您还可以检查首选项是否已正确保存到设备文件资源管理器中的以下位置:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml