如何使用MySQL数据库的android显示图 [英] how to display graph in android using MySQL database

查看:127
本文介绍了如何使用MySQL数据库的android显示图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从MySQL数据库中的数据进行图形。我发现一个例子$ C $下创建图形,但我想从数据库中把X轴数据和Y轴数据。

我的例子codeS是:

 公共类图形扩展活动{

    私人XYPlot xyPlot;

    @覆盖
    公共无效的onCreate(包savedInstanceState){

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

        //初始化我们XYPlot参考:
        xyPlot =(XYPlot)findViewById(R.id.xyplot);

        号码[]所得税= {2000,2500,2700,3000,2800,3500,3700,3800};
        数[]费用= {2200,2700,2900,2800,2600,3000,3300,3400};

        最终的String [] mMonths =新的String [] {
            简,月,月,月,月,君,
            七月,月,月,月,月,月

        };

        //转换上述收入数组XYSeries
        XYSeries incomeSeries =新SimpleXYSeries(
            Arrays.asList(收入),//阵列=>名单
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,// Y_VALS_ONLY意味着使用元素的索引为x值
            收入); //这个系列的标题

        //转换上述费用数组XYSeries
        XYSeries expenseSeries =新SimpleXYSeries(
            Arrays.asList(费用),//阵列=>名单
            SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,// Y_VALS_ONLY意味着使用元素的索引为x值
            费用); //这个系列的标题

        //创建一个格式来格式化收入一系列线,点
        LineAndPointFormatter incomeFormat =新LineAndPointFormatter(
            Color.rgb(0,0,255),/​​/线的颜色
            Color.rgb(200,200,200),//点色
            空值 ); //填充颜色(无)

        //创建一个格式来格式化开支一系列线,点
        LineAndPointFormatter expenseFormat =新LineAndPointFormatter(
            Color.rgb(255,0,0),//线的颜色
            Color.rgb(200,200,200),//点色
            空值); //填充颜色(无)

        //增加费用串联到xyplot:
        xyPlot.addSeries(expenseSeries,expenseFormat);

        //增加收入系列的xyplot:
        xyPlot.addSeries(incomeSeries,incomeFormat);

        //格式的域值(X轴)
        xyPlot.setDomainValueFormat(新格式(){

            @覆盖
            公共StringBuffer的格式(obj对象,StringBuffer的toAppendTo,FieldPosition的POS){
                返回新的StringBuffer(mMonths [((数量)OBJ).intValue());
            }

            @覆盖
            公共对象的parseObject(字符串源,一个ParsePosition POS){
                返回null;
            }
        });

        xyPlot.setDomainLabel();
        xyPlot.setRangeLabel(中的美元金额);

        //增加X轴1值
        xyPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL,1);

        xyPlot.getGraphWidget()setRangeLabelWidth(50)。

        //减少范围内标签的数量
        xyPlot.setTicksPerRangeLabel(2);

        //减少域标签的数量
        xyPlot.setTicksPerDomainLabel(2);

        //从图表中删除所有的开发者指南
        xyPlot.disableAllMarkup();
    }
 

获取数据库codeS:

 公共类AllProductsActivity扩展ListActivity {

    //进度对话框
    私人ProgressDialog pDialog;

    //创建JSON解析器对象
    JSONParser jParser =新JSONParser();

    ArrayList的< HashMap的<字符串,字符串>> productsList;

    // URL获得所有产品列表
    私有静态字符串url_all_products =htt​​p://10.0.2.2/android_connect/get_all_products.php;

    // JSON节点名称
    私有静态最后弦乐TAG_SUCCESS =成功;
    私有静态最后弦乐TAG_DEGERLER =degerler;
    私有静态最后弦乐TAG_SICAKLIK =Sicaklik;
    私有静态最后弦乐TAG_GERILIM =Gerilim;
    私有静态最后弦乐TAG_AKIM =阿基姆;
    私有静态最后弦乐TAG_REEL =卷轴居奇;
    私有静态最后弦乐TAG_REAKTIF =Reaktif居奇;

    //产品JSONArray
    JSONArray产品= NULL;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.all_products);

        //哈希映射为的ListView
        productsList =新的ArrayList< HashMap的<字符串,字符串>>();
     //大厦参数
        名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
        //从URL获取JSON字符串
        JSONObject的JSON = jParser.makeHtt prequest(url_all_products,GET,则params);

        //检查你的日志猫JSON响应
        Log.d(所有产品,json.toString());

        尝试 {
            //检查成功TAG
            INT成功= json.getInt(TAG_SUCCESS);

            如果(成功== 1){
                发现//产品
                //获取产品阵列
                产品= json.getJSONArray(TAG_DEGERLER);

                //遍历所有产品
                的for(int i = 0; I< products.length();我++){
                    JSONObject的C = products.getJSONObject(我);

                    //保存在变量中的每个JSON项目
                    字符串sicaklik = c.getString(TAG_SICAKLIK);
                    字符串gerilim = c.getString(TAG_GERILIM);
                    字符串阿基姆= c.getString(TAG_AKIM);
                    字符串卷轴= c.getString(TAG_REEL);
                    字符串reaktif = c.getString(TAG_REAKTIF);

                    //创建新的HashMap
                    HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();

                    //添加每个子节点HashMap中的key =>值
                    map.put(TAG_SICAKLIK,sicaklik);
                    map.put(TAG_GERILIM,gerilim);
                    map.put(TAG_AKIM,阿基姆);
                    map.put(TAG_REEL,盘);
                    map.put(TAG_REAKTIF,reaktif);

                    //添加HashList到ArrayList中
                    productsList.add(图)
                }
            } 其他 {

            }
        }赶上(JSONException E){
            e.printStackTrace();
        }

        ListAdapter适配器=新SimpleAdapter(
                AllProductsActivity.this,productsList,
                R.layout.list_item,新的String [] {TAG_SICAKLIK,
                        TAG_GERILIM,TAG_AKIM,TAG_REEL,TAG_REAKTIF},
                新的INT [] {R.id.sicaklik,R.id.gerilim,R.id.akim,R.id.reel,R.id.reaktif});
        //更新列表视图
        setListAdapter(适配器);



    }


}
 

JSON解析器codeS:

 公共类JSONParser {

    静态的InputStream是= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;

    //构造
    公共JSONParser(){

    }

    //功能得到URL JSON
    //通过HTTP POST或GET方法
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
            名单<的NameValuePair> PARAMS){

        //使HTTP请求
        尝试 {

            //检查请求的方法
            如果(方法==POST){
                //请求方法是POST
                // defaultHttpClient
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));

                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();

            }否则,如果(方法==GET){
                //请求方法是GET
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(PARAMS,UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);

                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }

        }赶上(UnsupportedEncodingException E){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常E){
            e.printStackTrace();
        }

        尝试 {
            的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\ N);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,转换的结果错误+ e.toString());
        }

        //尝试解析字符串到一个JSON对象
        尝试 {
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }

        //返回JSON字符串
        返回jObj;

    }
}
 

解决方案

是啊,这恰恰是行不通的。 Activity.onCreate不是主()。你不能只是把你的应用程序在那里。

我敢肯定这是不是你想听到什么,由你真的需要所有的方式回到绘图板。你将要把code请求JSON对象变成服务。

在code,做实际的图形看起来pretty的好。你需要这样当服务成功地检索JSON,然后解析它,它会通知的活动,有一些以图表来设置它。

步骤从code回来,刷上Android的架构几天。这并不难,但它是不同的。

I can't get data from MySQL database for graphics. I found an example code for create graph but I want to put x axis data and y axis data from database

My example codes are:

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();
    }

Get Database Codes:

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 Parser Codes:

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;

    }
}

解决方案

Yeah, this just isn't going to work. Activity.onCreate is not main(). You can't just put your application there.

I'm sure this isn't what you want to hear, by you really need to go all the way back to the drawing board. You are going to want to put the code that requests the JSON object into a Service.

The code that does the actual graphing looks pretty good. You will need to set it up so that when the Service succeeds in retrieving the JSON, and then parsing it, it notifies the Activity that there is something to graph.

Step back from the code and brush up on Android architecture for a couple days. It isn't hard, but it is different.

这篇关于如何使用MySQL数据库的android显示图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆