0

I tried a lot of things but I can't get it to work... I try to pass this String Variable (when i click Item in RecyclerView) to my MainActivity. What works bad is calling the function (OnRecyclerViewItemClick) and changing the variable(GetUrlFromItem). My version of Android Studio is 2.3.3

I really need do this:

My RecyclerView:

public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView titulo;
    Button playbtn01;
    List<Fuente> ListaObjeto;

    public viewHolder(View itemView,List<Fuente> datos) {
        super(itemView);

        ListaObjeto = datos;

        titulo = (TextView) itemView.findViewById(R.id.texto);
        playbtn01 = (Button) itemView.findViewById(R.id.playbtn00);

        playbtn01.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int position = getAdapterPosition();
        Fuente objeto = ListaObjeto.get(position);

        if (view.getId() == playbtn01.getId()) {

            MainActivity mainActivity = new MainActivity:
            mainActivity.OnRecyclerViewItemClick();      /// initiate Void in Main
            mainActivity.GetUrlFromItem = objeto.GetUrl; //Change Variable of Main

        }
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

    public String GetUrlFromItem; 

    public void OnRecyclerViewItemClick() {
        if (GetUrlFromItem  == "..."){
            doSomething...
        }
    }
}
0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22
Jose
  • 401
  • 4
  • 15

1 Answers1

0

There are two big problems that I see.

The first is how you get a MainActivity instance to work with. In your question, you have this line of code:

MainActivity mainActivity = new MainActivity:

Calling new is going to do exactly what it sounds like: create a new instance of the MainActivity class. You do not want a new instance! You want your alive and running instance.

There are a handful of ways to get ahold of your alive and running MainActivity, but probably the simplest one for now is going to be casting your ViewHolder's itemView's Context. So instead of the above, write something like this:

MainActivity mainActivity = (MainActivity) itemView.getContext();

The second big problem is in the next two lines:

mainActivity.OnRecyclerViewItemClick();
mainActivity.GetUrlFromItem = objeto.GetUrl;

The problem here is the order of these two statements. Because you invoke mainActivity.OnRecyclerViewItemClick() before setting the value of mainActivity.GetUrlFromItem, the value will not be updated when OnRecyclerViewItemClick() is executed.

Simply swap the order of these two lines.

Ben P.
  • 52,661
  • 6
  • 95
  • 123