Home > Software engineering >  how to pass data from activity to adapter?
how to pass data from activity to adapter?

Time:09-30

I have 2 Activities. Activity A contains recyclerview, and Activity B is going to pass the Arraylist data to recyclerview in Acrivity A.

my Adapter is like this.

public MainAdapter(MainActivity context,ArrayList<MainData> list) {
    this.context = context;
    this.list = list;
}

and MetaData.

public MainData(String tv_name, String tv_content) {
    this.tv_name = tv_name;
    this.tv_content = tv_content;
}

Activity A (that receives arraylist data):

   recyclerView = (RecyclerView) findViewById(R.id.rv);
    linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);

    list = new ArrayList<>();

    list = (ArrayList<MainData>)getIntent().getSerializableExtra("key");

    adapter = new MainAdapter(this,list);
    recyclerView.setAdapter(adapter);

AAnd Activity B that pass Arraylist :

 Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        Intent intent = new Intent(upload.this, MainActivity.class);

            ArrayList<MainData> list = new ArrayList<MainData>();

            EditText edit = (EditText) findViewById(R.id.edittext_name);
            String tv_name = edit.getText().toString();

            EditText edit_main = (EditText) findViewById(R.id.edittext_main);
            String tv_content = edit_main.getText().toString();

            list.add(new MainData(tv_name,tv_content));

            intent.putExtra("key", list);
            startActivity(intent);

        }
    });

And it throws Runtime Exception.

CodePudding user response:

The context you provided is not complete, please review the Android guide. If you need to transfer data between activities, please check this article enter link description here

CodePudding user response:

You should use Intent extras to pass the the array list from ActivityB to ActivityA and in the ActivityA you have to pass the list to the adapter so it will set the data on the recyclerView.

You shouldn't directly pass the data from ActivityB to the adapter of AdapterA

This might be helpful: https://developer.android.com/reference/android/content/Intent

  • Related