如何在AsyncTask中传递Json字符串?
我想使用Web服务将数据从JSON绑定到饼图。 问题是我想要将json字符串从doInBackground
传递到onPostExecute
。所以我可以将它绑定到条形图。 帮我在这里。如何在AsyncTask中传递Json字符串?
JSON数据:
[{"NAME":"601 GRIETA EN CUERPO","PERCENTAGE":"46"},
{"NAME":"77 ENFRIAMIENTO O DUNTING","PERCENTAGE":"18"},
{"NAME":"78 PRECALENTAMIENTO","PERCENTAGE":"18"},
{"NAME":"209 MAL MANEJO","PERCENTAGE":"9"},
{"NAME":"92 FUGA DE MANOMETRO","PERCENTAGE":"9"}]
派Chart.java
package com.example.saravanakumars.chart;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by saravanakumars on 9/18/2017.
*/
public class piechart extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private PieChart pieChart;
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pie_chart);
pieChart = (PieChart) findViewById(R.id.piechart);
new GetContacts().execute();
TextView txt1 = (TextView)findViewById(R.id.txthidden);
txt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(piechart.this);
builder.setTitle("Pick One");
builder.setItems(R.array.type_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
Toast.makeText(getApplicationContext(),"Type-1",Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(),"Type-2",Toast.LENGTH_SHORT).show();
default:
break;
}
}
});
builder.create();
builder.show();
}
});
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(piechart.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
String NAME = object.getString("NAME");
String PERCENTAGE = object.getString("PERCENTAGE");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
JSONArray jarray = new JSONArray(r);
//Bind data in array list for Defect ID
ArrayList<Entry> entries = new ArrayList<>();
for (int i = 0; i < jarray.length(); i++) {
// jobj = jarray.getJSONObject(i);
JSONObject object = (JSONObject) array.get(i);
entries.add(new Entry(object.getInt("PERCENTAGE"), i));
}
PieDataSet dataset = new PieDataSet(entries, "");
//Bind data in array list for Defect
ArrayList<Entry> labels = new ArrayList<String>();
for (int i = 0; i < jarray.length(); i++) {
jobj = jarray.getJSONObject(i);
labels.add(jobj.getString("NAME"));
}
PieData data = new PieData(labels, dataset);
// Legend settings
Legend l = pieChart.getLegend();
l.setFormSize(10f); // set the size of the legend forms/shapes
l.setForm(Legend.LegendForm.CIRCLE); // set what type of form/shape should be used
l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
l.setTextSize(15f);
l.setTextColor(Color.BLACK);
l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
l.setYEntrySpace(0f); // set the space between the legend entries on the y-axis
l.setYOffset(10f);
l.setWordWrapEnabled(true);
l.setEnabled(true);
dataset.setColors(ColorTemplate.COLORFUL_COLORS);
pieChart.setDescription("Top 5 Defects");
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
pieChart.animateY(3000);
pieChart.setDescriptionPosition(280, 40);
pieChart.setDescriptionTextSize(50);
pieChart.setHoleColor(Color.GRAY);
pieChart.setDrawCenterText(true);
pieChart.setRotationAngle(50);
pieChart.setRotationEnabled(true);
pieChart.setHighlightPerTapEnabled(true);
pieChart.setUsePercentValues(true);
//pieChart.setUsePercentValues(false);
//l.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5, 5, 5, 5);
pieChart.saveToGallery("/sd/mychart.jpg", 85); // 85 is the quality of the image
pieChart.setData(data);
}
}
}
帮我绑定JSON数据成饼图。
在此先感谢
有你需要声明,同时宣布了的AsyncTask 3种类型。 <Params, Progress, Result>
。您已将这些保存为<Void, Void, Void>
。你想要的是使用的结果类型为字符串或JSONObject的(任何适合你的情况。
因此新的异步宣言将是<Void, Void, String>
你doInBackground东方电气将作为protected String doInBackground(Void... params)
改变,你的onPostExecute会变化public void onPostExecute(String result)
现在你doInBackground可以返回一个字符串,你的onPostExecute会得到它作为一个参数。
我如何传递jsonstr(String)来发布执行方法。 –
这就是我上面写的。进行更改后,只需将doInBackground中的'return null;'更改为'return jsonStr;' –
谢谢你的工作。 –
要更新您的饼图AFTE r在'doInBackground()'方法中获取数据 – UltimateDevil