首页 > 解决方案 > recyclerview 适配器内的 startActivityForResult 无法正常工作?

问题描述

我在片段中有一个recyclerview。在那个回收站视图中,我放置了用户想要存储的注释(存储应用程序/片段的注释)。我想添加一个功能,以便用户可以修改/更改他们的笔记。但我在实施时面临困难。我成功地做了一个新的笔记。但是在实现修改注释的功能后,当我点击按钮的注释时,我的应用程序崩溃了。

我认为的主要问题是,我有两个指向同一活动的意图,但我无法正确处理它们。此外,我认为我也没有正确使用 startActivityForResult。

当用户单击现有任务时,我正在调用该任务以使用浮动操作按钮和编辑功能来创建新任务功能。

NotesFragment.java 文件

public class NotesFragment extends Fragment {

    List<NotesData> notesList = new ArrayList<>();
    ActivityResultLauncher<Intent> activityResultLauncher;
    DBHandler_Notes db;
    FloatingActionButton fab_notes;

    public NotesFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_notes, container, false);

        RecyclerView notes_recyclerView = view.findViewById(R.id.notes_recylerView);
        fab_notes = view.findViewById(R.id.fab_notes);

        db = new DBHandler_Notes(getContext());
        notesList = db.getAllNotes();

        NotesRecyclerViewAdapter adapter = new NotesRecyclerViewAdapter(getContext(),notesList,db);
        notes_recyclerView.setAdapter(adapter);

        StaggeredGridLayoutManager lytmanager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        notes_recyclerView.setLayoutManager(lytmanager);


        fab_notes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), writing_notes.class);
                intent.putExtra("source","first");
                activityResultLauncher.launch(intent);
            }
        });




        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == RESULT_OK && result.getData()!=null){
                    NotesData d=new NotesData();
                    d.setNotes(result.getData().getStringExtra("note"));
                    db.insertNote(d);
                    notesList = db.getAllNotes();
                    NotesRecyclerViewAdapter myadapter = new NotesRecyclerViewAdapter(getContext(),notesList,db);
                    notes_recyclerView.setAdapter(myadapter);
                }
            }
        });

        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == RESULT_OK){
                    notesList = db.getAllNotes();
                    NotesRecyclerViewAdapter myadapter = new NotesRecyclerViewAdapter(getContext(),notesList,db);
                    notes_recyclerView.setAdapter(myadapter);
                }
            }
        });



        return view;
    }
}

NotesRecyclerViewAdpater

public class NotesRecyclerViewAdapter extends RecyclerView.Adapter<NotesRecyclerViewAdapter.viewHolder>{

    Context context;
    List<NotesData> notesList;
    DBHandler_Notes db;
    ActivityResultLauncher<Intent> activityResultLauncher;

    public NotesRecyclerViewAdapter(Context context, List<NotesData> notesList,DBHandler_Notes db) {
        this.context = context;
        this.notesList = notesList;
        this.db=db;
    }

    @NonNull
    @Override
    public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.notes_custom_layout,parent,false);
        return new viewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull NotesRecyclerViewAdapter.viewHolder holder, int position) {
        NotesData data = notesList.get(position);
        holder.textView.setText(data.getNotes());

        holder.linearLayoutCustom.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("Delete This Note");
                builder.setMessage("Are you sure you want to delete this note?");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteSelectedNote(position);
                    }
                });

                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        notifyItemChanged(position);
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();

                Button nbutton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                nbutton.setTextColor(Color.BLACK);
                Button pbutton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                pbutton.setTextColor(Color.BLACK);

                return true;
            }

        });


        holder.linearLayoutCustom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NotesData d = notesList.get(position);

                Intent in = new Intent(context.getApplicationContext(), writing_notes.class);
                in.putExtra("source","second");
                in.putExtra("id",d.getId());
                in.putExtra("noteString",d.getNotes());
                activityResultLauncher.launch(in);



            }
        });

    }

    @Override
    public int getItemCount() {
        return notesList.size();
    }

    public void deleteSelectedNote(int position){
        NotesData d = notesList.get(position);
        db.deletenote(d.getId());
        notesList.remove(position);
        notifyItemRemoved(position);
    }


    public class viewHolder extends RecyclerView.ViewHolder{
        TextView textView;
        LinearLayout linearLayoutCustom;
        CardView cardView;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.notes_custom_textView);
            linearLayoutCustom = itemView.findViewById(R.id.custom_linearLayout);
            cardView = itemView.findViewById(R.id.CardView);
        }
    }
}

Notes 数据库类

public class DBHandler_Notes extends SQLiteOpenHelper {


    public static final int VERSION=1;
    public static final String DB_NAME="NotesListDB";
    public static final String NOTES_TABLE="notes";
    public static final String ID="_id";
    public static final String NOTE="note";
    public static final String CREATE_NOTES_TABLE="CREATE TABLE "+NOTES_TABLE+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
            +NOTE+" TEXT)";

    private SQLiteDatabase db;
    Context context;


    public DBHandler_Notes( Context context) {
        super(context, DB_NAME,null,VERSION);
        this.context=context;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_NOTES_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop existing old tables
        db.execSQL("DROP TABLE IF EXISTS "+NOTES_TABLE);
        //Create Table again
        onCreate(db);
    }

    public void insertNote(NotesData data){
        db=this.getWritableDatabase();
        ContentValues values= new ContentValues();
        values.put(NOTE,data.getNotes().toString());
        db.insert(NOTES_TABLE,null,values);
    }

    public List<NotesData> getAllNotes(){
        db=getReadableDatabase();
        List<NotesData> list=new ArrayList<>();
        Cursor cur=db.query(NOTES_TABLE,null,null,null,null,null,null,null);
        db.beginTransaction();
        try{
            if(cur!=null){
                if(cur.moveToFirst()) {
                    do{
                        NotesData d = new NotesData();
                        d.setId(cur.getInt(cur.getColumnIndex(ID)));
                        d.setNotes(cur.getString(cur.getColumnIndex(NOTE)));
                        list.add(d);
                    }while(cur.moveToNext());
                }
            }
        }
        finally {
            db.endTransaction();
            cur.close();
        }
        return list;
    }



    public void updateNotes(int id,String note){
        db=getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(NOTE,note);
        db.update(NOTES_TABLE,cv,ID+"=?",new String[] {String.valueOf(note)});
    }


    public void deletenote(int id){
        db=getWritableDatabase();
        db.delete(NOTES_TABLE, ID + "=?", new String[]{String.valueOf(id)});
    }

}

我正在写笔记的活动

public class writing_notes extends AppCompatActivity {

    EditText editText;
    Button SaveButton;
    DBHandler_Notes db;


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

        editText = findViewById(R.id.EditText_Note);
        SaveButton = findViewById(R.id.saveNoteButton);
        db = new DBHandler_Notes(getApplicationContext());


        Intent intent = new Intent();
        String from = "first";
        from= intent.getStringExtra("source");

        if("second".equals(from)){
            editText.setText(intent.getStringExtra("noteString"));
            SaveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    db.updateNotes(intent.getIntExtra("id",0),editText.getText().toString());
                    setResult(RESULT_OK);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            });
        }
        else {
            SaveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String note = editText.getText().toString();
                    intent.putExtra("note",note);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            });
        }



    }
}

编辑:我附上了 NotesFragment 和 writing_activity 的屏幕截图,在 此处输入图像描述

标签: javaandroid-intentandroid-recyclerviewstartactivityforresult

解决方案


推荐阅读