gpt4 book ai didi

java - 在 fragment 中的回调中获取异步任务结果

转载 作者:行者123 更新时间:2023-12-01 12:37:36 26 4
gpt4 key购买 nike

我刚刚开始使用 android,无法弄清楚如何在 fragment 中获取 http json 响应。在我的 Activity 中,我可以轻松地使用回调函数来做到这一点,但在 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();
}

最佳答案

对于任何拼写错误,我们深表歉意;我的解决方案是:

首先,最好在 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]));

}

关于java - 在 fragment 中的回调中获取异步任务结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com