2017-09-25 1 views
0

웹 서비스를 사용하여 json에서 파이 차트로 데이터를 바인딩하려고합니다. 문제는 doInBackground에서 json 문자열을 onPostExecute으로 전달하고 싶습니다. 그래서 그것을 막대 차트에 바인딩 할 수 있습니다. 나를 도와주세요.AsyncTask에서 Json String을 전달하는 방법?

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 당신의 pieChart를 업데이트 할 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

고마워요. –

관련 문제