[java] How to start Activity in adapter?

I have a ListActivity with my customized adapter and inside each of the view, it may have some buttons, in which I need to implement OnClickListener. I need to implement the OnClickListener in the adapter. However, I don't know how to call the function like startActivity() or setResult(). Since the adapter doesn't extend to Activity.

So what is the best way to solve this problem?

Thanks.

This question is related to java android android-activity adapter

The answer is


callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

      public MyInterface{
         public void  yourmethod(//incase needs parameters );
         }

In Adapter Let's Say MyAdapter:

    public MyAdapter extends BaseAdapter{
       private MyInterface listener;

    MyAdapter(Context context){
        try {
            this. listener = (( MyInterface ) context);
              } catch (ClassCastException e) {
               throw new ClassCastException("Activity must implement MyInterface");
          }

//do this where u need to fire listener l

          try {
                listener . yourmethod ();
            } catch (ClassCastException exception) {
               // do something
            }

      In Activity Implement your method:


         MyActivity extends AppCompatActivity implements MyInterface{

                yourmethod(){
                //do whatever you want
                     }
                     }

For newer versions of sdk you have to set flag activity task.

public void onClick(View v)
 {
     Intent myactivity = new Intent(context.getApplicationContext(), OtherActivity.class);
     myactivity.addFlags(FLAG_ACTIVITY_NEW_TASK);
     context.getApplicationContext().startActivity(myactivity);
 }

Simple way to start activity in Adopter's button onClickListener:

Intent myIntent = new Intent(view.getContext(),Event_Member_list.class);                    myIntent.putExtra("intVariableName", eventsList.get(position).getEvent_id());
                view.getContext().startActivity(myIntent);

public class MyAdapter extends Adapter {
     private Context context;      


     public MyAdapter(Context context) {
          this.context = context;         
     }


     public View getView(...){  
         View v;  
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                  Intent intent= new Intent(context, ToActivity.class); 
                   intent.putExtra("your_extra","your_class_value");
                 context.startActivity(intent);
             }
         });
     }
}

If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.

btnInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                intent.setData(Uri.parse(link));
                context.startActivity(intent);
            }
        });

When implementing the onClickListener, you can use v.getContext.startActivity.

btn.setOnClickListener(new OnClickListener() {                  
    @Override
    public void onClick(View v) {
        v.getContext().startActivity(PUT_YOUR_INTENT_HERE);
    }
});

First Solution:

You can call start activity inside your adapter like this:

public class YourAdapter extends Adapter {
     private Context context;

     public YourAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

Second Solution:

You can call onClickListener of your button out of the YourAdapter class. Follow these steps:

Craete an interface like this:

public YourInterface{
         public void  yourMethod(args...);
}

Then inside your adapter:

    public YourAdapter extends BaseAdapter{
               private YourInterface listener;

           public YourAdapter (Context context, YourInterface listener){
                    this.listener = listener;
                    this.context = context;
           }

           public View getView(...){
                View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 listener.yourMethod(args);
             }
         });
}

And where you initiate yourAdapter will be like this:

YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
            startActivity(...);
        });

This link can be useful for you.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to adapter

Bridged networking not working in Virtualbox under Windows 10 Remove all items from RecyclerView NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use Call Activity method from adapter Setting network adapter metric priority in Windows 7 How to remove listview all items How to start Activity in adapter? Clear listview content? Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"