douluyezhen4512 2017-05-03 06:31
浏览 148

根据从MYSQL获取的数据,使用MpAndroid库库在android上创建一个图形

Hello I'm creating a program which displays a graph of the BatchNo and FCR from the Database. Im using Android Studio, phpMyAdmin, and MpAndroid library in android studio. I modified the codes that I got from https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ which takes the data from MySQL and https://www.studytutorial.in/android-line-chart-or-line-graph-using-mpandroid-library-tutorial which I used to create a graph.

I created a database named aps, the table name is fcr_table, and the columns are BatchNo (int) and FCR (Float).

Here is my php codes for the database connection:

<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

define('hostname','localhost');
define('user','root');
define('password','');
define('databaseName','aps');

$connect = mysqli_connect(hostname, user, password, databaseName) or 
die('UNABLE TO CONNECT');
?>

Here is the php code for retrieving data from MySql:

<?php 
ini_set("display_errors", 1);
error_reporting(E_ALL);

//Importing Database Script 
require_once('connection.php');

//Creating sql query
$sql = "SELECT * FROM fcr_table";

//getting result 
$r = mysqli_query($connect,$sql);

//creating a blank array 
$result = array();

 //looping through all the records fetched
 while($row = mysqli_fetch_array($r)){

 //Pushing name and id in the blank array created 
 array_push($result,array(
 "BatchNo"=>$row['BatchNo']
 "FCR"=>$row['FCR']
 ));
 }

Below is the code for the activity on android:

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;


import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by q on 29/04/2017.
 */

public class ViewGraph extends AppCompatActivity implements                     
OnChartGestureListener, OnChartValueSelectedListener {

private String id, stringbatchno, stringfcr;
private int batchno;
private float fcr;
private String JSON_STRING;
private int resultcount;
private static int batchnoArray;
private static float fcrArray;
private LineChart mChart;
private ArrayList<String> allBatchNo;
private ArrayList<String> allFCR;
private JSONArray result;
private ArrayList<String> xVals, xValstosetdata;
private ArrayList<Entry> yVals, yValstosetdata;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_graph);

    mChart = (LineChart) findViewById(R.id.linechart);
    mChart.setOnChartGestureListener(this);
    mChart.setOnChartValueSelectedListener(this);

    // add data
    getJSON();

    // get the legend (only possible after setting data)
    Legend l = mChart.getLegend();

    // modify the legend ...
    // l.setPosition(LegendPosition.LEFT_OF_CHART);
    l.setForm(Legend.LegendForm.LINE);

}

@Override
public void onChartGestureStart(MotionEvent me,
                                ChartTouchListener.ChartGesture
                                        lastPerformedGesture) {

    Log.i("Gesture", "START, x: " + me.getX() + ", y: " + me.getY());
}

@Override
public void onChartGestureEnd(MotionEvent me,
                              ChartTouchListener.ChartGesture
                                      lastPerformedGesture) {

    Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture);

    // un-highlight values after the gesture is finished and no single-tap
    if(lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
        // or highlightTouch(null) for callback to onNothingSelected(...)
        mChart.highlightValues(null);
}

@Override
public void onChartLongPressed(MotionEvent me) {
    Log.i("LongPress", "Chart longpressed.");
}

@Override
public void onChartDoubleTapped(MotionEvent me) {
    Log.i("DoubleTap", "Chart double-tapped.");
}

@Override
public void onChartSingleTapped(MotionEvent me) {
    Log.i("SingleTap", "Chart single-tapped.");
}

@Override
public void onChartFling(MotionEvent me1, MotionEvent me2,
                         float velocityX, float velocityY) {
    Log.i("Fling", "Chart flinged. VeloX: "
            + velocityX + ", VeloY: " + velocityY);
}

@Override
public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
    Log.i("Scale / Zoom", "ScaleX: " + scaleX + ", ScaleY: " + scaleY);
}

@Override
public void onChartTranslate(MotionEvent me, float dX, float dY) {
    Log.i("Translate / Move", "dX: " + dX + ", dY: " + dY);
}

@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
    Log.i("Entry selected", e.toString());
    Log.i("LOWHIGH", "low: " + mChart.getLowestVisibleXIndex()
            + ", high: " + mChart.getHighestVisibleXIndex());

    Log.i("MIN MAX", "xmin: " + mChart.getXChartMin()
            + ", xmax: " + mChart.getXChartMax()
            + ", ymin: " + mChart.getYChartMin()
            + ", ymax: " + mChart.getYChartMax());
}

@Override
public void onNothingSelected() {
    Log.i("Nothing selected", "Nothing selected.");
}


private void showGraph(){

    JSONObject jsonObject = null;
    ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
    allBatchNo = new ArrayList<String>();
    allFCR = new ArrayList<String>();
    resultcount = 0;


    try {
        jsonObject = new JSONObject(JSON_STRING);
        result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
        for(int i = 0; i<result.length(); i++){
            JSONObject jo = result.getJSONObject(i);
            stringbatchno = jo.getString(Config.TAG_BATCHNO);
            stringfcr = jo.getString(Config.TAG_FCR);


            allBatchNo.add(stringbatchno);
            allFCR.add(stringfcr);
            resultcount++;

        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    xValstosetdata = setXAxisValues(resultcount, allFCR);
    yValstosetdata = setYAxisValues(resultcount, allBatchNo);
    setData(xValstosetdata,yValstosetdata);







}

private void getJSON() {
    class GetJSON extends AsyncTask<Void, Void, String> {

        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(ViewGraph.this, "Fetching Data", "Wait...", false, false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            JSON_STRING = s;
            showGraph();
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(Config.URL_GET_VIEW_GRAPH);
            return s;
        }
    }
    GetJSON gj = new GetJSON();
    gj.execute();
}

private ArrayList<String> setXAxisValues(int count, ArrayList<String> stringListx) {
    this.xVals = new ArrayList<String>();
    for (int i = 0; i < count; i++){
        xVals.add(stringListx.get(i));

}
    return xVals;
}


private ArrayList<Entry> setYAxisValues(int cnt, ArrayList<String> stringListy){
    this.yVals = new ArrayList<Entry>();

    for(int j=0; j<cnt;j++) {
        int y = Integer.valueOf(stringListy.get(j));
        yVals.add(new Entry(y,j));
    }
    return yVals;
}

private void setData(ArrayList<String> xArray,ArrayList<Entry> yArray) {

    ArrayList<String> xValues = xArray;

    ArrayList<Entry> yValues = yArray;

    LineDataSet set1;

    // create a dataset and give it a type
    set1 = new LineDataSet(yValues, "DataSet 1");
    set1.setFillAlpha(110);
    // set1.setFillColor(Color.RED);

    // set the line to be drawn like this "- - - - - -"
    // set1.enableDashedLine(10f, 5f, 0f);
    // set1.enableDashedHighlightLine(10f, 5f, 0f);
    set1.setColor(Color.BLACK);
    set1.setCircleColor(Color.BLACK);
    set1.setLineWidth(1f);
    set1.setCircleRadius(3f);
    set1.setDrawCircleHole(false);
    set1.setValueTextSize(9f);
    set1.setDrawFilled(true);

    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
    dataSets.add(set1); // add the datasets

    // create a data object with the datasets
    LineData data = new LineData(xValues, dataSets);

    // set data
    mChart.setData(data);

}

}

Bellow is my layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/linechart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

I've already put these codes in my build.gradle file:

repositories {
    maven { url "https://jitpack.io" }
}

dependencies {
compile 'com.github.PhilJay:MPAndroidChart:v2.2.4'
}

The application shows a blank graph: [][1]

[1]: https://i.stack.imgur.com/lT3dA.jpg

What could be the problem here? Did I screwed up at calling the right method? Thanks for your respond. I really appreciate it.

Sorry for the grammar and the wrong format. Its my first time posting here.

  • 写回答

1条回答 默认 最新

  • dongshi4589 2017-05-03 17:35
    关注

    On my php code for retrieving data from MySql i replaced

    "BatchNo"=>$row['BatchNo']
     "FCR"=>$row['FCR']
    

    with

    "BatchNo"=>$row['BatchNo'],
     "FCR"=>$row['FCR']
    

    It's working now.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题