Search code examples
javaandroidandroid-intentandroid-activityandroid-adapter

Intent problem: how to use MainActivity from another class "Adapter" to pass data to SecondActivity


This is in Adapter.Java

    public void onClick(View v) {
        String name=listItemData.get(i).getName();
        Intent intent = Intent(MainActivity.this, SecondActivity.class);
        intent.putExtra("NAME", name);
    }

I have now idea how to use MainActivity.this when I'm not in MainActivity class..


Solution

  • Try following code.

    Solution 1

    You have to pass context while you initialized Adapter in MainActivity.

    In MainActivity.this:

    XyzAdapter adapter = new XyzAdapter(MainActivity.this, .. ..)
    

    In your Adapter:

    private Context mContext;
       public XyzAdapter(Context context .. ..){
          mContext = context;
       }
    

    And then you can do like below:

    public void onClick(View v) {
            String name=listItemData.get(i).getName();
            Intent intent = Intent(mContext, SecondActivity.class);
            intent.putExtra("NAME", name);
            mContext.startActivity(intent);
        }
    

    Solution 2

    Another option is interface

    Create one interface like below:

    public interface AdapterInterface {
            public void buttonPressed();
        }
    

    Now in your adapter:

    AdapterInterface buttonListener;
    public XyzAdapter(Context context, AdapterInterface buttonListener)
    {
      super(context,c,flags);
      this.buttonListener = buttonListener;
    }
    
    public void onClick(View v) {
          buttonListener.buttonPressed()
    }
    

    In your Activity:

    AdapterInterface buttonListener;
    public MainActivity extends AppCompactActivity implements AdapterInterface{
    

    in onCreate

    buttonListener = this;
    
    XyzAdapter adapter = new XyzAdapter(MainActivity.this, buttonListener  .. ..)
    
    
    
    @Override
    public void buttonPressed(){
      // here you have to do once your click perform
    }