简体   繁体   English

Android asynctask将不接受上下文

[英]Android asynctask won't accept context

I have a strange problem. 我有一个奇怪的问题。 I am trying to change a TextView but cannot findViewById , it says that the findViewById cannot be resolved. 我正在尝试更改TextView但无法找到findViewById ,它表示无法解析findViewById I have a Main Activity from which I am calling AsyncTask(Context context) . 我有一个主要活动,从中可以调用AsyncTask(Context context) In the constructor I pass this from main activity, I have already tried with Main Activity.getContext() but it still doesn't work. 在构造函数中,我从main活动传递了此信息,我已经尝试使用Main Activity.getContext()了,但仍然无法正常工作。

Any help is welcome. 欢迎任何帮助。

public class UcitavanjeUpozadini extends AsyncTask<Void, Void, Void> {

private Context context;
private ProgressDialog progressDialog;
private UcitavanjeHelperKlasa helperKlasa;
private List<OglasHelper> lista;

public UcitavanjeUpozadini(Context context){
    this.context = context;
    this.progressDialog = null;
    this.helperKlasa = new UcitavanjeHelperKlasa();
    this.lista = new ArrayList<OglasHelper>();

}

Is this in a fragment or in an activity? 这是片段还是活动? Have you tried getApplicationContext()? 您是否尝试过getApplicationContext()?

findViewById isn't a function of Context, its a function of Activity. findViewById不是Context的功能,而是Activity的功能。 Generally you should pass in the view directly rather than an Activity and call findViewById on it. 通常,您应该直接传递视图而不是传递活动,并在其上调用findViewById。

You should do something like this if you have an activity, change the TextView value in onPostExecute: 如果您有活动,则应该执行以下操作,在onPostExecute中更改TextView值:

private MyActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState){ 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        mTextView = (TextView) findViewById(R.id.textview);
        new MyAsyncTask().execute();
    }

    private class MyAsyncTask extends AsyncTask<Void, Void, Boolean>{

        @Override
        protected void onPreExecute(){
            mTextView.setText("text changed before background operation");
        }

        @Override
        protected Boolean doInBackground(Void... params){
            //perform your background operations changing the paramaters 
            //and return type accordingly
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result){
            mTextView.setText("text changed after background operation");
        }
    }
}

If you need to put the AsyncTask in a separate file, you could add a callback to an interface implemented in your Activity or pass the TextView to the AsyncTask during the instantiation 如果需要将AsyncTask放在单独的文件中,则可以在实例化过程中向在Activity中实现的接口添加回调,也可以将TextView传递给AsyncTask

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

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