如何从OnContextItemSelected中删除列表项以及从SharedPreferences中删除?

时间:2017-01-16 05:08:32

标签: android

我正在处理涉及ListViewSharedPreference的Android应用。现在,问题是我无法动态删除ListView中的项目。我尝试了List_view_name.remove(1),但它只删除了数组中的第一个索引,但是当我尝试从列表中删除第二个项目时,它会删除第一个项目。

第二件事是,我尝试从ArrayList删除SharedPreference个地点,以便在应用重新加载时不会显示,但会删除ArrayList个地点中的所有项目。如何从ListView中的SharedPreferenceonContextItemSelected删除特定项目。

下面我发布了代码。

public class MainActivity extends AppCompatActivity {

    static ArrayList<String> places = new ArrayList<String>();
    static ArrayList<LatLng> locations = new ArrayList<>();   //to save lat and long
    static ArrayAdapter arrayAdapter;
    ListView listView;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);

        sharedPreferences = this.getSharedPreferences("com.starprojects.memorableplaces", Context.MODE_PRIVATE);

        //tricker locations
        ArrayList<String> latitudes = new ArrayList<>();
        ArrayList<String> longitudes = new ArrayList<>();

        //initially set
        places.clear();
        latitudes.clear();
        longitudes.clear();
        locations.clear();

        //to restore
        try {
            places = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("places", ObjectSerializer.serialize(new ArrayList<>())));

            latitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("latitudes", ObjectSerializer.serialize(new ArrayList<>())));

            longitudes = (ArrayList<String>) ObjectSerializer.deserialize(sharedPreferences.getString("longitudes", ObjectSerializer.serialize(new ArrayList<>())));

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

        //check to see if we have anything from data storage
        if(places.size() > 0 && latitudes.size() > 0 && longitudes.size() > 0) {
            //something is gone wrong and we dont have same number of places,latitudes and logitudes, app will give error so check to see
            if(places.size() == latitudes.size() && latitudes.size() == longitudes.size()) {
                //loop through both latitude nad lonitude
                for(int i = 0;i<latitudes.size();i++) {
                    locations.add(new LatLng(Double.parseDouble((latitudes.get(i))), Double.parseDouble(longitudes.get(i))));
                }
            }

        } else {
            places.add("Add a new place....");
            locations.add(new LatLng(0,0));
        }

        arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,places);

        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

           //     Toast.makeText(MainActivity.this, i, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getApplication(),MapsActivity.class);
                intent.putExtra("placeNumber",i);
                startActivity(intent);
            }
        });

        registerForContextMenu(listView);

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                if(listView.getItemAtPosition(i) == listView.getItemAtPosition(0)) {
                    Toast.makeText(MainActivity.this, "No", Toast.LENGTH_SHORT).show();
                } else {
                    listView.showContextMenu();
                }

                return true;
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
      //  super.onCreateContextMenu(menu, v, menuInfo);

        if(v.getId()==R.id.listView) {
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
            menu.setHeaderTitle("Menu");
            String[] menuItems = getResources().getStringArray(R.array.menu);
            for (int i = 0; i<menuItems.length; i++) {
                menu.add(Menu.NONE, i, i, menuItems[i]);
            }
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {    
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); //returns null

            if((item.getTitle()).equals("Delete")) {
                int position = (int) info.id;
                Log.i("Psotion",String.valueOf(position));
                places.remove(position);
                return true;

            }
          return super.onContextItemSelected(item);
       }
} 

2 个答案:

答案 0 :(得分:0)

您可以从Adapter中使用的ArrayList中删除值,然后调用notifydatasetchanged()。 为此,您可以创建一个类MyCustomAdapter并扩展BaseAdapter类。您可以在谷歌上获得更多信息。

答案 1 :(得分:0)

您需要从列表而非列表视图中删除项目。在您的情况下,您可以删除以下项目:places.remove(2);locations.remove(2)之后,通知适配器列表项的更改如下:arrayAdapter.notifyDataSetChanged();

尝试这样:

 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
 int index = info.position; 
 places.remove(index);  // delete item from corresponding list
 arrayAdapter.notifyDataSetChanged();