我想使用Web服务将数据从json绑定到饼图。
问题是我想将doInBackground
的json字符串传递给onPostExecute
。这样我就可以将它绑定到条形图上。
帮助我解决这个问题。
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"}]
Pie 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数据绑定到饼图中。
提前致谢
答案 0 :(得分:0)
声明AsyncTask时需要声明3种类型。 <Params, Progress, Result>
。您将这些保留为<Void, Void, Void>
。你想要的是使用Result类型作为String或JSONObject(适合你的情况。
因此,您的新异步声明将为<Void, Void, String>
您的doInBackground decl将更改为protected String doInBackground(Void... params)
并且您的onPostExecute将更改为public void onPostExecute(String result)
现在你的doInBackground可以返回一个String,你的onPostExecute会把它作为参数。