Skip to main content

Android GeoChart

Reference:

https://developers.google.com/chart/interactive/docs/gallery/geomap
http://jsfiddle.net/Mep7R/4/

Marker = https://jsfiddle.net/doktormolle/S6vBK/

India= https://jsfiddle.net/jitendravyas/f5ZLn/

Google Charts = https://www.tutorialspoint.com/googlecharts/
Google =https://developers.google.com/chart/interactive/docs/quick_start

doc =  http://zetcode.com/web/googlecharts/#








 
 
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>



Example 2:

MainActivity.java

public class MainActivity extends ActionBarActivity {

   

   EditText num1, num2, num3, num4, num5;

   Button btnShow;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        num1 = (EditText)findViewById(R.id.num1);

        num2 = (EditText)findViewById(R.id.num2);

        num3 = (EditText)findViewById(R.id.num3);

        num4 = (EditText)findViewById(R.id.num4);

        num5 = (EditText)findViewById(R.id.num5);

        btnShow = (Button)findViewById(R.id.show);

        

        btnShow.setOnClickListener(btnShowOnClickListener);

    }

    

    OnClickListener btnShowOnClickListener =

       new OnClickListener(){



         @Override

         public void onClick(View v) {

            Intent intent = new Intent(

               MainActivity.this, 

               ShowWebChartActivity.class);

            

            intent.putExtra("NUM1", getNum(num1));

            intent.putExtra("NUM2", getNum(num2));

            intent.putExtra("NUM3", getNum(num3));

            intent.putExtra("NUM4", getNum(num4));

            intent.putExtra("NUM5", getNum(num5));



            startActivity(intent);

         }

       

    };

    

    private int getNum(EditText editText){

       

       int num = 0;



       String stringNum = editText.getText().toString();

       if(!stringNum.equals("")){

          num = Integer.valueOf(stringNum);

       }

       

       return (num);

    }



}




ShowWebChartActivity.java
@SuppressLint("SetJavaScriptEnabled") 

public class ShowWebChartActivity extends ActionBarActivity {

   

   WebView webView;

   int num1, num2, num3, num4, num5;



   @Override

   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_webchart);

        

        Intent intent = getIntent();

        num1 = intent.getIntExtra("NUM1", 0);

        num2 = intent.getIntExtra("NUM2", 0);

        num3 = intent.getIntExtra("NUM3", 0);

        num4 = intent.getIntExtra("NUM4", 0);

        num5 = intent.getIntExtra("NUM5", 0);

        

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

      //webView.setInitialScale(getScale());



      //webView.getSettings().setLoadWithOverviewMode(true);

      //webView.getSettings().setUseWideViewPort(true);





   }







   private int getScale(){

      Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

      int width = display.getWidth();

      Double val = new Double(width)/new Double(500.00);

      val = val * 100d;

      return val.intValue();

   }







   public class WebAppInterface {



       @JavascriptInterface

      public int getNum1() {

         return num1;

      }

      

      @JavascriptInterface

      public int getNum2() {

         return num2;

      }

      

      @JavascriptInterface

      public int getNum3() {

         return num3;

      }

      

      @JavascriptInterface

      public int getNum4() {

         return num4;

      }

      

      @JavascriptInterface

      public int getNum5() {

         return num5;

      }

   }



}


assets/chart.html

<html>

  <head>

    <!--Load the AJAX API-->

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script type="text/javascript">

    

      // Load the Visualization API and the piechart package.

      google.load('visualization', '1.0', {'packages':['corechart']});

      

      // Set a callback to run when the Google Visualization API is loaded.

      google.setOnLoadCallback(drawChart);



      // Callback that creates and populates a data table, 

      // instantiates the pie chart, passes in the data and

      // draws it.

      function drawChart() {



      // Create the data table.

      var data = new google.visualization.DataTable();

      data.addColumn('string', 'ITEM');

      data.addColumn('number', 'VALUE');

      data.addRows([

        ['Item 1', Android.getNum1()],

        ['Item 2', Android.getNum2()],

        ['Item 3', Android.getNum3()], 

        ['Item 4', Android.getNum4()],

        ['Item 5', Android.getNum5()]

      ]);



      // Set chart options

      var options = {'title':'Android-er: Load Google Charts (pie chart) with WebView',

                     'width':600,

                     'height':600};



      // Instantiate and draw our chart, passing in some options.

      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

      chart.draw(data, options);

    }

    </script>

  </head>

  <body>

   <!--Div that will hold the pie chart-->

    <div id="chart_div" style="width:600; height:600"></div>

 </body>

</html>

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!