如何处理从SharedPreferences中删除这些项目?

时间:2016-03-22 17:25:44

标签: java android sharedpreferences

我正在构建一个应用程序,根据他们的位置使人们的铃声沉默。我使用PlacePicker API,然后将地点的名称保存到SharedPreferences并将其添加到ListView。但是我在删除项目方面遇到了问题。当用户长按listview项时,它应该从SharedPreferences中删除。问题是,在第一次删除之后,我的方法是引用要删除的SharedPrefs项是坏的,它不起作用。我该如何解决?

public class MainActivity extends AppCompatActivity implements LocationListener {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
ArrayList<Double> latitudeList;
Integer counter;
LocationManager locationManager;
String provider;
double lat;
double lng;
Place place;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    placeListView = (ListView) findViewById(R.id.placeListView);
    latitudeList = new ArrayList<>();
    placeArrayList = new ArrayList<String>();
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, placeArrayList);
    placeListView.setAdapter(arrayAdapter);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), false);


    placeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {






            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Are you sure?")
                    .setMessage("Do you want to delete this place?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {



                            placeArrayList.remove(position);


                            SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);

                            sharedPreferences.edit().remove("name" + position).apply();


                            arrayAdapter.notifyDataSetChanged();




                        }
                    })
                    .setNegativeButton("No", null)
                    .show();



            return false;
        }
    });




    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;
    }
    Location location = locationManager.getLastKnownLocation(provider);

    if (location != null){


        lat = location.getLatitude();

        lng = location.getLongitude();

        Toast.makeText(getApplicationContext(), String.valueOf(lat) + String.valueOf(lng), Toast.LENGTH_LONG).show();


    }else{

        Toast.makeText(getApplicationContext(), "Unable to get location", Toast.LENGTH_LONG).show();

    }


    sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();

sharedPreferences.edit().putInt("counter", 0);

    counter = sharedPreferences.getInt("counter", -1);




    arrayAdapter.notifyDataSetChanged();
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            PLACE_PICKER_REQUEST = 1;
            builder = new PlacePicker.IntentBuilder();
            pickPlace();


        }
    });
   }

public void pickPlace(){

    try {
        startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
    } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }






}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
             place = PlacePicker.getPlace(data, this);
           // String toastMsg = String.format("Place: %s", place.getName());
            //Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();


            counter = sharedPreferences.getInt("counter", -1);


                counter = counter + 1;
                sharedPreferences.edit().putInt("counter", counter).apply();


           LatLng latLng = place.getLatLng();

            sharedPreferences.edit().putFloat("latitude" + String.valueOf(counter), (float) latLng.latitude).apply();

            sharedPreferences.edit().putFloat("longitude" + String.valueOf(counter), (float) latLng.longitude).apply();




                   placeArrayList.add(place.getName().toString());

            sharedPreferences.edit().putString("name" + placeArrayList.size(), place.getName().toString()).apply();








arrayAdapter.notifyDataSetChanged();








        }

    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onLocationChanged(Location location) {

    for (int i = counter; i >= 0; i--){


        if (lat >= sharedPreferences.getFloat("latitude" + String.valueOf(i), -1) - .005 &&
                lat <= sharedPreferences.getFloat("latitude" + String.valueOf(i), -1) + .005 &&
                lng >= sharedPreferences.getFloat("longitude" + String.valueOf(i), -1) - .005 &&
                lng <= sharedPreferences.getFloat("longitude" + String.valueOf(i), -1) + .005){


            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

            audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);


        }

    }



}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

1 个答案:

答案 0 :(得分:1)

您可以为首选项更改添加侦听器。像这样:

preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

            }
        });

您收到密钥已更改,现在您可以检查此值或此密钥是否存在。

希望它对你有所帮助。