简体   繁体   English

如何将应用程序上下文从主活动传递给实现异步任务的类,以从异步任务中的 onPostExecute() 附加适配器?

[英]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主要活动@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.我想将应用程序上下文从主活动传递到实现 asynctask 的不同 java 类文件。 This is done in order to take away the adapter attaching from onPostExecute() in async task since doing that creates an while creating apk.这样做是为了从异步任务中的 onPostExecute() 中移除适配器,因为这样做会在创建 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 :在将 Context 对象传递给 AsyncTask 的构造函数之后,就像您已经完成的那样,然后,当您构造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 ().另一个建议是将您的AsyncTask类作为您的活动的私有内部类 - 这样我很确定您将有权访问getApplicationContext ()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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