Android equivalent of getActivity() from/in ActionBarActivity

MrLeblond picture MrLeblond · May 28, 2015 · Viewed 8.6k times · Source

Like my title says, i'm looking for an equivalent of getActivity() in my ActionBarActivity class in my Android project.

I want to pass an Activity parameter in AsyncTask declaration object, because i'm using an Activity object in my custom AsyncTask extended class

Here an example simplest code of my project

public class EventCreator extends ActionBarActivity {

private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_even_creator);
    View v = getLayoutInflater().inflate(R.layout.activity_even_creator,null);
    this.context = this.getBaseContext();

    final Button createButton = (Button)findViewById(R.id.createEventButton);
    createButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AsyncTask<Void,Void,Boolean> eventCreatorSend = new SendEvents(/* here need activity object */);
            eventCreatorSend.execute();
        }
    });

}

    class SendEvents extends AsyncTask<Void,Void,Boolean> {

        public Activity act;

        SendEvents(Activity a) {
            this.act = a;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
        }

        @Override
        protected Boolean doInBackground(Void... params) {

            SystemClock.sleep(5000);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean params) {
            if (params){

                ((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.GONE);
                act.finish();
            }
            else {
                ((LinearLayout)act.findViewById(R.id.layout_loader_create_event)).setVisibility(View.VISIBLE);
                Toast.makeText(act,"Fail to send event",Toast.LENGTH_SHORT).show();
            }
        }


    };
}

In a time, i thought use getParent() from ActionBarActivity class, but it return a null object. So how to get the Activity object i want in ActionBarActivity class ?

Answer

frankie015 picture frankie015 · May 28, 2015

Try nameofactivity.this instead getActivity()

I always use getActivity() in Fragments Activities and .this in any other kind of Activity.