Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access "findViewById" in AsyncTask

I'm using an AsyncTask class to download data from a php file. After downloading, I want to put this data, into different TextViews, but I can't use the method findViewById.

The problem, is that I'm doing this by separate classes, and it all within a fragment.

This is my code:

public class RecuperarComentarisFoto extends AsyncTask<String, String, String>{
private Context mContext;
[...]
public RecuperarComentarisFoto(Context context){
    this.mContext=context;
}
@Override
protected void onPreExecute() {
    [...]
}

@Override
protected String doInBackground(String... arg0) { 
    params.add(new BasicNameValuePair("pid", "1"));
    JSONObject json = jsonParser.makeHttpRequest(url_get_comentaris, "GET", params);
    JSONArray productObj;
    //HERE I RETRIEVE DATA FROM JSON. ITS WORKING OK.

    return null;
}

And where I've the problem:

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    this.pDialog.dismiss();
    TextView comentariEditText = (TextView) findViewById(R.id.commentsMostrar);
}

I've tried this:

        TextView comentariEditText = (TextView) mContext.findViewById(R.id.commentsMostrar);

But isn't working too.

Note that I'm calling this AsyncTask from a Fragment. As you can see, I had to pass the context retrieved by getActivity() to the AsyncTask:

public class MyFragmentA extends Fragment {
Context cont;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);

    cont=getActivity();
    new RecuperarComentarisFoto(cont).execute();
    return myFragmentView;
}


}

What should I do?

Thank you.

like image 451
Reinherd Avatar asked Jan 04 '13 20:01

Reinherd


1 Answers

Try this ((Activity)context) it works for me...

TextView comentariEditText = 
(TextView) ((Activity)context).findViewById(R.id.commentsMostrar);
like image 91
Khalid Musa Sagar Avatar answered Nov 16 '22 23:11

Khalid Musa Sagar