繁体   English   中英

如何在AsyncTask中传递Json字符串?

[英]How to Pass Json String in AsyncTask?

我想使用网络服务将数据从json绑定到饼图。 问题是我想将json字符串从doInBackgroundonPostExecute 这样我就可以将其绑定到条形图。 在这方面帮助我。

杰森数据:

[{"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"}]

饼图.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> 您想要的是将Result类型用作String或JSONObject(无论哪种情况)。

因此,您的新异步声明将为<Void, Void, String>

您的doInBackground decl将更改为protected String doInBackground(Void... params)

并且您的onPostExecute将更改为public void onPostExecute(String result)

现在,您的doInBackground可以返回一个字符串,并且onPostExecute将其作为参数获取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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