android – 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?-ThrowExceptions

Exception or error:

I tried several ways but always get a NPE due to difference in lifecycles etc
This is my MainActivity where I need to transfer a new Contact to the adapter

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();
        });
    }}

the line in question (this line is red now), where I need to transfer data to the adapter is
adapter.addContact(contact);

this is my 2nd activity that is used to initiated adapter’s object and recycler view (and that is used to display database)

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();
    }

And this is my adapter 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();
    }
}

I would be really grateful for any help

How to solve:

You can’t access adapter from your MainActivity, send you Contact data to the other Activity by using Intent’s(putExtra) and use adapter.addContact() there.

###

Create a method in your activity like

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

you can call this method from MainActivity when you have data

Leave a Reply

Your email address will not be published. Required fields are marked *