onRotate getactivity为null

时间:2014-10-05 19:46:09

标签: android gridview android-fragments picasso

我使用picasso在网格视图中显示从json解析的一堆图像,但是在旋转应用程序崩溃时,postexecute中的getActivity()变为null!

我的片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_upload_data, container, false);

        images_gv=(GridView) v.findViewById(R.id.images);
        new RetrieveItemData().execute();


        return v;
    }

这是我片段中的RetieveItemData类:

 private class RetrieveItemData extends AsyncTask<Void, Void, Void> {
        private ArrayList<String> imageList=new ArrayList<String>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(Constant.URL, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    JSONArray images;
                    if(!jsonObj.isNull(TAG_IMAGES)) {
                      images=jsonObj.getJSONArray(TAG_IMAGES);
                        //looping through Features
                        for (int i = 0; i < images.length(); i++) {
                            imageList.add(images.getString(i));
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            imageAdapter=new GridViewAdapter(getActivity().getApplicationContext(), imageList);
            images_gv.setAdapter(imageAdapter);


        }

    }

这是我的适配器:

public class GridViewAdapter extends BaseAdapter {

    final Context context;
    private List<String> urls = new ArrayList<String>();

    public GridViewAdapter(Context context,ArrayList<String> urls) {
        this.context = context;
        this.urls=urls;

    }

    @Override public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.gridview_image_item, null);
        }


        ImageView  imageview = (ImageView) convertView.findViewById(R.id.image_item);

// Get the image URL for the current position.
        String url = getItem(position);

// Trigger the download of the URL asynchronously into the image view.
        Picasso.with(context) //
                .load(url) //
                .fit()
                .into(imageview);

        return convertView;
    }

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

    @Override public String getItem(int position) {
        return urls.get(position);
    }

    @Override public long getItemId(int position) {
        return position;
    }

    final class SquaredImageView extends ImageView {
        public SquaredImageView(Context context) {
            super(context);
        }

        public SquaredImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
        }
    }

1 个答案:

答案 0 :(得分:2)

执行任务的Fragment不再附加到Activity。当设备的配置发生变化(例如更改设备的方向)时,整个活动将被销毁并重新创建,因此系统正在创建一个全新的活动(并附加一个全新的碎片)。

最简单的解决方案是在销毁片段时取消任务。新创建的Fragment将再次启动任务。这意味着您可能会进行两次网络连接,因此可能会有更高效的数据使用解决方案,但这并不算太糟糕,因为在数据加载时不太可能发生旋转。

您可以通过调整Fragment来实现这一目标:

RetrieveItemData mRetrieveDataTask;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_upload_data, container, false);

    images_gv=(GridView) v.findViewById(R.id.images);

    mRetrieveDataTask = new RetrieveItemData();
    mRetrieveDataTask.execute();

    return v;
}

@Override
public void onDestroyView(){
    super.onDestroyView();
    mRetrieveDataTask.cancel(false);
}