Andoid

Bmob+Android+ECharts 实现移动端数据上传与图

2017-05-23  本文已影响0人  Haraway

Bmob:后端云 全方位一体化的后端服务平台,无需再造应用后端服务 轻松拥有开发中需要的各种后端能力。
  ECharts:开源图表库,丰富的可视化效果,多图表类型,满足不同数据的处理需求 更多的搭配方案让你的数据呈现方式更个性和完美。

1,Android Bmob使用

官方文档:http://docs.bmob.cn/data/Android/a_faststart/doc/index.html

1)在 Project 的 build.gradle 文件中添加 Bmob的maven仓库地址,

  allprojects {
     repositories {
         jcenter()
         //Bmob的maven仓库地址--必填
         maven { url "https://raw.github.com/bmob/bmob-android-sdk/master" }
     }
 }

2)在app的build.gradle文件中添加compile依赖文件,

        //如果你想应用能够兼容Android6.0,请添加此依赖(org.apache.http.legacy.jar)
        compile 'cn.bmob.android:http-legacy:1.0'

3)Bmob初始化,

       //默认初始化
        Bmob.initialize(this, "Your Application ID");
        // 注:自v3.5.2开始,数据sdk内部缝合了统计sdk,开发者无需额外集成,传渠道参数即可,不传默认没开启数据统计功能
        //Bmob.initialize(this, "Your Application ID","bmob");

4)Bmob使用。
  首先建立数据对象AddressIofo,

package com.demo.xiep.mode;

import cn.bmob.v3.BmobObject;

/**
 * 作者:xiep on 2017/5/22 10:38
 */

public class AddressIofo extends BmobObject {
    /** 国家 */
    private String country;
    private String country_id;
    /** 地区 */
    private String area;
    private String area_id;
    /** 省 */
    private String region;
    private String region_id;
    /** 市 */
    private String city;
    private String city_id;
    /** 县 */
    private String county;
    private String county_id;

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry_id() {
        return country_id;
    }

    public void setCountry_id(String country_id) {
        this.country_id = country_id;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getArea_id() {
        return area_id;
    }

    public void setArea_id(String area_id) {
        this.area_id = area_id;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getRegion_id() {
        return region_id;
    }

    public void setRegion_id(String region_id) {
        this.region_id = region_id;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCity_id() {
        return city_id;
    }

    public void setCity_id(String city_id) {
        this.city_id = city_id;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    public String getCounty_id() {
        return county_id;
    }

    public void setCounty_id(String county_id) {
        this.county_id = county_id;
    }
}

通过BmobObject进行数据操作。

package com.demo.xiep;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.demo.xiep.mode.AddressIofo;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.UpdateListener;

public class MainActivity extends AppCompatActivity {

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

        //第一:默认初始化
        Bmob.initialize(this, "App ID");

        Button AddData = (Button) findViewById(R.id.add_data);
        Button QueryData = (Button) findViewById(R.id.query_data);
        Button ModifyData = (Button) findViewById(R.id.modify_data);
        Button DeleteData = (Button) findViewById(R.id.delete_data);

        AddData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addData();
            }
        });

        QueryData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryData();
            }
        });

        ModifyData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyData();
            }
        });

        DeleteData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
            }
        });
    }

    private void addData() {
        List<BmobObject> addressIofos = new ArrayList<BmobObject>();
        for (int i = 0; i < 10; i++) {
            AddressIofo addressIofo = new AddressIofo();
            addressIofo.setCountry("中国");
            addressIofo.setRegion("广东");
            addressIofo.setCity("深圳");
            addressIofos.add(addressIofo);
        }
        for (int i = 0; i < 5; i++) {
            AddressIofo addressIofo = new AddressIofo();
            addressIofo.setCountry("中国");
            addressIofo.setRegion("广东");
            addressIofo.setCity("广州");
            addressIofos.add(addressIofo);
        }
        for (int i = 0; i < 5; i++) {
            AddressIofo addressIofo = new AddressIofo();
            addressIofo.setCountry("中国");
            addressIofo.setRegion("湖南");
            addressIofo.setCity("长沙");
            addressIofos.add(addressIofo);
        }
        new BmobBatch().insertBatch(addressIofos).doBatch(new QueryListListener<BatchResult>() {

            @Override
            public void done(List<BatchResult> o, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < o.size(); i++) {
                        BatchResult result = o.get(i);
                        BmobException ex = result.getError();
                        if (ex == null) {
                            Log.i("bmob", "第" + i + "个数据批量添加成功:" + result.getCreatedAt() + "," + result.getObjectId() + "," + result.getUpdatedAt());
                        } else {
                            Log.i("bmob", "第" + i + "个数据批量添加失败:" + ex.getMessage() + "," + ex.getErrorCode());
                        }
                    }
                } else {
                    Log.i("bmob", "失败:" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private void queryData() {
        BmobQuery<AddressIofo> query = new BmobQuery<AddressIofo>();
        //查询playerName叫“比目”的数据
        query.addWhereEqualTo("country", "中国");
        query.order("-createdAt");// 按照时间降序
        //返回50条数据,如果不加上这条语句,默认返回10条数据
        query.setLimit(100);
        //执行查询方法
        query.findObjects(new FindListener<AddressIofo>() {
            @Override
            public void done(List<AddressIofo> object, BmobException e) {
                if (e == null) {
                    toast("查询成功:共" + object.size() + "条数据。");
                    for (AddressIofo addressIofo : object) {
                        //获得playerName的信息
                        addressIofo.getCountry();
                        //获得数据的objectId信息
                        addressIofo.getRegion();
                        //获得createdAt数据创建时间(注意是:createdAt,不是createAt)
                        addressIofo.getCreatedAt();

                        Log.i("bmob", "成功:" + addressIofo.getCountry() + "," + addressIofo.getRegion() + "," + addressIofo.getCity() + "," + addressIofo.getCreatedAt());
                    }
                } else {
                    Log.i("bmob", "失败:" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private void modifyData() {
        //更新Person表里面id为6b6c11c537的数据,address内容更新为“北京朝阳”
        final AddressIofo p2 = new AddressIofo();
        p2.setCity("常德");
        p2.update("1ec0b8868d", new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    toast("更新成功:" + p2.getUpdatedAt());
                } else {
                    toast("更新失败:" + e.getMessage());
                }
            }

        });
    }

    private void deleteData() {
        final AddressIofo p2 = new AddressIofo();
        p2.setObjectId("4baf4e4f1b");
        p2.delete(new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    toast("删除成功:" + p2.getUpdatedAt());
                } else {
                    toast("删除失败:" + e.getMessage());
                }
            }

        });
    }

    private void toast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }
}

数据操作结果:

Address数据库后台.png

2,JavaScript Bmob使用

1)安装BmobSDK
把下面这行代码加入你的页面中,其中,"bmob-min.js"为SDK文件:

<script src="bmob-min.js"></script>

2)接着是加入下面这行代码进行初始化

Bmob.initialize("你的Application ID", "你的REST API Key");

3,Echarts 图表使用

官方文档:http://echarts.baidu.com/index.html

1)引入 ECharts

<script src="echarts.min.js"></script>

2)创建echarts实例

 <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        var option = {
            ···
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    </script>

完整示例:

<html>  
 <head>  
  <meta http-equiv="content-type" content="text/html;charset=utf-8">  
<title>Demo</title>
<style>

</style>

</head>

    <div id="main" style="width: 1280px;height:720px;"></div>

<body>

<script src="http://echarts.baidu.com/gallery/vendors/jquery/jquery.js"></script>  
<script src="http://echarts.baidu.com/dist/echarts.min.js"></script>
<script src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/china.js"></script>
<script src="http://7xwlc0.com1.z0.glb.clouddn.com/bmob-min.js"></script>

<script type="text/javascript">
Bmob.initialize("你的Application ID", "你的REST API Key");

var DeviceData = Bmob.Object.extend("DeviceData");
var query = new Bmob.Query(DeviceData);
// 查询所有数据
query.find({
  success: function(results){
       
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
  myChart.hideLoading();

    myChart.setOption(option = {
    title: {
        text: '设备信息',
        subtext: '纯属虚构',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left',
        data:['device']
    },
    visualMap: {
        min: 0,
        max: 2500,
        left: 'left',
        top: 'bottom',
        text: ['高','低'],           // 文本,默认为数值文本
        calculable: true
    },
    toolbox: {
        show: true,
        orient: 'vertical',
        left: 'right',
        top: 'center',
        feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}
        }
    },
    series: [
        {
            name: 'device',
            type: 'map',
            mapType: 'china',
            roam: false,
            label: {
                normal: {
                    show: true
                },
                emphasis: {
                    show: true
                }
            },
             data: convertData(results)
        }
    ]
});
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);

    // alert("共查询到 " + results.length + " 条记录");

  },
  error: function(error) {
    alert("查询失败: " + error.code + " " + error.message);
  }
});
     
function convertData(results) {
  // console.log("共查询到 results " + results);
    var res = [];
   for (var i = 0; i < results.length; i++) {     
           var object = results[i];
           res.push({
               name: object.get('name'),
               value: object.get('value')
           });

            // alert(object.id + ' - ' + object.get('name'));

           console.log("results[i].name " + object.get('name') + ' - ' + object.get('value'));
   }
   // console.log("共查询到 res " + res);
   return res;
};

</script>
</body>
</html>

示例图表生成效果:


设备信息地图1.png 设备信息地图2.png

如需要使用世界地图只需引入世界地图资源:

<!-- <script src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/china.js"></script> -->
<script src="http://gallery.echartsjs.com/dep/echarts/map/js/world.js"></script>

使用ECharts生成其他图表示例:

饼图.png 雷达图.png

Android 源码下载地址:http://7xwlc0.com1.z0.glb.clouddn.com/AddressInfoDemo.zip
Bmob+Android+ECharts :http://7xwlc0.com1.z0.glb.clouddn.com/DeviceInfo.html

上一篇下一篇

猜你喜欢

热点阅读