从AsyncTask更新Fragment的UI会生成NullPointerException

时间:2014-06-07 07:03:31

标签: java android android-fragments android-asynctask

我正在尝试在执行asynctask后更新片段的UI。

以下是我的工作:

public class OpinionFragment extends Fragment {

    private static final String BUNDLE_POSTTION = "opinion_position";
    private static final String BUNDLE_OPINION_TEXT = "opinion_text";
    private CirclePulseView circlePulseView;
    private TextView opinionTV;
    private String opinionText;

    public static OpinionFragment newInstance(int position, String opinionText) {
        Bundle args = new Bundle();
        //add parameters to the bundle here
        //args.putInt(BUNDLE_OBJECTIVE_ID, objective.getLocalId());
        args.putInt(BUNDLE_POSTTION, position);
        args.putString(BUNDLE_OPINION_TEXT, opinionText);

        OpinionFragment fragment = new OpinionFragment();
        fragment.setArguments(args);

        return fragment;
    }

    public OpinionFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            opinionText = args.getString(BUNDLE_OPINION_TEXT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_opinion, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        opinionTV = (TextView) view.findViewById(R.id.opinionTV);
        opinionTV.setText(opinionText);
        circlePulseView = (CirclePulseView) view.findViewById(R.id.circle_view);
    }

    public void translateReview(String text) {
        if (text != null) {
            new TranslateReviewAsyncTask(text).execute();
        }
    }

    class TranslateReviewAsyncTask extends AsyncTask<Void, Void, String> {

        private String textToTranslate;

        public TranslateReviewAsyncTask(String textToTranslate) {
            this.textToTranslate = textToTranslate;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            circlePulseView.setVisibility(View.VISIBLE);
            opinionTV.setVisibility(View.GONE);
        }

        @Override
        protected String doInBackground(Void... params) {
            String result;
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, Constants.TIMEOUT_MILISEC);
            HttpConnectionParams.setSoTimeout(httpParams, Constants.TIMEOUT_MILISEC);
            HttpParams p = new BasicHttpParams();
            // Instantiate an HttpClient
            HttpClient httpclient = new DefaultHttpClient(p);
            String textParam = null;
            try {
                textParam = URLEncoder.encode(textToTranslate, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String url = "http://192.168.0.104:8080/ClujTouristWS/webresources/tourists/translate/" + textParam;
            HttpGet httpGet = new HttpGet(url);

            // Instantiate a GET HTTP method
            try {
                Log.i(getClass().getSimpleName(), "send  task - start");
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httpGet,
                        responseHandler);
                Log.d(LoginTouristAsyncTask.class.getCanonicalName(), "Login response: " + responseBody);
                result = responseBody;
            } catch (ClientProtocolException e) {
                e.printStackTrace();
                result = "error";
            } catch (IOException e) {
                e.printStackTrace();
                result = "error";
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null && !s.equals("error")) {
                System.out.println("This is your translated text:  " + s);
            }
            circlePulseView.setVisibility(View.GONE);
            opinionTV.setVisibility(View.VISIBLE);
            opinionTV.setText(s);
        }
    }

}

我在按下父片段中的按钮后尝试这样做:

translateTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpinionFragment fragment = (OpinionFragment) opinionsAdapter.getItem(currentPage);
                fragment.translateReview(opinionsAdapter.getObjectiveReviews().get(currentPage));
            }
        });

我的代码崩溃了,onPreExecute

@Override
        protected void onPreExecute() {
            super.onPreExecute();
            circlePulseView.setVisibility(View.VISIBLE);
            opinionTV.setVisibility(View.GONE);
        }

mCirclePulseView为空......我不知道如何解决这个问题....

没有其他合适的时间来触发AsyncTask,因为: 我所拥有的是一个带有viewPager的Fragment,其中包含视图分页器外部的片段和2个按钮。只有在按下主片段中的按钮后,我才应该更新寻呼机内当前片段的内容...

这是View Pager的适配器类:

public class OpinionPagerAdapter extends FragmentStatePagerAdapter {

List<String> objectiveReviews = new ArrayList<String>();
private Map<Integer, Fragment> mPageReferenceMap = new HashMap<Integer,Fragment>();

public OpinionPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = OpinionFragment.newInstance(position,objectiveReviews.get(position));
    mPageReferenceMap.put(position, fragment);
    return fragment;
}

@Override
public int getCount() {
    return objectiveReviews.size();
}

public void addOpinionsToList(List<String> objectiveReviews){
    this.objectiveReviews.clear();
    for (String o : objectiveReviews) {
        //if (CategoryUtils.getInstance().checkCategorySelected(o.getCategoryID())) {
        this.objectiveReviews.add(o);
        //}
    }
    notifyDataSetChanged();
}

public List<String> getObjectiveReviews(){
    return this.objectiveReviews;
}

public Fragment getFragment(int key){
    return mPageReferenceMap.get(key);
}

}

0 个答案:

没有答案