从另一个类更新ListFragment

时间:2014-10-08 12:31:25

标签: android android-fragments android-fragmentactivity

我有一个帮助下载数据并将其存储在内容提供程序中的类,我有一个ListFragment,它从用户登录时加载来自提供程序的数据,下载数据并且一切正常,但是当数据有更新时,该类意味着下载数据并保存,但是当我调用ListFragment进行更新时,它会崩溃。任何帮助将不胜感激,我的代码如下:

这是下载数据的类

public class OrderDataRetrieval {

    final Context context;
    ProgressDialog pDiag;

    public OrderDataRetrieval(final Context myContext){
        context = myContext;
    }

    public void getData(String getToken, final Uri uri1, final Uri uri2, final Uri uri3){

        pDiag = new ProgressDialog(context.getApplicationContext());
        pDiag.setMessage("Loading...");
        pDiag.setCancelable(false);
        String order_URL = "http://xxxxxxxxxxxxxxxxx.json?token=" + getToken + "&contain=nnnnn,mmmm&uuuuu=0";
        //pDiag.show();
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        final Entry entry = cache.get(order_URL);
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                order_URL, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        //pDiag.dismiss();
                        if (response != null) {
                            context.getContentResolver().delete(uri2, null, null);
                            context.getContentResolver().delete(uri3, null, null);
                            context.getContentResolver().delete(uri1, null, null);
                            Log.d("REPLY", response.toString());
                            handleResponse(response, uri1, uri2, uri3);
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // TODO Auto-generated method stub
                        //pDiag.dismiss();

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq);
    }

    public void handleResponse(JSONObject response, Uri uri1, Uri uri2, Uri uri3){


        try {
            JSONObject respOrd = response.getJSONObject("response");
            JSONObject dataOrd = respOrd.getJSONObject("data");
            JSONArray ordersArr = dataOrd.getJSONArray("orders");
            Log.d("TEST", uri1.toString());
            Log.d("TAGURL", uri2.toString());
            for (int i = 0; i < ordersArr.length(); i++) {

                ContentValues value = new ContentValues(); 
                JSONObject ordItmObj = (JSONObject) ordersArr.get(i);
                final String id = ordItmObj.getString("id");
                value.put("order_id", ordItmObj.getString("id"));
                value.put("source_number", ordItmObj.getString("number"));
                value.put("order_type", ordItmObj.getString("order_type"));
                value.put("order_picked", ordItmObj.getString("picked"));
                value.put("order_delivered", ordItmObj.getString("delivered"));
                value.put("source_code", ordItmObj.getString("source_customer_code"));
                value.put("source_email", ordItmObj.getString("source_customer_email"));
                value.put("source_name", ordItmObj.getString("source_customer_name"));
                value.put("source_phone", ordItmObj.getString("source_customer_phone_number"));
                value.put("source_address", ordItmObj.getString("source_customer_address_line_1") + " " + ordItmObj.getString("source_customer_city"));
                value.put("destination_code", ordItmObj.getString("destination_customer_code"));
                value.put("destination_email", ordItmObj.getString("destination_customer_email"));
                value.put("destination_name", ordItmObj.getString("destination_customer_name"));
                value.put("destination_phone", ordItmObj.getString("destination_customer_phone_number"));
                value.put("destination_address", ordItmObj.getString("destination_customer_address_line_1") + " " + ordItmObj.getString("destination_customer_city"));
                context.getContentResolver().insert(uri1, value);
                JSONArray ordItem = ordItmObj.getJSONArray("OrderItem");
                for (int j = 0; j < ordItem.length(); j++) {
                    JSONObject itm = (JSONObject) ordItem.get(j);
                    ContentValues valueItem = new ContentValues();
                    valueItem.put("order_id", id);
                    valueItem.put("item_name", itm.getString("name"));
                    valueItem.put("item_quantity", itm.getString("quantity"));
                    valueItem.put("item_details", itm.getString("details"));
                    context.getContentResolver().insert(uri2, valueItem);
                }
                JSONArray ordIssues = ordItmObj.getJSONArray("Issue");
                for (int h = 0; h < ordIssues.length(); h++) {
                    JSONObject issues = (JSONObject) ordIssues.get(h);
                    ContentValues valueIssues = new ContentValues();
                    valueIssues.put("order_id", id);
                    valueIssues.put("issue_type", issues.getString("issue_type_id"));
                    valueIssues.put("issue_description", issues.getString("description"));
                    context.getContentResolver().insert(uri3, valueIssues);
                }
            }


Intent intent = new Intent();
            intent.setAction("RELOAD");
            context.sendBroadcast(intent);
            //pends.getActivity().
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



}

以下是需要更新的ListFragment,PendingFragment pends = PendingFragment.getInstance(); pends.getResults();调用该行时,它会崩溃应用

    public class PendingFragment extends ListFragment{

        Context activityContext;
        private ProgressDialog pDialog;
        private PendingOrderListAdapter listAdapter;
        private List<PendingTrackItem> trackItems;
        SharedPreferences pref;
private BroadcastReceiver myReciever = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            getResults();
        }
    };

    public void onDestroyView() {
        super.onDestroyView();
        getActivity().getApplicationContext().unregisterReceiver(myReciever);
    };
        private static PendingFragment pending;

        public PendingFragment(){

        }

        public static PendingFragment getInstance(){
            if (null == pending) {
                pending = new PendingFragment();
            }
            return pending;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View pending = inflater.inflate(R.layout.pending_frag, container, false);
            setHasOptionsMenu(true);

            return pending;
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onViewCreated(view, savedInstanceState);

            ListView list = getListView();

            trackItems = new ArrayList<PendingTrackItem>();
            listAdapter = new PendingOrderListAdapter(getActivity(), trackItems);
            list.setAdapter(listAdapter);
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    TextView add_id = (TextView) view.findViewById(R.id.orderId);
                    TextView orderNumber = (TextView) view.findViewById(R.id.orderNumber);
                    pref = getActivity().getSharedPreferences("myId", Context.MODE_PRIVATE);
                    Editor edit = pref.edit();
                    edit.putString("int1", add_id.getText().toString());
                    edit.commit();
                    Intent i = new Intent(getActivity(), OrderFragmentActivity.class);
                    i.putExtra("key1", orderNumber.getText().toString());
                    startActivity(i);
                }

            });

        }

        public void getResults(){
            Uri uri = Uri.parse("content://" + getString(R.string.AUTORITY_ORDER) + "/order");
            Log.d("URL PRINT", uri.toString());
            final Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, "_id");
            Log.d("CURSOR DATA:", cursor.toString());
                JSONArray array = new JSONArray();
                if (cursor != null && cursor.getCount() > 0) {
                    while(cursor.moveToNext()){
                        JSONObject object = new JSONObject();
                        try {
                            object.put("destination_address", cursor.getString(0));
                            object.put("destination_code", cursor.getString(1));
                            object.put("destination_email", cursor.getString(2));
                            object.put("destination_name", cursor.getString(3));
                            object.put("destination_phone", cursor.getString(4));
                            object.put("_id", cursor.getString(5));
                            object.put("order_delivered", cursor.getString(6));
                            object.put("order_id", cursor.getString(7));
                            object.put("order_picked", cursor.getString(8));
                            object.put("order_type", cursor.getString(9));
                            object.put("source_address", cursor.getString(10));
                            object.put("source_code", cursor.getString(11));
                            object.put("source_email", cursor.getString(12));
                            object.put("source_name", cursor.getString(13));
                            object.put("source_number", cursor.getString(14));
                            object.put("source_phone", cursor.getString(15));
                            array.put(object);
                            Log.d("ARRAY", String.valueOf(array.length()));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    parseJsonFeed(array);
                    cursor.close();
                    /*FragmentManager fm = getFragmentManager();
                    FragmentTransaction ft  = fm.beginTransaction();
                    ClosedFragment cF = new ClosedFragment();
                    ft.replace(android.R.id.list, cF);
                    ft.commit();
                    cF.getResults();*/
                }

        }

        public void parseJsonFeed(JSONArray jArr){
            Log.d("jsonArr", jArr.toString());
            try {
                trackItems.clear();
                for (int i = 0; i < jArr.length(); i++) {

                    JSONObject rest = (JSONObject) jArr.get(i);
                    String check = rest.getString("order_delivered");
                    PendingTrackItem item = new PendingTrackItem();
                    String sourceAdrress, destinationAddress;
                    sourceAdrress = rest.getString("source_address");
                    destinationAddress = rest.getString("destination_address");
                    Log.d("ORDER_CHECK", rest.toString());

                    if (check.equals("false")) {
                        item.setId(rest.getString("order_id"));
                        item.setNumber(rest.getString("source_number"));
                        if (sourceAdrress.matches(" ")) {
                            item.setSourceAddress(rest.getString("destination_address"));
                            item.setSourceName(rest.getString("destination_name"));
                        } else if (destinationAddress.matches(" ")) {
                            item.setSourceAddress(rest.getString("source_address"));
                            item.setSourceName(rest.getString("source_name"));
                        } else {
                            item.setSourceAddress(rest.getString("source_address"));
                            item.setSourceName(rest.getString("source_name"));
                        }
                        trackItems.add(item);
                    } 
                }
                //Log.d("ITEm", String.valueOf(trackItems.size()));
                TextView txt =  (TextView) getActivity().findViewById(R.id.txtCount);
                txt.setText(String.valueOf(trackItems.size()));
                listAdapter.notifyDataSetChanged(); 
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }


        }

        @Override
        public void onResume() {
            // TODO Auto-generated method stub
            activityContext = getActivity().getApplicationContext();
            SharedPreferences pref = this.getActivity().getSharedPreferences("myData", Context.MODE_PRIVATE);  
            String getToken = pref.getString("key1", "no data");
IntentFilter filter = new IntentFilter("RELOAD");
        getActivity().getApplicationContext().registerReceiver(myReciever, filter);
            getResults();
            //getData(getToken, uri, itemUri, issuesUri);
            super.onResume();
        }
    }

崩溃报告

10-08 13:29:34.370: E/AndroidRuntime(9723): Process: com.deliveryscience.pod, PID: 9723
10-08 13:29:34.370: E/AndroidRuntime(9723): java.lang.IllegalStateException: Fragment PendingFragment{41f49628} not attached to Activity
10-08 13:29:34.370: E/AndroidRuntime(9723):     at android.support.v4.app.Fragment.getResources(Fragment.java:603)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at android.support.v4.app.Fragment.getString(Fragment.java:625)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.deliveryscience.pod.fragments.PendingFragment.getResults(PendingFragment.java:109)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.deliveryscience.pod.handlers.OrderDataRetrieval.handleResponse(OrderDataRetrieval.java:122)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:53)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:1)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
10-08 13:29:34.370: E/AndroidRuntime(9723):     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)

我很难找到一种方法来刷新ListFragment

1 个答案:

答案 0 :(得分:0)

按照以下步骤

1)在ListFragment中注册广播接收器。

2)从下载数据类,发送一个广播消息,其注意事项与您注册接收器相同。

而不是代码,请使用sendBroadcast

 PendingFragment pends = PendingFragment.getInstance();
            pends.getResults();

3)从接收者类的onReceive进行必要的更新。

或者,您可以使用Handler在Download class和Fragment之间进行通信。

而不是