Taking Android JSON Data from PHP MySQL Web Database



Authors want to share the knowledge to make the Android Application to Access Data in the form of JSON from MySQL PHP Web Database. Before this collection belongs to the author of the program code is still fragmentary. This time the author managed to collect into an example of a complete program to retrieve data from MySQL PHP Web Server using JSON and then followed by Android Application Adds Data from Web to MySQL with PHP POST method. Mengupdat data by POST method as well. Deleting the data and we try to use the GET method. 

Because this application is quite long. The author divides into 4 sections: 
1. Take the JSON data from PHP MySQL 
2. Adding Data to MySQL PHP using POST. 
3. Edit / update data to MySQL PHP using POST method. 
4. Deleting Data in MySQL with PHP GET method. 

While the source code sharing program writer and can be downloaded under the four sections are complete. Please downloaded. 

In this article we discuss the first part of the Take Data JSON PHP MySQL: 

On the Web PHP MySQL open localhost / phpmyadmin, create a database and make `db` table `city` in it with the following SQL command: 

CREATE TABLE IF NOT EXISTS `city` ( 
`Id` int (11) NOT NULL AUTO_INCREMENT, 
`Name` varchar (200) DEFAULT NULL, 
`Latitude` varchar (100) DEFAULT NULL, 
`Longitude` varchar (100) DEFAULT NULL, 
PRIMARY KEY (`id`) 
) ENGINE = MyISAM DEFAULT CHARSET = latin1 AUTO_INCREMENT = 5; 

INSERT INTO `city` (`id`, `name`, `latitude`, `longitude`) VALUES 
(1, 'Yogyakarta', '111111 ', '222222'), 
(2, 'Semarang', '333333 ', '444444'), 
(3, 'Solo', '5555555 ', '6666666'), 
(4, 'Magelang', '7777777 ', '8888888'); 





Then in the htdocs folder in this case we made in the / xampp / htdocs / json / daftarkota.php, we create a PHP file to retrieve data in a MySQL database and display the JSON format. code is as follows: 

<? Php 
$ Link = mysql_connect ('localhost', 'root','') or die ('Can not connect to the DB'); 
mysql_select_db ('db', $ link) or die ('Can not select the DB'); 

$ Query = "SELECT * FROM cities"; 
$ Result = mysql_query ($ query, $ link) or die ('Errorquery:'. $ Query); 

$ Rows = array (); 
while ($ r = mysql_fetch_assoc ($ result)) { 
$ Rows [] = $ r; 
} 
$ Data = "{city:". Json_encode ($ rows). "}"; 
echo $ data; 
?> 

Then connect the first computer where the MySQL server is PHP with an IP network so that it is active. Click Start, Search type "cmd", at the DOS command ipconfig type the following command to obtain the IP addresses that computers will be used in the Android source code to connect to a web server 


Then we go to the Android Project. Open Eclipse, create a new Android project. 

The main program we put in MainActivity 

MainActivity.java 

com.amijaya.androidphpmysqljson package; 

import java.io.BufferedReader; 
import java.io.InputStream; 
java.io.InputStreamReader import; 

org.apache.http.HttpResponse import; 
org.apache.http.client.HttpClient import; 
org.apache.http.client.methods.HttpGet import; 
org.apache.http.impl.client.DefaultHttpClient import; 
org.json.JSONArray import; 
org.json.JSONException import; 
import org.json.JSONObject; 

android.app.Activity import; 
android.app.AlertDialog import; 
android.content.DialogInterface import; 
android.content.Intent import; 
android.os.Bundle import; 
android.view.Menu import; 
android.view.MenuItem import; 
android.view.View import; 
android.widget.AdapterView import; 
android.widget.ArrayAdapter import; 
android.widget.ListView import; 
android.widget.Toast import; 
android.widget.AdapterView.OnItemClickListener import; 

/ / Http://cariprogram.blogspot.com 
/ / Nuramijaya@gmail.com 

public class extends Activity {MainActivity 
 private JSONObject jObject; 
 JsonResult private String = ""; 
 private String url = "http://192.168.43.150/json/daftarkota.php"; 
 private String url2 = "http://192.168.43.150/json/delkota.php"; 
 String [] daftarid; 
 String [] daftarnama; 
 String [] daftarlatitude; 
 String [] daftarlongitude; 
 Menu menu; 
 public static MainActivity ma; 

/ ** Called when the activity is first created. * / 
@ Override 
public void onCreate (Bundle savedInstanceState) { 
super.onCreate (savedInstanceState); 
setContentView (R.layout.main); 
        
ma = this; 
RefreshList (); 
} 
    
public void RefreshList () { 
 try { 
 JsonResult = getRequest (url); 
 
 jObject = new JSONObject (JsonResult); 
 JSONArray menuitemArray = jObject.getJSONArray ("city"); 

 daftarid = new String [menuitemArray.length ()]; 
 daftarnama = new String [menuitemArray.length ()]; 
 daftarlatitude = new String [menuitemArray.length ()]; 
 daftarlongitude = new String [menuitemArray.length ()]; 

 for (int i = 0; i <menuitemArray.length (); i + +) 
 { 
 daftarid [i] = menuitemArray.getJSONObject (i). getString ("id"). toString (); 
 daftarnama [i] = menuitemArray.getJSONObject (i). getString ("name"). toString (); 
 daftarlatitude [i] = menuitemArray.getJSONObject (i). getString ("latitude"). toString (); 
 daftarlongitude [i] = menuitemArray.getJSONObject (i). getString ("longitude"). toString (); 
 } 
 } Catch (JSONException e) { 
 / / TODO Auto-generated catch block 
 e.printStackTrace (); 
 } 
 
 ListView01 listview = (ListView) findViewById (R.id.ListView01); 
ListView01.setAdapter (new ArrayAdapter (this, android.R.layout.simple_list_item_1, daftarnama)); 
        
ListView01.setSelected (true); 
ListView01.setOnItemClickListener (new OnItemClickListener () { 
 @ Override 
 public void onItemClick (AdapterView <?> arg0, View arg1, int arg2, 
 Long Arg3) { 
 selectionid = daftarid final String [arg2]; 
 selectionnama = daftarnama final String [arg2]; 
 selectionlatitude = daftarlatitude final String [arg2]; 
 selectionlongitude = daftarlongitude final String [arg2]; 
 final CharSequence [] dialogitem = {"Edit", "Delete"}; 
 AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this); 
 builder.setTitle ("Choose?"); 
 builder.setItems (dialogitem, new DialogInterface.OnClickListener () { 
 public void onClick (DialogInterface dialog, int item) { 
 switch (item) { 
 case 0: 
 / * Intent i = new Intent (getApplicationContext (), EditActivity.class); 
 i.putExtra ("id", selectionid); 
 i.putExtra ("name", selectionnama); 
 i.putExtra ("latitude", selectionlatitude); 
 i.putExtra ("longitude", selectionlongitude); 
 startActivity (i); * / 
 
 break; 
 case 1: 
 / * GetRequest (url2 + "? Id =" + selectionid); 
 RefreshList (); 
* / 
 break; 
 } 
 } 
 }); 
 builder.create (.) show (); 
 }}); 

((ArrayAdapter) ListView01.getAdapter ()). NotifyDataSetInvalidated (); 
        
} 
    
/ ** 
 * Method for Transmitting data to the server 
 * / 
 public String getRequest (String url) { 

 Snip String = ""; 
 HttpClient client = new DefaultHttpClient (); 
 HttpGet request = new HttpGet (url); 
 try { 
 HttpResponse response = client.execute (request); 
 snip = request (response); 

 } Catch (Exception ex) { 
 Toast.makeText (this, "Failed" + slap, Toast.LENGTH_SHORT). Show (); 
 } 
 return slap; 

 } 
 / ** 
 * Method to Receive data from server 
 * / 
 public static String request (HttpResponse response) { 
 String result = ""; 
 try { 
 InputStream in = response.getEntity (). GetContent (); 
 BufferedReader reader = new BufferedReader (new InputStreamReader (in)); 
 StringBuilder str = new StringBuilder (); 
 String line = null; 
 while ((line = reader.readLine ())! = null) { 
 str.append (line + "\ n"); 
 } 
 in.close (); 
 result = str.toString (); 
 } Catch (Exception ex) { 
 result = "Error"; 
 } 
 return result; 
 } 
@ Override 
public boolean onCreateOptionsMenu (Menu menu) { 
 this.menu = menu; 
 
 menu.add (0, 1, 0, "Add"). setIcon (android.R.drawable.btn_plus); 
 menu.add (0, 2, 0, "Refresh"). setIcon (android.R.drawable.ic_menu_rotate); 
menu.add (0, 3, 0, "Exit"). setIcon (android.R.drawable.ic_menu_close_clear_cancel); 
 return true; 
} 
    
@ Override 
public boolean onOptionsItemSelected (MenuItem item) { 
switch (item.getItemId ()) { 
case 1: 
 / / Intent i = new Intent (MainActivity.this, AddActivity.class); 
 / / StartActivity (i); 
return true; 
case 2: 
RefreshList (); 
 return true; 
case 3: 
finish (); 
return true; 
} 
 return false; 
} 
} 

Then zoom we use only the default view and then added a single ListView with ListView01 name: 

main.xml 

<? Xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 
android: orientation = "vertical" 
android: layout_width = "fill_parent" 
android: layout_height = "fill_parent" 
> 
<TextView 
android: layout_width = "fill_parent" 
android: layout_height = "wrap_content" 
android: text = "Android JSON PHP MySQL" 
/> 
<ListView Android:id="@+id/ListView01" android:layout_width="match_parent" android:layout_height="wrap_content"> </ ListView> 
</ LinearLayout> 

Android Manifest should be added permisson to connect to the Internet: 

AndroidManifest.xml 

<? Xml version = "1.0" encoding = "utf-8"?> 
<Manifest xmlns: android = "http://schemas.android.com/apk/res/android" 
package = "com.amijaya.androidphpmysqljson" 
android: versionCode = "1" 
android: versionName = "1.0"> 
<application android:icon="@drawable/icon" android:label="@string/app_name"> 
<Activity android: name = ". MainActivity" 
android: label = "@ string / APP_NAME"> 
<intent-filter> 
<action android:name="android.intent.action.MAIN" /> 
<category android:name="android.intent.category.LAUNCHER" /> 
</ Intent-filter> 
</ Activity> 
 <! - Activity android: name = ". AddActivity" 
android: label = "@ string / APP_NAME"> 
</ Activity> 
<Activity android: name = ". EditActivity" 
android: label = "@ string / APP_NAME"> 
</ Activity -> 
</ Application> 
<uses-sdk android:minSdkVersion="8" /> 
 <uses-permission android:name="android.permission.INTERNET"/> 
</ Manifest> 

The result 


More Project please downloaded here: 

https://docs.google.com/open?id=0B4i1FYc_4RXzN2NOb29kYUcycW8 

Hopefully helpful, Happy Coding.

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...