2013-05-13 1 views
0

그래픽 용 MySQL 데이터베이스에서 데이터를 가져올 수 없습니다. 나는 그래프를 만들에 대한 예제 코드를 발견하지만 난MySQL 데이터베이스를 사용하여 안드로이드에 그래프를 표시하는 방법

내 예제 코드는 데이터베이스에서 x 축 데이터와 y 축 데이터를 넣을 :

public class Graph extends Activity { 

    private XYPlot xyPlot; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.graph); 

     // initialize our XYPlot reference: 
     xyPlot = (XYPlot) findViewById(R.id.xyplot); 

     Number[] income = {2000, 2500, 2700, 3000, 2800, 3500, 3700, 3800 }; 
     Number[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 }; 

     final String[] mMonths = new String[] { 
      "Jan","Feb", "Mar","Apr", "May","Jun", 
      "Jul", "Aug","Sep","Oct", "Nov","Dec" 

     }; 

     // Converting the above income array into XYSeries 
     XYSeries incomeSeries = new SimpleXYSeries(
      Arrays.asList(income),     // array => list 
      SimpleXYSeries.ArrayFormat.Y_VALS_ONLY , // Y_VALS_ONLY means use the element index as the x value 
      "Income");         // Title of this series 

     // Converting the above expense array into XYSeries 
     XYSeries expenseSeries = new SimpleXYSeries(
      Arrays.asList(expense),     // array => list 
      SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value 
      "Expense");        // Title of this series 

     // Create a formatter to format Line and Point of income series 
     LineAndPointFormatter incomeFormat = new LineAndPointFormatter(
      Color.rgb(0, 0, 255),     // line color 
      Color.rgb(200, 200, 200),    // point color 
      null);         // fill color (none) 

     // Create a formatter to format Line and Point of expense series 
     LineAndPointFormatter expenseFormat = new LineAndPointFormatter(
      Color.rgb(255, 0, 0),     // line color 
      Color.rgb(200, 200, 200),    // point color 
      null);         // fill color (none) 

     // add expense series to the xyplot: 
     xyPlot.addSeries(expenseSeries,expenseFormat); 

     // add income series to the xyplot: 
     xyPlot.addSeries(incomeSeries, incomeFormat); 

     // Formatting the Domain Values (X-Axis) 
     xyPlot.setDomainValueFormat(new Format() { 

      @Override 
      public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { 
       return new StringBuffer(mMonths[ ((Number)obj).intValue() ] ); 
      } 

      @Override 
      public Object parseObject(String source, ParsePosition pos) { 
       return null; 
      } 
     }); 

     xyPlot.setDomainLabel(""); 
     xyPlot.setRangeLabel("Amount in Dollars"); 

     // Increment X-Axis by 1 value 
     xyPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1); 

     xyPlot.getGraphWidget().setRangeLabelWidth(50); 

     // Reduce the number of range labels 
     xyPlot.setTicksPerRangeLabel(2); 

     // Reduce the number of domain labels 
     xyPlot.setTicksPerDomainLabel(2); 

     // Remove all the developer guides from the chart 
     xyPlot.disableAllMarkup(); 
    } 

가져 오기 데이터베이스 코드 :

public class AllProductsActivity extends ListActivity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // Creating JSON Parser object 
    JSONParser jParser = new JSONParser(); 

    ArrayList<HashMap<String, String>> productsList; 

    // url to get all products list 
    private static String url_all_products = "http://10.0.2.2/android_connect/get_all_products.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_DEGERLER = "degerler"; 
    private static final String TAG_SICAKLIK = "Sicaklik"; 
    private static final String TAG_GERILIM = "Gerilim"; 
    private static final String TAG_AKIM = "Akim"; 
    private static final String TAG_REEL = "Reel Guc"; 
    private static final String TAG_REAKTIF = "Reaktif Guc"; 

    // products JSONArray 
    JSONArray products = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.all_products); 

     // Hashmap for ListView 
     productsList = new ArrayList<HashMap<String, String>>(); 
    // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 

     // Check your log cat for JSON response 
     Log.d("All Products: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // products found 
       // Getting Array of Products 
       products = json.getJSONArray(TAG_DEGERLER); 

       // looping through All Products 
       for (int i = 0; i < products.length(); i++) { 
        JSONObject c = products.getJSONObject(i); 

        // Storing each json item in variable 
        String sicaklik = c.getString(TAG_SICAKLIK); 
        String gerilim = c.getString(TAG_GERILIM); 
        String akim = c.getString(TAG_AKIM); 
        String reel = c.getString(TAG_REEL); 
        String reaktif = c.getString(TAG_REAKTIF); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_SICAKLIK, sicaklik); 
        map.put(TAG_GERILIM, gerilim); 
        map.put(TAG_AKIM, akim); 
        map.put(TAG_REEL, reel); 
        map.put(TAG_REAKTIF, reaktif); 

        // adding HashList to ArrayList 
        productsList.add(map); 
       } 
      } else { 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     ListAdapter adapter = new SimpleAdapter(
       AllProductsActivity.this, productsList, 
       R.layout.list_item, new String[] { TAG_SICAKLIK, 
         TAG_GERILIM,TAG_AKIM,TAG_REEL,TAG_REAKTIF}, 
       new int[] { R.id.sicaklik, R.id.gerilim, R.id.akim, R.id.reel, R.id.reaktif}); 
     // updating listview 
     setListAdapter(adapter); 



    } 


} 

JSON 파서 코드 :

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET method 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      }   

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 
+0

데이터베이스에서 데이터를 가져 오려고 시도한 곳은 어디입니까? –

+0

localhost에서 내 데이터베이스 – bsahan

+0

나는 분명히 추측하지 않았다. 나는 코드에서 어디에서 그래프를 만들기 위해 데이터베이스에서 데이터를 추출하려고 시도 했는가? –

답변

1

그래,이 그냥 일하지 않을거야. Activity.onCreate가 main()이 아닙니다. 거기에 응용 프로그램을 넣을 수는 없습니다.

나는 이것이 당신이 듣고 싶은 것이 아니라고 확신합니다. 정말로 드로잉 보드로 다시 돌아갈 필요가 있습니다. JSON 객체를 요청하는 코드를 서비스에 넣기를 원할 것입니다.

실제 그래프를 작성하는 코드는 꽤 잘 보입니다. 서비스가 JSON을 검색하고 파싱에 성공하면 Activity에 그래프가 있다는 것을 알려주도록 설정해야합니다.

코드에서 뒤로 물러나서 Android 아키텍처에서 2 일 동안 닦아주십시오. 어렵지는 않지만 다르다.

+0

귀하의 의견을 보내 주셔서 감사합니다. 나는 그 방법을 시도 할 것이다 – bsahan

0

예. 가능합니다. 당신은 나의 예를 따를 수있다

Bar Chart in Android With out any Built in jars. 여기서 데이터베이스에서 데이터를 가져 와서 배열의 결과를 설정할 수 있습니다 (배열 grossSal, netSal, datelabel 배열)

여기에는 필요한 병이없는 간단한 논리가 있습니다. 이 예제의 코딩으로 막 대형 차트를 구현할 수 있습니다.

+0

숫양 .. 소스 코드를 다운로드 할 수 없습니다 .. 당신은 그 문제를 해결할 수 있습니까? – AndroidManifester