@Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); final ViewGroup characterItemView = (ViewGroup) info.targetView; // info.position will give the index of selected item if (item.getTitle() == "Copy") { final String characterName = ((TextView) characterItemView.findViewById(R.id.list_character_name)) .getText() .toString(); NewCharacterDialog(this, characterName); } else if (item.getTitle() == "Delete") { final CharacterListAdapter abc = characterListAdapter; // Code to execute when clicked on This Item // find the list object // get the name of the character in that object TextView charName = (TextView) (characterItemView.getChildAt(0)); String name = String.valueOf(charName.getText()); File a = new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + name + ".chr"); if (a.delete()) { Toast.makeText(getApplicationContext(), name + " deleted.", Toast.LENGTH_SHORT).show(); abc.removeView(name); GenerateCharacterButtons(); } else { Toast.makeText( getApplicationContext(), name + " not deleted, please try again.", Toast.LENGTH_SHORT) .show(); } } else { return false; } return true; }
// call this when updating the list private void GenerateCharacterButtons() { // detect existing files in path String[] filenames = getApplicationContext().getFilesDir().list(); for (String filename : filenames) { // read in the data // open the stream if (filename.contains(".chr")) { try { FileInputStream fileInputStream = new FileInputStream(new File(fileRootDir, filename)); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); // Generate a nice character name CharacterObject characterObject = (CharacterObject) objectInputStream.readObject(); String[] info = { characterObject.getName(), characterObject.getJobAsString(), String.valueOf(characterObject.getLevel()) }; characterListAdapter.removeView(info[0]); characterListAdapter.addView(info, parentView); characterList.add(info[0]); fileInputStream.close(); objectInputStream.close(); } catch (IOException | ClassNotFoundException e) { Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } } if (characterListAdapter.getCount() == 0) { TextView a = (TextView) findViewById(R.id.messageArea); a.setText(R.string.info_no_existing_characters); } else { TextView a = (TextView) findViewById(R.id.messageArea); a.setText(R.string.info_existing_characters); } this.characterListAdapter.notifyDataSetChanged(); }