如何从 MainActivity 获取在另一个 activity 中启动的对象的适配器(或实际上将数据传输到适配器)?

How can I get the Adapter (or actually transfer data to the adapter)that's object is initiated in the other activity from the MainActivity?

我尝试了几种方法,但由于生命周期等方面的差异,总是得到 NPE 这是我的 MainActivity,我需要在其中将新联系人传输到适配器

public class MainActivity extends AppCompatActivity {
    private TextInputEditText textInputLastName;
    private TextInputEditText textInputFirstName;
    private TextInputEditText textInputMiddleName;
    private TextInputEditText textInputAge;
    private int age;
    private TextInputLayout lastNameWrapper;
    private TextInputLayout ageWrapper;
    private ViewGroup parent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lastNameWrapper = findViewById(R.id.last_name_wrapper);
        ageWrapper = findViewById(R.id.age_wrapper);
        textInputLastName = findViewById(R.id.text_input_last_name);
        textInputFirstName = findViewById(R.id.text_input_first_name);
        textInputMiddleName = findViewById(R.id.text_input_middle_name);
        textInputAge = findViewById(R.id.text_input_age);
        addButtonMainActivity();
    }

    private void addButtonMainActivity() {
        final Button buttonSendData = findViewById(R.id.button_send);
        buttonSendData.setOnClickListener(view -> {
            startActivity(new Intent(this, ShowDatabaseActivity.class));
            if (textInputLastName.getText().toString().isEmpty()) {
                lastNameWrapper.setError("Enter your Last Name");
                return;
            } else if (TextUtils.isEmpty(textInputAge.getText())) {
                ageWrapper.setError("Enter your Age");
                return;
            }
            age = Integer.parseInt(String.valueOf(textInputAge.getText()));
            final Handler handler = new Handler();
            Thread backgroundThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String lastName = textInputLastName.getText().toString();
                    String firstName = textInputFirstName.getText().toString();
                    String middleName = textInputMiddleName.getText().toString();
                    int age = Integer.parseInt(textInputAge.getText().toString());
                    Contact contact = new Contact(lastName, firstName, middleName, age);
                    AppDatabase.getINSTANCE(MainActivity.this).contactDao().insert(contact);
                    AppDatabase.getINSTANCE(MainActivity.this).contactDao().getAll();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter.addContact(contact);
                        }
                    });
                }
            });
            backgroundThread.start();
        });
    }}

有问题的线(这条线现在是红色的),我需要向适配器传输数据的地方是 adapter.addContact(contact);

这是我的第二个activity,用于启动适配器的对象和回收器视图(以及用于显示数据库)

public class ShowDatabaseActivity extends AppCompatActivity {
    private List<Contact> allContacts = new ArrayList<>();
    public ContactsListAdapter adapter;
    private ViewGroup parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        adapter = new ContactsListAdapter(allContacts, ShowDatabaseActivity.this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        getTableData();
    }

这是我的适配器class

public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;
    private LayoutInflater inflater;

    public LayoutInflater getInflater() {
        return inflater;
    }

    public ContactsListAdapter(@NonNull List<Contact> contacts, Context context) {
        this.contacts = contacts;
        this.context = context;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
        Contact currentContact = contacts.get(position);
        if (currentContact != null) {
            holder.contactLastNameView.setText(currentContact.getLastName());
            holder.contactFirstNameView.setText(currentContact.getFirstName());
            holder.contactMiddleNameView.setText(currentContact.getMiddleName());
            holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
        } else {
            holder.contactLastNameView.setText("No information");
            holder.contactFirstNameView.setText("No information");
            holder.contactMiddleNameView.setText("No information");
            holder.contactAgeView.setText("No information");
        }
    }

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

    public class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        public TextView getContactLastNameView() {
            return contactLastNameView;
        }

        public TextView getContactFirstNameView() {
            return contactFirstNameView;
        }

        public TextView getContactMiddleNameView() {
            return contactMiddleNameView;
        }

        public TextView getContactAgeView() {
            return contactAgeView;
        }

        public ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    public void addContact(Contact contact) {
        contacts.add(contact);
        notifyDataSetChanged();
    }
}

如果有任何帮助,我将不胜感激

在你的activity中创建一个方法

public void showData(List<Contact> allContacts) {
    //here you can show the data received from main activity
    this.addContacts.addAll(allContacts);
    adapter.notifyDataSetChanged();
}

当你有数据

时,你可以从MainActivity调用这个方法

您无法从 MainActivity 访问适配器,无法通过使用 Intent 的 (putExtra) 将联系人数据发送给另一个 Activity 并在那里使用 adapter.addContact()。