グラフィック用の 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;
}
}