简体   繁体   中英

Get Async task result in a callback in an Fragment

I am starting fresh with android and not able to figure out how to get an http json response back in a Fragment. In my activity I am easily able to do so using callback function but it seems difficult to accomplish the same in Fragment.

Any help would really appreciated.

//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;
   }

My JSON class is as follows:

// 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;
    }
}

Edit 1: I use the following code for populating my frontend. (Display results)

        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();
        }

sorry about any typo; my solution is:

first it is good idea to process your response in doInBackground method because it makes UI thread be less busy so:

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

and in doInBackground do something like this:

@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;
}

now let's go to final change:

 protected void onPostExecute( ArrayList<SalesItem> result) {

 salesListView.setAdapter(new CustomSaleListAdapter(getActivity(), result[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();
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM