-1

So I want to send an object (Person) to the Main Activity from another one which is using a recyclerView with a ViewHolder, then close the activity using the viewHolder and print the text on a textView of the Main Activity, I didn't know how to send an object from a viewHolder to another activity so I tried using an interface but I'm getting this error and I don't know how to fix it or what's the cause:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

Which points to this line: obj.SendData_FromViewholder(selectedPerson);

The viewHolder class

class PersonaViewHolder extends RecyclerView.ViewHolder{

    public Person selectedPerson;
    public ArrayList<SendData_FromViewholder> array = new ArrayList();

    public PersonaViewHolder(@NonNull View itemView) {
        super(itemView);

        ActivityMain actMain = new ActivityMain();
        this.addInterfaz(actMain);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectedPerson = (Person) v.getTag();               

                for(SendData_FromViewholder obj : array){       
                    obj.SendData_FromViewholder(selectedPerson);
                }

                ((Activity_PersonList)v.getContext()).finish();     // activity of the recyclerView
            }
        });
    }

    public void addInterfaz(SendData_FromViewholder interface){
        array.add(interface);
    }
}

Main activity with the interface implementation

public class ActivityMain extends AppCompatActivity implements SendData_FromViewholder {
    @Override
    public void getPersonFromViewholder(Person person) {
        TextView textView = findViewById(R.id.tv_mainHeader);
        textView.setText(person.getName()+" - ID:"+person.get_id());
    }
}

The interface class

public interface SendData_FromViewholder {
    void getPersonFromViewholder(Person person);
}

  • `ActivityMain actMain = new ActivityMain();` – You cannot do that. `Activity` classes must be instantiated and initialized by the system for them to work correctly. If this `Activity` with the `RecyclerView` was started from `ActivityMain`, you could instead use `startActivityForResult()`/`setResult()` to send the selected data back to `ActivityMain` on an `Intent`; e.g., like is demonstrated in these posts: https://stackoverflow.com/q/920306, https://stackoverflow.com/q/2139134. – Mike M. Dec 07 '19 at 23:54

1 Answers1

0

You can pass an object from view holder to an activity , the same way you do it from an activity to another activity by using intents , and passing the object as serializable (you have to make the person class implement serializable)

Khaled Ahmed
  • 156
  • 3
  • 7