获取异步任务会导致片段中的回调

时间:2014-08-22 12:54:10

标签: java android eclipse

我刚开始使用android并且无法弄清楚如何在片段中获取http json响应。在我的活动中,我很容易使用回调函数,但在Fragment中似乎很难完成相同的操作。

任何帮助都会非常感激。

//SaleFragment.java
public class SaleFragment extends Fragment{

public static final String ARG_CLIENT_NUMBER = "client_number";
private ListView salesListView;
private View rootView;

public SaleFragment() {
// Empty constructor required for fragment subclasses
}

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

       rootView = inflater.inflate(R.layout.fragment_sale, container, false);
            int i = getArguments().getInt(ARG_CLIENT_NUMBER);
            try{
                     SaleStackJSON sale_json = new SaleStackJSON();
                     sale_json.execute("http://test.url/getJson"); //url to retrieve json
                     // do processing on the result (I do not know how to retrieve them here after the request)

           }catch(Exception e){
                      //  resultView.setText(e.getMessage());
              }

        return rootView;
   }

我的JSON类如下:

// SaleStackJSON.java
public class SaleStackJSON   extends AsyncTask<String, Void, String>{

    InputStream is = null;
    String result = "";
    JSONArray jArray = null;
    String error_text="";
    JSONObject j = null;
    TextView resultView;

    @Override
    protected String doInBackground(String... urls) {

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(urls[0]);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            setResult(sb.toString());

            //     this.jArray = new JSONArray(result);
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }


        return getResult();
    }


    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
}

编辑1:我使用以下代码填充我的前端。 (显示结果)

        JSONArray jArray;
        ArrayList all_sales = new ArrayList();
        try {
            jArray = new JSONArray(result);
            int total_retail_outlets = jArray.length();
            //LinearLayout scrollable_sale_layout = (LinearLayout)findViewById(R.id.scrollable_sale_layout);
            for (int i = 0; i < total_retail_outlets; i++) {
                    JSONObject jObj = jArray.getJSONObject(i);

                    String customer_name = jObj.getString("name");
                    String created_at = jObj.getString("created_at");
                    String quantity = jObj.getString("quantity");
                    String billing_amount = jObj.getString("billing_amount");
                    String discount_percentage = jObj.getString("discount_percentage");
                    String discount = jObj.getString("discount");
                    String total = jObj.getString("total");
                    SalesItem salesData = new SalesItem();
                    salesData.setBilling_amount(billing_amount);
                    salesData.setCreated_at(created_at);
                    salesData.setCustomer_name(customer_name);
                    salesData.setDiscount(discount);
                    salesData.setDiscount_percentage(discount_percentage);
                    salesData.setQuantity(quantity);
                    salesData.setTotal(total);

                    all_sales.add(salesData);
                }

            salesListView.setAdapter(new CustomSaleListAdapter(getActivity(), all_sales));


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:1)

抱歉任何错字;我的解决方案是:

首先,最好在doInBackground方法中处理您的响应,因为它会使UI线程不那么繁忙,所以:

 public class SaleStackJSON   extends AsyncTask<String, Void,  ArrayList<SalesItem>>

并在doInBackground中执行以下操作:

@Override
protected String doInBackground(String... urls) {

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(urls[0]);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();


        //     this.jArray = new JSONArray(result);
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    ArrayList<SalesItem> all_sales = new ArrayList<SalesItem>();
    JSONArray jArray;
    try {
        jArray = new JSONArray(sb.toString());
        int total_retail_outlets = jArray.length();
        for (int i = 0; i < total_retail_outlets; i++) {
                JSONObject jObj = jArray.getJSONObject(i);

                String customer_name = jObj.getString("name");
                String created_at = jObj.getString("created_at");
                String quantity = jObj.getString("quantity");
                String billing_amount = jObj.getString("billing_amount");
                String discount_percentage = jObj.getString("discount_percentage");
                String discount = jObj.getString("discount");
                String total = jObj.getString("total");
                SalesItem salesData = new SalesItem();
                salesData.setBilling_amount(billing_amount);
                salesData.setCreated_at(created_at);
                salesData.setCustomer_name(customer_name);
                salesData.setDiscount(discount);
                salesData.setDiscount_percentage(discount_percentage);
                salesData.setQuantity(quantity);
                salesData.setTotal(total);

                all_sales.add(salesData);
            }
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    return all_sales;
}

现在让我们进行最后的改变:

 protected void onPostExecute( ArrayList<SalesItem> result) {

 salesListView.setAdapter(new CustomSaleListAdapter(getActivity(), result[0]));

}

答案 1 :(得分:0)

This will might help u I do also got the same problem but resolved at the end


    protected void onPostExecute(JSONObject result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (null != pd && pd.isShowing()) {
                pd.dismiss();
            }
            String message="";
            try
            {
                message=result.getString("message");
            }catch(Exception e)
            {
                e.printStackTrace();
            }
            try {
                if(result!=null&&message.equalsIgnoreCase("Invalid User"))
                {
                    activity.startActivity(new Intent(activity,LoginRegisterOptionScreen.class));
                    activity.finish();
                }
                else
                {
                    if(fragment!=null)
                    {
                        if(fragment.getClass().getSimpleName().equalsIgnoreCase("ProfileFragment"))
                        {
                            ((ProfileFragment) fragment).getServerResponse(result); 
                        }
                        else if (fragment.getClass().getSimpleName().equalsIgnoreCase("reviewScreen")) {
                            ((ReviewScreen) fragment).getServerResponse(result);
                        }
                        else if (fragment.getClass().getSimpleName().equalsIgnoreCase("ReviewEditable")) {
                            ((ReviewEditable) fragment).getServerResponse(result);
                        }
                        //          else if(fragment.getClass().getSimpleName().equalsIgnoreCase("FavoritesFragment"))
                        //          {
                        //              ((FavoritesFragment) fragment).getServerResponse(result); 
                        //          }

                    }
                    else if (activity != null) {
                        if (activity.getClass().getSimpleName().equalsIgnoreCase("RegisterScreen2")) {
                            ((RegisterScreen2) activity).getServerResponse(result);
                        }
                        else if (activity.getClass().getSimpleName().equalsIgnoreCase("LoginScreen")) {
                            ((LoginScreen) activity).getServerResponse(result);
                        }

                        else if (activity.getClass().getSimpleName().equalsIgnoreCase("changePassword")) {
                            ((changePassword) activity).getServerResponse(result);
                        }


                        //          else if (activity.getClass().getSimpleName().equalsIgnoreCase("googlemap")) {
                        //              ((googlemap) activity).getServerResponse(result);
                        //          }
                        //          else if (activity.getClass().getSimpleName().equalsIgnoreCase("chatter")) {
                        //              try {
                        //                  ((chatter) activity).getServerResponse(result);
                        //              } catch (JSONException e) {
                        //                  // TODO Auto-generated catch block
                        //                  e.printStackTrace();
                        //              }
                        //          }
                        //          else if (activity.getClass().getSimpleName().equalsIgnoreCase("Chatlist")) {
                        //              ((Chatlist) activity).getServerResponse(result);
                        //          }


                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }