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



主活动@覆盖

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();
}

标题

异步任务:

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;

我想将应用程序上下文从主活动传递到另一个实现asynctask的java类文件。这样做是为了去除异步任务中onPostExecute((的适配器附加,因为这样做会在创建apk时创建一个。我该怎么办??

将其传递到构造函数中,而不是作为方法参数。那么就不需要依赖于泛型参数了

将Context对象传递到AsyncTask的构造函数之后,就像您已经做的那样然后,当您构建AsyncTask:时

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

另一个建议是将AsyncTask类作为活动的私有内部类,这样我很确定您将可以访问getApplicationContext((。

最新更新