Rss

Archives for : java basic

JSON Java & PHP

I want to show you how to get the value of the variable from php to java using JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate(wikipedia).

First, you build your database and create a table. For this example, I want to make a table named “personal”.

CREATE TABLE IF NOT EXISTS `personal` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nama` varchar(40) NOT NULL,
  `nik` varchar(40) NOT NULL,
  `jabatan` varchar(40) NOT NULL,
  `email` varchar(120) NOT NULL,
  `alamat` varchar(140) NOT NULL,
  `hp` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Then, don’t forget to config the main.xml (for Android)


	
	

Then, you build your java class, for this example, I build for android. So the code will be like:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class ViewDataActivity extends Activity {
	private JSONObject jObject;
	private String xResult = "";
	private Button back;
	private String url = "http://10.0.2.2/android/datakaryawan.php";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.datakaryawan);
		back = (Button) findViewById(R.id.back);
		back.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				goToMenu();
			}
		});
		TextView txtResult = (TextView) findViewById(R.id.TextViewResult);
		url += "?nik=" + UserData.getEmail();
		xResult = getRequest(url);
		try {
			parse(txtResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse(TextView txtResult) throws Exception {
		jObject = new JSONObject(xResult);
		JSONArray menuitemArray = jObject.getJSONArray("personal");
		String sret = "";
		int j = 0;
		for (int i = 0; i < menuitemArray.length(); i++) {
			sret += "Data Karyawan  : n n";
			sret += "Nama  : "
					+ menuitemArray.getJSONObject(i).getString("nama")
							.toString() + "n";
			sret += "NIK      : "
					+ menuitemArray.getJSONObject(i).getString("nik")
							.toString() + "n";
			sret += "E-mail : "
					+ menuitemArray.getJSONObject(i).getString("email")
							.toString() + "n";
			sret += "Alamat: "
					+ menuitemArray.getJSONObject(i).getString("alamat")
							.toString() + "n";
			sret += "No HP  : "
					+ menuitemArray.getJSONObject(i).getString("hp").toString()
					+ "n";
			sret += "Jabatan: "
					+ menuitemArray.getJSONObject(i).getString("jabatan")
							.toString() + "n";
			j = i;
		}
		txtResult.setText(sret);
	}
	/**
	 * Method untuk Mengirimkan data kes erver event by button login diklik
	 * 
	 * @param view
	 */
	public String getRequest(String Url) {
		String sret = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(Url);
		try {
			HttpResponse response = client.execute(request);
			sret = request(response);
		} catch (Exception ex) {
			Toast.makeText(this, "Gagal " + sret, Toast.LENGTH_SHORT).show();
		}
		return sret;
	}
	/**
	 * Method untuk Menenrima data dari server
	 * 
	 * @param response
	 * @return
	 */
	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;
	}
	public void goToMenu() {
		finish();
	}
}

Next, you build the php code.

$nik = $_GET['nik'];//get nilai user from client
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('cuti', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM personal where nik='$nik'";
$result = mysql_query($query, $link) or die('Errorquery:  '.$query);
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
	$rows[] = $r;
}
$data = "{personal:".json_encode($rows)."}";
echo $data;
$query2 = "SELECT * FROM cuti where nik='$nik'";
$result2 = mysql_query($query2, $link) or die('Errorquery:  '.$query2);
$rows2 = array();
while ($r2 = mysql_fetch_assoc($result2)) {
	$rows2[] = $r2;
}
$data2 = "{cuti:".json_encode($rows2)."}";
echo $data2;

the result will be like this:

Encapsulation

package exercise4;

public class Telepon {
private int durasi, tarif;
private String kodeAsal, kodeTujuan, nomorAsal, nomorTujuan;

public int ongkos() {
if (kodeAsal.equals(kodeTujuan)) {
tarif = 100;
} else {
tarif = 200;
}
return tarif * durasi;
}

public int getDurasi() {
return durasi;
}

public void setDurasi(int durasi) {
this.durasi = durasi;
}

public String getKodeAsal() {
return kodeAsal;
}

public void setKodeAsal(String kodeAsal) {
this.kodeAsal = kodeAsal;
}

public String getKodeTujuan() {
return kodeTujuan;
}

public void setKodeTujuan(String kodeTujuan) {
this.kodeTujuan = kodeTujuan;
}

public String getNomorAsal() {
return nomorAsal;
}

public void setNomorAsal(String nomorAsal) {
this.nomorAsal = nomorAsal;
}

public String getNomorTujuan() {
return nomorTujuan;
}

public void setNomorTujuan(String nomorTujuan) {
this.nomorTujuan = nomorTujuan;
}
}

and for the main....


package exercise4;

public class Main {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Telepon tlp = new Telepon();
tlp.setKodeAsal("021");
tlp.setNomorAsal("948494");
tlp.setKodeTujuan("021");
tlp.setNomorTujuan("958394");
tlp.setDurasi(90);
System.out.println(tlp.ongkos());
}

}