SlideShare a Scribd company logo
1 of 9
Download to read offline
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
Menambahkan / menyimpan data ke database pada Eclipse
Buat lah database local menggunakan XAMPP dan masuk ke alamat localhost/phpmyadmin
Buat database = “mahasiswa” dan nama tabel “biodata”
Setelah membuat database – buat file php untuk menghubungkan aplikasi
android kita dengan database mysql
Buat file “simpan.php”
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "mahasiswa";
$koneksi = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_error()) {
echo 'Gagal melakukan koneksi ke Database
:'.mysqli_connect_error();
}
$nim = $_POST['nim'];
$nama = $_POST['nama'];
$prodi = $_POST['prodi'];
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
$query = mysqli_query($koneksi, "INSERT INTO biodata (nim, nama, prodi)
VALUES ('$nim', '$nama','$prodi')");
$result = mysqli_query($koneksi, "SELECT * FROM mahasiswa where nim =
'$nim'");
$row = mysqli_fetch_array($result);
$data = $row[2];
if ($data)
{
echo "0";
} else {
echo "2";
}
mysqli_close($con);
?>
Setelah itu buat lah project baru dengan nama “SimpanDatabase”
Buatlah file java “CustomHttpClient.java”
package com.example.crud;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params,
HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url,
ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new
UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Setelah itu desain layout activity_main.xml
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
Berikut codingan lengkap activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/bgd">
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scrollbarStyle="insideInset">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/nim"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="NIM"
android:paddingRight="10dp" />
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/nama"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:paddingRight="10dp"
android:hint="Nama"
/>
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
android:id="@+id/prodi"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:paddingRight="10dp"
android:hint="Prodi"/>
<Button
android:id="@+id/btnsubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:background="@drawable/button"
android:paddingRight="10dp"
android:onClick="simpan"
android:text="SIMPAN" />
<Button
android:id="@+id/btn_back"
android:background="@drawable/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="KEMBALI" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Sekarang masuk ke kodingan MainActivity.java
package com.example.crud;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import android.content.Intent;
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
public class MainActivity extends Activity {
EditText nim, nama, prodi;
Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tambah);
nim = (EditText) findViewById(R.id.nim);
nama = (EditText) findViewById(R.id.nama);
prodi = (EditText) findViewById(R.id.prodi);
}
public void simpan (View View) {
String nim1 = nim.getText().toString();
String nama1 = nama.getText().toString();
String prodi1 = prodi.getText().toString();
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new
ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("nim", nim1));
postParameters.add(new BasicNameValuePair("nama", nama1));
postParameters.add(new BasicNameValuePair("prodi", prodi1));
String response = null;
try {
response =
CustomHttpClient.executeHttpPost("http://10.0.2.2/insert/Simpan.php",
postParameters);
String res = response.toString();
res = res.trim();
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
res = res.replaceAll("s+","");
if (res.equals("0"))
{
Toast.makeText(getApplicationContext(),"Data Sudah
Tersimpan" , Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Data Sudah
Tersimpan Ke Server" , Toast.LENGTH_LONG).show();
Intent i = new Intent(this, TampilActivity.class);
startActivity(i);
nim.setText("");
nama.setText("");
prodi.setText("");
}
} catch (Exception e) {
nim.setText(e.toString());
}
}
}
Sekarang kita masuk ke AndroidManifest.xml
Tambahkan
<uses-permission android:name="android.permission.INTERNET" >
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.crud"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
Mata kuliah : Mobile Technologies (3sks)
Dosen Pengampu : Tri Sugihartono, M.Kom
Materi : Simpan Data ke Database
Website : www.atmaluhur.ac.id
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

More Related Content

What's hot

#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX ConceptsGaurish Goel
 
Rx 101 Codemotion Milan 2015 - Tamir Dresher
Rx 101   Codemotion Milan 2015 - Tamir DresherRx 101   Codemotion Milan 2015 - Tamir Dresher
Rx 101 Codemotion Milan 2015 - Tamir DresherTamir Dresher
 
Box connector Mule ESB Integration
Box connector Mule ESB IntegrationBox connector Mule ESB Integration
Box connector Mule ESB IntegrationAnilKumar Etagowni
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleErich Beyrent
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Engaging users with live tiles and notifications
Engaging users with live tiles and notificationsEngaging users with live tiles and notifications
Engaging users with live tiles and notificationsAlex Golesh
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Nida Ismail Shah
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinNida Ismail Shah
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourCarl Brown
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompressSon Nguyen
 

What's hot (20)

Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Javascript 1
Javascript 1Javascript 1
Javascript 1
 
Android - Saving data
Android - Saving dataAndroid - Saving data
Android - Saving data
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX Concepts
 
Backendless apps
Backendless appsBackendless apps
Backendless apps
 
Rx 101 Codemotion Milan 2015 - Tamir Dresher
Rx 101   Codemotion Milan 2015 - Tamir DresherRx 101   Codemotion Milan 2015 - Tamir Dresher
Rx 101 Codemotion Milan 2015 - Tamir Dresher
 
Box connector Mule ESB Integration
Box connector Mule ESB IntegrationBox connector Mule ESB Integration
Box connector Mule ESB Integration
 
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate ModuleDigital Mayflower - Data Pilgrimage with the Drupal Migrate Module
Digital Mayflower - Data Pilgrimage with the Drupal Migrate Module
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
Engaging users with live tiles and notifications
Engaging users with live tiles and notificationsEngaging users with live tiles and notifications
Engaging users with live tiles and notifications
 
Hooks and Events in Drupal 8
Hooks and Events in Drupal 8Hooks and Events in Drupal 8
Hooks and Events in Drupal 8
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
 
Compress and decompress
Compress and decompressCompress and decompress
Compress and decompress
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 

Similar to Simpan data- ke- database

May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Struts database access
Struts database accessStruts database access
Struts database accessAbass Ndiaye
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppSyed Shahul
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenDavid Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenPostgresOpen
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyYahoo
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 

Similar to Simpan data- ke- database (20)

Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Step By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts AppStep By Step Guide For Buidling Simple Struts App
Step By Step Guide For Buidling Simple Struts App
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres OpenDavid Keeney - SQL Database Server Requests from the Browser @ Postgres Open
David Keeney - SQL Database Server Requests from the Browser @ Postgres Open
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Library Project
Library ProjectLibrary Project
Library Project
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Web based development
Web based developmentWeb based development
Web based development
 
Mail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - ItalyMail OnLine Android Application at DroidCon - Turin - Italy
Mail OnLine Android Application at DroidCon - Turin - Italy
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 

More from Tri Sugihartono

More from Tri Sugihartono (20)

Pertemuan 12 splash screen,+ create database
Pertemuan 12 splash screen,+ create databasePertemuan 12 splash screen,+ create database
Pertemuan 12 splash screen,+ create database
 
Pert 2. pengertian profesi dan profesionalisme
Pert 2. pengertian profesi dan profesionalismePert 2. pengertian profesi dan profesionalisme
Pert 2. pengertian profesi dan profesionalisme
 
Pert 1. pengantar etika profesi
Pert 1. pengantar etika profesiPert 1. pengantar etika profesi
Pert 1. pengantar etika profesi
 
Pertemuan 10 lanjutan 0
Pertemuan 10   lanjutan 0Pertemuan 10   lanjutan 0
Pertemuan 10 lanjutan 0
 
Pertemuan 10 lanjutan
Pertemuan 10   lanjutanPertemuan 10   lanjutan
Pertemuan 10 lanjutan
 
Pertemuan 7 file apk
Pertemuan 7   file apkPertemuan 7   file apk
Pertemuan 7 file apk
 
Pertemuan 12 simpan data ke database
Pertemuan 12   simpan data ke databasePertemuan 12   simpan data ke database
Pertemuan 12 simpan data ke database
 
Pertemuan 11 database
Pertemuan 11   databasePertemuan 11   database
Pertemuan 11 database
 
Pertemuan 6 login
Pertemuan 6   loginPertemuan 6   login
Pertemuan 6 login
 
Pertemuan 6 latihan
Pertemuan 6   latihanPertemuan 6   latihan
Pertemuan 6 latihan
 
Pertemuan 5 perhitungan
Pertemuan 5   perhitunganPertemuan 5   perhitungan
Pertemuan 5 perhitungan
 
Pertemuan 4 latihan
Pertemuan 4   latihanPertemuan 4   latihan
Pertemuan 4 latihan
 
Pertemuan 3 data string
Pertemuan 3   data stringPertemuan 3   data string
Pertemuan 3 data string
 
Pertemuan 2 hello world
Pertemuan 2   hello worldPertemuan 2   hello world
Pertemuan 2 hello world
 
Pertemuan 1 instalasi
Pertemuan 1   instalasiPertemuan 1   instalasi
Pertemuan 1 instalasi
 
Pertemuan1 installasi eclipse
Pertemuan1 installasi eclipsePertemuan1 installasi eclipse
Pertemuan1 installasi eclipse
 
Ch 12
Ch 12Ch 12
Ch 12
 
Ch 11
Ch 11Ch 11
Ch 11
 
Ch 10
Ch 10Ch 10
Ch 10
 
Ch 09
Ch 09Ch 09
Ch 09
 

Recently uploaded

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

Simpan data- ke- database

  • 1. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id Menambahkan / menyimpan data ke database pada Eclipse Buat lah database local menggunakan XAMPP dan masuk ke alamat localhost/phpmyadmin Buat database = “mahasiswa” dan nama tabel “biodata” Setelah membuat database – buat file php untuk menghubungkan aplikasi android kita dengan database mysql Buat file “simpan.php” <?php $db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "mahasiswa"; $koneksi = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if (mysqli_connect_error()) { echo 'Gagal melakukan koneksi ke Database :'.mysqli_connect_error(); } $nim = $_POST['nim']; $nama = $_POST['nama']; $prodi = $_POST['prodi'];
  • 2. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id $query = mysqli_query($koneksi, "INSERT INTO biodata (nim, nama, prodi) VALUES ('$nim', '$nama','$prodi')"); $result = mysqli_query($koneksi, "SELECT * FROM mahasiswa where nim = '$nim'"); $row = mysqli_fetch_array($result); $data = $row[2]; if ($data) { echo "0"; } else { echo "2"; } mysqli_close($con); ?> Setelah itu buat lah project baru dengan nama “SimpanDatabase” Buatlah file java “CustomHttpClient.java” package com.example.crud; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class CustomHttpClient { /** The time it takes for our client to timeout */ public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds /** Single instance of our HttpClient */ private static HttpClient mHttpClient; /** * Get our single instance of our HttpClient object.
  • 3. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id * * @return an HttpClient object with connection parameters set */ private static HttpClient getHttpClient() { if (mHttpClient == null) { mHttpClient = new DefaultHttpClient(); final HttpParams params = mHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); ConnManagerParams.setTimeout(params, HTTP_TIMEOUT); } return mHttpClient; } /** * Performs an HTTP Post request to the specified url with the * specified parameters. * * @param url The web address to post the request to * @param postParameters The parameters to send via the request * @return The result of the request * @throws Exception */ public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception { BufferedReader in = null; try { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }
  • 4. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id } /** * Performs an HTTP GET request to the specified url. * * @param url The web address to post the request to * @return The result of the request * @throws Exception */ public static String executeHttpGet(String url) throws Exception { BufferedReader in = null; try { HttpClient client = getHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } } Setelah itu desain layout activity_main.xml
  • 5. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id Berikut codingan lengkap activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/bgd"> <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:scrollbarStyle="insideInset"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <EditText android:id="@+id/nim" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:hint="NIM" android:paddingRight="10dp" /> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/nama" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="Nama" /> <EditText android:layout_height="wrap_content" android:layout_width="match_parent"
  • 6. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id android:id="@+id/prodi" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="Prodi"/> <Button android:id="@+id/btnsubmit" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:background="@drawable/button" android:paddingRight="10dp" android:onClick="simpan" android:text="SIMPAN" /> <Button android:id="@+id/btn_back" android:background="@drawable/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="KEMBALI" /> </LinearLayout> </ScrollView> </LinearLayout> Sekarang masuk ke kodingan MainActivity.java package com.example.crud; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.*; import android.content.Intent;
  • 7. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id public class MainActivity extends Activity { EditText nim, nama, prodi; Intent i; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_tambah); nim = (EditText) findViewById(R.id.nim); nama = (EditText) findViewById(R.id.nama); prodi = (EditText) findViewById(R.id.prodi); } public void simpan (View View) { String nim1 = nim.getText().toString(); String nama1 = nama.getText().toString(); String prodi1 = prodi.getText().toString(); // TODO Auto-generated method stub ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("nim", nim1)); postParameters.add(new BasicNameValuePair("nama", nama1)); postParameters.add(new BasicNameValuePair("prodi", prodi1)); String response = null; try { response = CustomHttpClient.executeHttpPost("http://10.0.2.2/insert/Simpan.php", postParameters); String res = response.toString(); res = res.trim();
  • 8. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id res = res.replaceAll("s+",""); if (res.equals("0")) { Toast.makeText(getApplicationContext(),"Data Sudah Tersimpan" , Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(),"Data Sudah Tersimpan Ke Server" , Toast.LENGTH_LONG).show(); Intent i = new Intent(this, TampilActivity.class); startActivity(i); nim.setText(""); nama.setText(""); prodi.setText(""); } } catch (Exception e) { nim.setText(e.toString()); } } } Sekarang kita masuk ke AndroidManifest.xml Tambahkan <uses-permission android:name="android.permission.INTERNET" > <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.crud" android:versionCode="1" android:versionName="1.0" > <uses-sdk
  • 9. Mata kuliah : Mobile Technologies (3sks) Dosen Pengampu : Tri Sugihartono, M.Kom Materi : Simpan Data ke Database Website : www.atmaluhur.ac.id android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >