如何在Android的GeoChart中获取arrayToDataTable()?

时间:2019-02-22 04:03:02

标签: javascript java android google-visualization

var data = google.visualization.arrayToDataTable(JSON.parse(newRows), false);

我无法传递var数据的arrayToDataTable()中的数据,因为字符串数据的newRows无法获取newRows数据。 所以请帮忙。

我在下面插入了如何获取GeoChart的代码。

GeoChartData.java

public class GeoChartData {


int id;
String Country;
String Total;

@JavascriptInterface
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@JavascriptInterface
public String getCountry() {
    return Country;
}

public void setCountry(String country) {
    Country = country;
}

@JavascriptInterface
public String getTotal() {
    return Total;
}

public void setTotal(String total) {
    Total = total;
}


@Override
public String toString() {

   return  "\n[" + "'" + Country + "'"+ ":" +Integer.valueOf(Total)+ "]";
}}

GeoChartActivity.java

 @SuppressLint("SetJavaScriptEnabled")
  public class GeoChartActivity extends Activity {


WebView webView;
int num1, num2;

List listOfCountry;


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



    num1 = 390;

    webView = (WebView)findViewById(R.id.web);


    webView.addJavascriptInterface(new WebAppInterface(), "Android");


    webView.getSettings().setJavaScriptEnabled(true);

    webView.loadUrl("file:///android_asset/geochart.html");


    webView.setPadding(0, 0, 0, 0);



}


public class WebAppInterface {

    @JavascriptInterface
    public String getArrayGeoChartData() {
       // System.out.println(listOfCountry.toString());
        return String.valueOf(getCountryData());
    }

    @JavascriptInterface
    public int getNum1() {
        return num1;
    }


}



 public List getCountryData() {


    listOfCountry = new ArrayList<>();


    GeoChartData s1 = new GeoChartData();
    s1.setId(100);
    s1.setCountry("Germany");
    s1.setTotal("200");
    listOfCountry.add(s1);

    GeoChartData s2 = new GeoChartData();
    s2.setId(101);
    s2.setCountry("Canada");
    s2.setTotal("200");
    listOfCountry.add(s2);


    return listOfCountry;
} }

assets / geochart.html

 <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {
        'packages':['geochart'],
        // Note: you will need to get a mapsApiKey for your project.
        // See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
        'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
      });
      google.charts.setOnLoadCallback(drawRegionsMap);

      var newRows = [];
     var rowData = [];
var dataTable = null;
      function drawRegionsMap() {


//console.log(Android.getArrayGeoChartData());


var jsonString = Android.getArrayGeoChartData(); // json string of array
console.log(jsonString);

newRows.push(jsonString);
console.log(newRows);

 var dataArray = ["['Country', 'Popularity']"];
console.log(dataArray);

console.log(dataArray.push(dataArray, newRows));



 var data = google.visualization.arrayToDataTable(JSON.parse(newRows), false);
 //data.setColumnProperty ('Country', 'Popularity');


         var csv = google.visualization.dataTableToCsv(data);
    console.log(csv);

      // console.log("france" +Android.getNum1());


        var options = {};

        var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="regions_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

发生错误

enter image description here

1 个答案:

答案 0 :(得分:0)

https://ctalandroid.blogspot.com/2019/02/android-geochart.html

GeoChartActivity.java

@SuppressLint("SetJavaScriptEnabled")
public class GeoChartActivity extends Activity {


    String url = "https://battery-75d95.firebaseio.com/";

    WebView webView;
    int num1, num2;
    public static  List<GeoTotalByCountry> lstItemArry;
    List listOfStudent;

    public static List<Order> salArry;
    public static List<Order> hosArry;
    public static List<Order> ProductData;


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

        ProductData = new ArrayList<>();
        hosArry = new ArrayList();
        salArry = new ArrayList();
        lstItemArry = new ArrayList();

        listOfStudent = new ArrayList();



        getOrderArray();


        num1 = 390;

        webView = (WebView)findViewById(R.id.web);


        webView.addJavascriptInterface(new WebAppInterface(), "Android");


        webView.getSettings().setJavaScriptEnabled(true);
        // webView.loadUrl("file:///android_asset/chart.html");

        webView.loadUrl("file:///android_asset/geochart.html");

        //WebView web = new WebView(this);
        webView.setPadding(0, 0, 0, 0);



    }








    public class WebAppInterface {

        @JavascriptInterface
        public String getArrayGeoChartData() {
//            System.out.println(listOfStudent.toString());
            return String.valueOf(listOfStudent);
        }

        @JavascriptInterface
        public int getNum1() {
            return num1;
        }


    }








    //arrayOrder
    void getOrderArray() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);

        Call<List<Order>> call = service.getOrderDetails();

        call.enqueue(new Callback<List<Order>>() {
            @Override
            public void onResponse(Response<List<Order>> response, Retrofit retrofit) {

                try {
                    ProductData = response.body();
                    for (int i = 0; i < ProductData.size(); i++) {

                        //displaying the string array into gridView

                        Order b = new Order();
                        b.setId(ProductData.get(i).getId());
                        b.setStatus(ProductData.get(i).getStatus());
                        b.setTotal(ProductData.get(i).getTotal());
                        b.setBilling(ProductData.get(i).getBilling());
                        hosArry.add(b);

                    }

                    listOfStudent = new ArrayList<>();


                    //   Log.v("hosarry", String.valueOf(hosArry.size()));
                    for (int i =0; i<hosArry.size(); i++){

                      //  if(hosArry.get(i).getStatus().contains("completed"))
                        {
                            GeoTotalByCountry b = new GeoTotalByCountry();
                            b.setId(hosArry.get(i).getId());
                            b.setTotal(hosArry.get(i).getTotal());
                            b.setCountry(hosArry.get(i).getBilling().getCountry());
                            lstItemArry.add(b);
                        }
                    }
                 //   Log.v("listOfStudent", String.valueOf(salArry.size()));



             Map<String, List<GeoTotalByCountry>> map = new HashMap<String, List<GeoTotalByCountry>>();

                    for (GeoTotalByCountry student : lstItemArry) {
                        String key  = String.valueOf(student.getCountry());
                        if(map.containsKey(key)){
                            List<GeoTotalByCountry> list = map.get(key);
                            list.add(student);

                        }else{
                            List<GeoTotalByCountry> list = new ArrayList<GeoTotalByCountry>();
                            list.add(student);
                            map.put(key, list);
                        }

                    }


                    System.out.println("map"+map);


                    //Summing for Net Quentity

                    for (Map.Entry<String, List<GeoTotalByCountry>> entry : map.entrySet()) {
                        //  System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());

                        // for (int i=0 ; i< entry.getKey().length(); i++){
                        Double sum = 0.00, value;
                        for (int j = 0; j < entry.getValue().size(); j++){
                            value = Double.valueOf(String.valueOf(entry.getValue().get(j)));
                            //System.out.println(j+ "value = " + value);
                            sum += value;

                            //  System.out.println(j+"chgevalue = " + sum);
                        }
                        System.out.println("chgevalue = " + sum.intValue());

                        // System.out.println( "Key : " + entry.getKey() + "qty = " + sum);
                        //System.out.println(getProductById(Integer.valueOf(entry.getKey())));

                        ChartGeoModel pieDataXYChart = new ChartGeoModel();

                        pieDataXYChart.setCountry(entry.getKey());
                        pieDataXYChart.setTotal(sum.intValue());
                        listOfStudent.add(pieDataXYChart);
                    }

                    System.out.println(listOfStudent.toString());




                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    }
}

Androidmanifest.xml

<uses-permission android:name="android.permission.INTERNET" />

GeoTotalByCountry.java

public class GeoTotalByCountry {

    int id;
    String Country;
    String Total;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountry() {
        return Country;
    }

    public void setCountry(String country) {
        Country = country;
    }

    public String getTotal() {
        return Total;
    }

    public void setTotal(String total) {
        Total = total;
    }


    @Override
    public String toString() {
        return String.valueOf(Total);
    }
}

ChartGeoModel.java

public class ChartGeoModel {

    int id;
    String Country;
    int Total;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountry() {
        return Country;
    }

    public void setCountry(String country) {
        Country = country;
    }

    public int getTotal() {
        return Total;
    }

    public void setTotal(int total) {
        Total = total;
    }

    @Override
    public String toString() {
        return new Gson().toJson(this);
    }

}

assets / geochart.html

<html>
  <head>
      <!--Load the AJAX API-->
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {
        'packages':['geochart'],
        // Note: you will need to get a mapsApiKey for your project.
        // See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
        'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
      });
      google.charts.setOnLoadCallback(drawRegionsMap);

      var newRows = [];
     var rowData = [];
var dataTable = null;
var data=[];


function drawRegionsMap() {


var jsonString = Android.getArrayGeoChartData(); // json string of array
console.log(jsonString);

newRows.push(jsonString);
console.log(newRows);

var obj = JSON.parse(newRows);
console.log(obj);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'NetTotal');

for (var i = 0; i < obj.length; i++) {
     data.addRow([obj[i].Country, obj[i].Total]);
}


 var csv = google.visualization.dataTableToCsv(data);
    console.log(csv);

// console.log("france" +Android.getNum1());

        var options = {};

        var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="regions_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>