2017-09-25 77 views
0

我想使用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數據成餅圖。

在此先感謝

+0

要更新您的餅圖AFTE r在'doInBackground()'方法中獲取數據 – UltimateDevil

回答

0

有你需要聲明,同時宣佈了的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會得到它作爲一個參數。

+0

我如何傳遞jsonstr(String)來發布執行方法。 –

+1

這就是我上面寫的。進行更改後,只需將doInBackground中的'return null;'更改爲'return jsonStr;' –

+0

謝謝你的工作。 –

相關問題