Fixing Google Geo chart PHP + MYSQLi or XML parser complete tutorials

Fixing Google Geo chart PHP + MYSQLi or XML parser complete tutorials

 

Please Subscribe my Chanel on Youtube:

YouTube-Subscribe

google geo chart

Mysqltable is bellow:

google chart mysql

 

<?php $con = mysqli_connect('localhost','root','','test') or Die(); ?>
<html>
  <head>
   <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">
      google.load("visualization", "1", {packages:["geochart"]});
      google.setOnLoadCallback(drawRegionsMap);

      function drawRegionsMap() {

        var data = google.visualization.arrayToDataTable([

          ['Country', 'Visits'],
           <?php $query = "SELECT count(ip) AS count, country FROM visitors GROUP BY country"; $exec = mysqli_query($con,$query); while($row = mysqli_fetch_array($exec)){ echo "['".$row['country']."',".$row['count']."],"; } ?>
        ]);

        var options = {
        	
        };

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

        chart.draw(data, options);
      }
    </script>
  
    

   
  </head>
  <body>
 



<h3>Geo Chart</h3>






<div id="geochartsatu" style="width: 900px; height: 500px;"></div>



  
   
         

  </body>
</html>

Comparison JSON and XML parsing with PHP it’s easy

unduhan

Comparison JSON and XML parsing with PHP it’s easy.

PHP SimpleXML Introduction

SimpleXML is an extension that allows us to easily manipulate and get XML data.

Installation

As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to use these functions.

SimpleXML provides an easy way of getting an element’s name, attributes and textual content if you know the XML document’s structure or layout.

download

SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays and objects.

<?php
  $url = "http://data.bmkg.go.id/cuaca_indo_1.xml";
  $sUrl = file_get_contents($url, False);
  $xml = simplexml_load_string($sUrl);


for ($i=0; $i<sizeof($xml->Isi->Row); $i++) { 
	 $row = $xml->Isi->Row[$i];
?>

<a href="detailcuaca.php?detail=<?php echo $row->Kota; ?>"><?php echo $row->Kota; ?></a>
<?php echo "

Data Cuaca : ".$row->Cuaca." 

"; ?>
	

	   
<?php }?>

Android RecyclerView JSON Parsing using Retrofit

recyclerView

Dans nos précédents tutoriels nous avons appris à mettre en œuvre un RecyclerView simple et l’image de chargement dans RecyclerView utilisant Picasso . Dans ce tutoriel, nous allons apprendre comment analyser les données JSON d’ URL et de l’afficher dans RecyclerView en utilisant Rénovation. Nous analysons le JSON. réponse de l’URL http://api.learn2crack.com/android/jsonandroid.
Take a look at my previous RecyclerView tutorials for reference
Jetez un oeil à mes tutoriels RecyclerView précédentes pour référence

Retrofit est une bibliothèque de client HTTP par Square Inc. Il rend en réseau plus facile et aussi facile à mettre en œuvre .

Ici, je l’ai créé un projet Android Studio avec package com.learn2crack.recyclerjsonparsing également Activity as MainActivity et mise en page comme activity_main .

 

 

La dépendance pour Rénovation est

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'

Ensuite, nous devons ajouter la bibliothèque convertisseur Rénovation GSON . Cela prend en charge la sérialisation ( Convertis objets Java en JSON et vice versa )

compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

Les autres dépendances dont nous avons besoin

compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.android.support:cardview-v7:23.2.0'
La complète build.gradle
apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "com.learn2crack.recyclerjsonparsing"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:recyclerview-v7:23.2.0'
    compile 'com.android.support:cardview-v7:23.2.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
}

Nous avons besoin d’ajouter la permission d’ Internet dans notre AndroidManifest.xml

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

Mise en page Création

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.learn2crack.recyclerjsonparsing.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/card_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
La disposition suivante est pour la liste RecylerView article . Il dispose de trois widgets TextView à afficher Android nom de la version , le numéro de version et le niveau de l’API
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    card_view:cardCornerRadius="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_name"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="18sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"/>
        <TextView
            android:id="@+id/tv_version"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/tv_api_level"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</android.support.v7.widget.CardView>

Now we create AndroidVersion model class to store Android version name, version number and API level. We obtain a array of JSON objects similar to,

Maintenant, nous créons AndroidVersion classe modèle pour stocker Android nom de la version , le numéro de version et le niveau de l’API . Nous obtenons une gamme de JSON objets semblables,

{
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
}

This AndroidVersion model class stores the JSON object. The variable declaration name should be same as JSON object name. In the above JSON response, for JSON object name “ver” the variable name should be defined as “ver” ,

privateString ver;

The Retrofit GSON converter takes care of converting the JSON objects and store it in our model class.Then generate getter methods.

package com.ndesostyle.recyclerjsonparsing;
public class AndroidVersion {
    private String ver;
    private String name;
    private String api;
    public String getVer() {
        return ver;
    }
    public String getName() {
        return name;
    }
    public String getApi() {
        return api;
    }
}

Then we need to create a JSONResponse model. The JSON response has a only JSON object “android” with child JSON array. This child JSON array can be stored in AndroidVersion model class. In our JSONResponse model class create a AndroidVersion array variable named “android” and generate getter.

packagecom.ndesostyle.recyclerjsonparsing;
publicclassJSONResponse {
    privateAndroidVersion[] android;
    publicAndroidVersion[] getAndroid() {
        returnandroid;
    }
}

We need to create a Interface and define the Request endpoints. Here we use GET request to obtain JSON data. The endpoint is defined using @GET annotation. Our request URL is http://api.learn2crack.com/android/jsonandroid, wherehttp://api.learn2crack.com is base url and android/jsonandroid is endpoint.

For our request method getJSON() the JSONResponse object is wrapped in Call object. By using Call, the request is made Asynchronous so you need not worry about UI blocking or AsyncTask. The JSON response received after making the request it is stored in JSONResponse object.

package com.ndesostyle.recyclerjsonparsing;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
    @GET("android/jsonandroid")
    Call<JSONResponse> getJSON();
}

Creating Adapter

We are using the adapter similar to the one we used in our previous projects. We pass Androidversion model class as ArrayList in constructor. We obtain the Android version name, version number, API level from the AndroidVersion object using the getter methods and set it to TextView widgets.

package com.ndesostyle.recyclerjsonparsing;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private ArrayList<AndroidVersion> android;
    public DataAdapter(ArrayList<AndroidVersion> android) {
        this.android = android;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
        viewHolder.tv_name.setText(android.get(i).getName());
        viewHolder.tv_version.setText(android.get(i).getVer());
        viewHolder.tv_api_level.setText(android.get(i).getApi());
    }
    @Override
    public int getItemCount() {
        return android.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_name,tv_version,tv_api_level;
        public ViewHolder(View view) {
            super(view);
            tv_name = (TextView)view.findViewById(R.id.tv_name);
            tv_version = (TextView)view.findViewById(R.id.tv_version);
            tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
        }
    }
}

Creating Activity

The views are initialized in initViews() method. In the loadJSON() method we initialize Retrofit and carry out network operations. The Retrofit is defined using,

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.learn2crack.com")
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface object is created using

RequestInterface request = retrofit.create(RequestInterface.class);

To carry out a asyncronous request Call object should be created from RequestInterface object by calling getJSON() method.

Call<JSONResponse> call = request.getJSON();

The Asyncronous request is executed by calling enqueue() method on the call object. If the request is success and response is received onResponse() callback method is executed. The JSONResponse object is obtained by calling body() method on the Response object. From the JSONResponse object we obtain the AndroidVersion array object. We convert theAndroidVersion array object to ArrayList. Finally a new DataAdapter object is created and set to RecyclerView usingsetAdapter() method.

If the request fails onFailure() is executed.

package com.ndesostyle.recyclerjsonparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ArrayList<AndroidVersion> data;
    private DataAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    private void initViews(){
        recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }
    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.learn2crack.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
                JSONResponse jsonResponse = response.body();
                data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
                adapter = new DataAdapter(data);
                recyclerView.setAdapter(adapter);
            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }
}

Google chart 2016 PHP + MYSQLi Connection

Google chart 2016 PHP + MYSQLi Connection theme case is Populer startup in Indonesia (data is Fiktif)

googlechart_php+myqliconnection

 

googlechart


<?php //open connection to mysql db $connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection)); //fetch table rows from mysql db $sql = "select * from populer_startup"; $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection)); //create an array $rows = array(); //flag is not needed $flag = true; $table = array(); $table['cols'] = array( // Labels for your chart, these represent the column titles // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title array('label' => 'Startup', 'type' => 'string'),
    array('label' => 'Users', 'type' => 'number')
 
);
	

	$rows = array();
    while($r =mysqli_fetch_assoc($result))
    {
    $temp = array();
    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $r['name']); 
 
    // Values of each slice
    $temp[] = array('v' => (int) $r['custommer']);
    $rows[] = array('c' => $temp);
    }
	
  $table['rows'] = $rows;
   $jsonTable = json_encode($table);

?>



<html>
  <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
 
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});
 
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
 
    function drawChart() {
 
      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
           title: 'Populer startup in Indonesia. ',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>
 
  <body>
    <!--this is the div that will hold the pie chart-->

<div id="chart_div"></div>

  </body>
</html>