简体   繁体   中英

How to pass application context from main activity to a class that implements async task to attach adapter from onPostExecute() in async task?

main activity @Override

    protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mContext = getApplicationContext();


            recyclerView = findViewById(R.id.recyclerview_student);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));

            buttonAddTask = findViewById(R.id.Fbutton_add);
            buttonAddTask.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
               Intent intent = new Intent(MainActivity.this, addStudent.class);
               startActivity(intent);
        }
    });

        final getStudents getstudents = new getStudents(getApplicationContext());
                getstudents.execute();
}

Heading

async task:

     public class getStudents extends AsyncTask<Void, Void, List<Student>>
     {
             private Context mContext;
             public  getStudents(Context context)
             {
                    mContext=context;
             }

     @Override
     protected List<Student> doInBackground(Void... voids) 
     {
             List<Student> studentList= 
             DatabaseClient.getInstance(mContext.getApplicationContext().);

              return  studentList;

I want to pass application context from main activity to a different java class file that implements asynctask. This is done in order to take away the adapter attaching from onPostExecute() in async task since doing that creates an while creating apk. what should i do ??

Pass it in the constructor, not as a method parameter. Then you don't need to depend on the generic parameters.

After Passing a Context object into the AsyncTask's constructor, like you already done and then, when you are constructing your AsyncTask :

getStudents stud= new getStudents (this);
stud.execute(...);

another suggestion is to put your AsyncTask class as a private inner class to your activity - that way I am pretty sure you will have access to getApplicationContext ().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM