Gustavomcls Gustavomcls - 9 days ago 6
Java Question

How start an activity using Intent inside a inner static class?

I have a static and inner class inside my

Activityclass
. I need to call an Activity using
Intent(context,nameOfTheNewActivity.class)
because I am trying to call an
Intent
when an item from a
RecyclerView.ViewHolder
is clicked. I had to Override the
onClick
to get the position of the item was clicked using
getLayoutPosition()
(this getLayoutPosition() worked fine).

Now when I try to use Intent I have the error:


Non-static method cannot be referenced by a static context.


I read another links from Stackoverflow like this. How do I call an Intent in this case of static context and inside an inner class, I.e, how do I get the context inside an inner class, and how do I solve the **fundamental ** error to do not call a non static class from an static class?

I tried the following to no avail:


  1. Get the context from the View using v.context but I continue with the problem - and still calling a non static method from a static context.

  2. "Static" startActivity(Intent) method?

  3. Delete the word static form my inner class, but did not solve and the app crashes.



My code:

public class ActivityOne extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {

public static class MessageViewHolderOfFriend extends RecyclerView.ViewHolder { public MessageViewHolderOfFriend(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
;

Intent intent = new Intent(v.getContext(),NewActivityToRun.class);
startActivity(intent);//Error in this Line//
}
});
}
}

Answer

Try using the reference of the Activity.

ActivityOne.this.startActivity(intent);

If that doesn't work, then know that startActivity is a method of any Context.

class MessageViewHolderOfFriend extends RecyclerView.ViewHolder {

    private final Context context;

    public  MessageViewHolderOfFriend(View v) {
        super(v);
        context = v.getContext();

        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,NewActivityToRun.class);
                context.startActivity(intent);
            }
        });

    }

Ref. How to open a different activity on recyclerView item onclick

Regarding

delete the word static from my inner class, but did not solve and the app crashes

You probably were closer to the solution with the removal of static. The app actually built. The app crashing means you should read the logcat and implement the proper solution.