Search code examples
androidlistviewandroid-activityandroid-contextlistadapter

How to get Activity reference in ListView Adapter class?


I am trying to request the phone call permission from the list adapter class on the click of a button which requires the Activity as the first argument.

 ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CALL_PHONE},1 );

here the mContext is passed from one of the activity. but it show error :

Wrong 1st argument type. Found: 'android.content.Context', required: 'android.app.Activity'.

i tried to pass every context and also the getParent() activity but it's not working. Is there any way to get the Activity and use it in list adapter ?.

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                dialNumber(employee.get(i).getNumber());
                }
            else
                {

                    Log.i(TAG, "onClick: you don't have permission to call");
                    ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CALL_PHONE},1 );
                }

                Log.i(TAG, "onClick: Wroks " + getItemId(i));

        }

this is the full code for button click listener.

Thankyou.


Solution

  • Having references of Activity in Adapter class is a bad approach. Anything that should be done within the activity class such as UI changes, displaying dialog etc. should not be done anywhere else but from the activity itself.

    Solution:
    1) Create an interface

    public interface MyListener {
         void doSomething(Params... params);
    }
    

    2) Implement it in Activity class

    class MyActivity extends AppCompatActivity implements MyListener{ 
           new MyAdapter(this);  
    
           void doSomething(Params... params){
                 //Request Permission here
           }
    }
    

    3) Use like this in Adapter class

    class MyAdapter extends .....{
          MyListener myListener;
    
          MyAdapter(Context mContext){
               if(mContext instanceOf MyListener)
                     myListener = (MyListener) mContext;
          }
    
          void anotherFunction(){
                 myListener.doSomething(Params... params) 
         }
    }