2014-03-18 9 views
1

이 문제를 해결하려면 도움이 필요합니다. 나는 MySQLdb에서 일부 데이터를 사용하여 내 안드로이드 응용 프로그램에 그려진 PieChart 있습니다. 클래스 구현을 사용하여 서버에서 데이터를로드하여 HTTPPostRequest으로 만들고 응답을 구문 분석하여 JSON을 반환합니다. 차트가 잘 나오고 화면에 그려집니다. 차트가 비정상적으로 동작하고 슬라이스가 다시 그려지는 이유는 무엇인지 모르겠지만 화면을 회전하면 Activity의 모든 메서드가 호출됩니다. 다시 (onCreate(), onStart()onResume() 방법). 어쩌면 그게 그거야 ??? 데이터가 중복되는내 Android PieChart 드로잉이 비정상적으로 작동하는 이유와 화면 회전시 복제 된 슬라이스가 표시되는 이유는 무엇입니까?

enter image description here

: 나는 장치를 회전 할 때 다음

enter image description here

:하지만 여기처럼 보이게하는 방법입니다 ... 확실하지 않다! 왜? 나는 무엇을 착각하고 있는가? 여기

모든 코드 :

public class ComeHaInvestito extends Activity { 

/**** PieChartBuilder ****/ 
/** Colors to be used for the pie slices. */ 
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN }; 
/** The main series that will include all the data. */ 
private CategorySeries mSeries = new CategorySeries(""); 
/** The main renderer for the main dataset. */ 
private DefaultRenderer mRenderer = new DefaultRenderer(); 
/** Edit text field for entering the slice value. */ 
//private EditText mValue; 
/** The chart view that displays the data. */ 
private GraphicalView mChartView; 

private int HowmanyTimes; 
@Override 
protected void onRestoreInstanceState(Bundle savedState) { 
    super.onRestoreInstanceState(savedState); 
    mSeries = (CategorySeries) savedState.getSerializable("current_series"); 
    mRenderer = (DefaultRenderer) savedState.getSerializable("current_renderer"); 
} 

    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putSerializable("current_series", mSeries); 
    outState.putSerializable("current_renderer", mRenderer); 
    } 

/**** ComeHaInvestito ****/ 
// String which will store the values of the user 
String municipalityName; 
String year; 
String versedMoney; 

// List<Item> ArrayList that will be used to store data from DB 
List<Item> MasterAndDetailstatisticsInfoList; 

private static final String TAG_COMUNE = "mun_name"; 
private static final String TAG_ANNO = "year"; 
private static final String TAG_VERSED_MONEY = "versed_money"; 
private static final String TAG_SUCCESS = "success"; 

// POST request information 
private static final String URL_ANDROID_APP_LISTENER = "http://xxx.xxx.xxx.xxx/androidApp/AndroidListener.php"; 

private ProgressDialog pDialog; 
// JSONParser instance 
JSONParser jParser = new JSONParser(); 

// JSON data retrieving information 
private static final String JSON_STATISTICS_INFOS_LABEL = "statistics_infos"; 
private static final String JSON_MASTER_LABEL = "master"; 
private static final String JSON_DETAIL_LABEL = "detail"; 
private static final String JSON_MASTER_DETAIL_NAME_LABEL = "name"; 
private static final String JSON_MASTER_DETAIL_VALUE_LABEL ="value"; 

// statistics info JSON Array which will contain the Master and Detail data that will come from the POST request 
JSONArray statisticsInfo = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_come_ha_investito); 
    Log.d("OnCREATE", "CREO L'ACTIVITY"); 
    // recovering data from previous actitity 
    Intent iMieiDati = getIntent(); 
    this.municipalityName = iMieiDati.getStringExtra(TAG_COMUNE); 
    this.year = iMieiDati.getStringExtra(TAG_ANNO); 
    this.versedMoney = iMieiDati.getStringExtra(TAG_VERSED_MONEY); 

    // instantiating the needed data structure 
    MasterAndDetailstatisticsInfoList = new ArrayList<Item>(); 

    mRenderer.setStartAngle(270); 
    mRenderer.setDisplayValues(true); 

    new LoadAllMunicipalitiesInvestmentStatisticsThread().execute(); 

    //mRenderer.setZoomButtonsVisible(true); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.pie_chart_builder2, menu); 
    return true; 
} 

@Override 
protected void onResume() { 
    super.onResume(); 

    if (mChartView == null) { 
     LinearLayout layout = (LinearLayout) findViewById(R.id.chart); 
     mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer); 
     mRenderer.setClickEnabled(true); 
     mChartView.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint(); 
      if (seriesSelection == null) { 
      Toast.makeText(ComeHaInvestito.this, "No chart element selected", Toast.LENGTH_SHORT).show(); 
      } 
      else { 
      for (int i = 0; i < mSeries.getItemCount(); i++) { 
       mRenderer.getSeriesRendererAt(i).setHighlighted(i == seriesSelection.getPointIndex()); 
      } 
      // mChartView.repaint(); 

      Toast.makeText(
       ComeHaInvestito.this, 
       "Chart data point index " + seriesSelection.getPointIndex() + " selected" 
        + " point value=" + seriesSelection.getValue(), Toast.LENGTH_SHORT).show(); 

      } 
     } 
     }); 
     layout.addView(mChartView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    } 
    else { 
     //mChartView.repaint(); 
    } 
    } 


    private void initChart() { 
     int i=0; 
     double value=0; 
     for (Item item : MasterAndDetailstatisticsInfoList) { 
      if (i == 4) { 
       break; 
      } 
      Log.d("Ciclo ", "NUMERO " + i); 
      if (item.getViewType() == EntryType.MASTER.ordinal()) { 
       MasterWithValue master = (MasterWithValue) item; 
       Log.d("MASTER NAME", master.getMasterName()); 
       Log.d("MASTER VALUE", master.getMasterValue()); 
       try { 
        value = Double.parseDouble(master.getMasterValue()); 
       } 
       catch (NumberFormatException e) { 
        // value is not a decimal 
       } 
       mSeries.add(master.getMasterName(), value); 
       SimpleSeriesRenderer renderer = new SimpleSeriesRenderer(); 
       renderer.setColor(COLORS[i%4]); 
       i++; 
       mRenderer.addSeriesRenderer(renderer); 
       Log.d("mSeries", mSeries.toString()); 
      } 
     } 
    } 

/**** Background Thread ****/ 
public class LoadAllMunicipalitiesInvestmentStatisticsThread extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(ComeHaInvestito.this); 
     pDialog.setMessage("Caricamento..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show();   
    } 

    @Override 
    protected String doInBackground(String... args) { 
     Log.d("ilMioComune", "Caricamento Statistiche Investimenti"); 
     // building the HTTP POST request 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair(TAG_COMUNE, municipalityName)); 
     params.add(new BasicNameValuePair(TAG_ANNO, year)); 
     params.add(new BasicNameValuePair(TAG_VERSED_MONEY, versedMoney)); 
     Log.d("params", params.toString()); 
     JSONObject json = jParser.makeHttpRequest(URL_ANDROID_APP_LISTENER, "POST", params); 

     Log.d("JSON POST statistics investments", json.toString()); 
     try { 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 

       statisticsInfo = json.getJSONArray(JSON_STATISTICS_INFOS_LABEL); 

       // foreach Statistics Master Entry 
       for (int i = 0; i<statisticsInfo.length(); i++) { 
        JSONObject JSONstatisticsInfo = statisticsInfo.getJSONObject(i); 
        JSONObject JSONmasterEntry = JSONstatisticsInfo.getJSONObject(JSON_MASTER_LABEL); 

        String masterEntryName = JSONmasterEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL); 
        String masterEntryValue = JSONmasterEntry.getString(JSON_MASTER_DETAIL_VALUE_LABEL); 
        MasterAndDetailstatisticsInfoList.add(new MasterWithValue(masterEntryName, masterEntryValue));      

        JSONArray JSONdetails = JSONmasterEntry.getJSONArray(JSON_DETAIL_LABEL); 
        for (int j = 0; j<JSONdetails.length(); j++) { 
         JSONObject JSONdetailEntry = JSONdetails.getJSONObject(j); 

         String detailEntryName = JSONdetailEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL); 
         String detailEntryValue = JSONdetailEntry.getString(JSON_MASTER_DETAIL_VALUE_LABEL); 

         MasterAndDetailstatisticsInfoList.add(new Detail(detailEntryName, detailEntryValue)); 
        } 
       } 
      } 
      else { 
       // no statistics infos associated to the selected municipality were found 
      } 
     } 
     catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String file_url) { 
     pDialog.dismiss(); 

     runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       String MasterAndDetails = MasterAndDetailstatisticsInfoList.toString(); 
       Log.d("List", MasterAndDetails); 

       // Creating the pie chart using the data recovered from the DB 
       initChart(); 
      } 
     }); 
    } 
} 
} 

사람이이 문제를 해결하는 방법에 대한 어떤 생각을 가지고 있습니까?

관심을 가져 주셔서 감사합니다. 도움이되기를 바랍니다!

답변

0

회전 할 때마다 onCreate(), onResume() 등이 올바르게 호출됩니다. 이 때문에 new LoadAllMunicipalitiesInvestmentStatisticsThread().execute();을 두 번 호출해야합니다.

데이터 초기화 논리를 한 곳으로 이동하고 savedInstanceState에서 해당 데이터를로드하거나 savedInstanceState가 null을 반환하면 초기화 논리를 호출해야합니다.

예를 들어

:

변화 선언 내에서 onCreate() 메소드에서 그 라인을 추가 한 onCreate()

if(savedInstanceState != null) 
    mSeries = (CategorySeries) savedInstanceState.getSerializable("current_series"); 

if(mSeries == null) 
{ 
    mSeries = new CategorySeries(""); 
    new LoadAllMunicipalitiesInvestmentStatisticsThread().execute(); //this line can be substituted for a new init method, which would contain the thread.execute 
} 
+0

에서

private CategorySeries mSeries = null;

에하지만 난 얻을 자바 Null 포인터 예외, 라인에서 - mSeries = (CategorySeries) savedInstanceState.getSerializable ("current_series"); - 나는 그 줄을 앞뒤에 넣으려고했다. --super.onCreate (savedInstanceState); - onCreate() 메서드를 시작할 때 호출합니다. 내가 뭘 알고 있어야하지? – tonix

+0

해결 방법이 있습니까? – tonix

+0

savedInstanceState가 null인지 아닌지 확인하십시오. 저장된 인스턴스 (즉, 활동이 처음 시작될 때)에서 onCreate가 호출되지 않으면 null이됩니다. 내 대답을 편집했습니다. – invertigo