从上下文菜单中删除单个列表项时出错

时间:2017-08-05 20:46:31

标签: java android

我正在处理笔记应用程序。我已经实现了一个note类来显示列表项和Note Serializable。我想在显示警告对话框后从上下文菜单中删除单个列表视图项。现在我正在崩溃,不知道自己做错了什么。

主要活动

    public boolean onContextItemSelected(final MenuItem item) {
            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
          final  Note mLoadedNote = (Note) mListNotes.getAdapter().getItem(info.position);
            mLoadedNote.getTitle();
            switch (item.getItemId()) {

                case R.id.delete:
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
                            .setTitle("Delete " +  mLoadedNote.getTitle())
                            .setMessage("are you sure?")
                    .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        here is where am getting the error
                        if(mLoadedNote != null) {
                            ArrayAdapter<String> note = (ArrayAdapter<String>) mListNotes.getAdapter().getItem(info.position);
    note.remove(note.getItem(info.position));
                            note.notifyDataSetChanged();
                            Toast.makeText(MainActivity.this,  mLoadedNote.getTitle() + " is deleted", Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(MainActivity.this,  "can not delete the note '" + mLoadedNote.getTitle() + "'", Toast.LENGTH_SHORT).show();
                        }

                    }
                    })
                        .setNegativeButton("NO", null); //do nothing on clicking NO button :P
                    alertDialog.show();
            }
            return super.onContextItemSelected(item);
        }

注意适配器

   public class NoteAdapter extends ArrayAdapter<Note> {

    public static final int WRAP_CONTENT_LENGTH = 50;
    public NoteAdapter(Context context, int resource, List<Note> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.view_note_item, null);
        }

        Note note = getItem(position);

        if(note != null) {
            TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
            TextView date = (TextView) convertView.findViewById(R.id.list_note_date);
            TextView content = (TextView) convertView.findViewById(R.id.list_note_content_preview);

            title.setText(note.getTitle());
            date.setText(note.getDateTimeFormatted(getContext()));

            //correctly show preview of the content (not more than 50 char or more than one line!)
            int toWrap = WRAP_CONTENT_LENGTH;
            int lineBreakIndex = note.getContent().indexOf('\n');
            //not an elegant series of if statements...needs to be cleaned up!
            if(note.getContent().length() > WRAP_CONTENT_LENGTH || lineBreakIndex < WRAP_CONTENT_LENGTH) {
                if(lineBreakIndex < WRAP_CONTENT_LENGTH) {
                    toWrap = lineBreakIndex;
                }
                if(toWrap > 0) {
                    content.setText(note.getContent().substring(0, toWrap) + "...");
                } else {
                    content.setText(note.getContent());
                }
            } else { //if less than 50 chars...leave it as is :P
                content.setText(note.getContent());
            }
        }

        return convertView;
    }

}

Note.java

public class Note implements Serializable {
    private long mDateTime; //creation time of the note
    private String mTitle; //title of the note
    private String mContent; //content of the note

    public Note(long dateInMillis, String title, String content) {
        mDateTime = dateInMillis;
        mTitle = title;
        mContent = content;
    }

    public void setDateTime(long dateTime) {
        mDateTime = dateTime;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public void setContent(String content) {
        mContent = content;
    }

    public long getDateTime() {
        return mDateTime;
    }

    /**
     * Get date time as a formatted string
     * @param context The context is used to convert the string to user set locale
     * @return String containing the date and time of the creation of the note
     */
    public String getDateTimeFormatted(Context context) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"
                , context.getResources().getConfiguration().locale);
        formatter.setTimeZone(TimeZone.getDefault());
        return formatter.format(new Date(mDateTime));
    }

    public String getTitle() {
        return mTitle;
    }

    public String getContent() {
        return mContent;
    }
}

错误

FATAL EXCEPTION: main
                                                                       Process: com.app.ben.notetaker, PID: 27476
                                                                       java.lang.ClassCastException: com.app.ben.notetaker.Note cannot be cast to android.widget.ArrayAdapter
                                                                           at com.app.ben.notetaker.MainActivity$2.onClick(MainActivity.java:103)
                                                                           at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

1 个答案:

答案 0 :(得分:0)

改变这个:

ArrayAdapter<String> note = (ArrayAdapter<String>) mListNotes.getAdapter().getItem(info.position);

到此:

ArrayAdapter<Note> note = (ArrayAdapter<Note>) mListNotes.getAdapter();

另外,使用note作为ArrayAdater var的名称并不好。将其重命名为notesArrayAdapter或类似内容。