Asyntack part 2
Kemaren saya sudah buat artikel tentang asyntack,yang dimana asyntack di gunakan untuk mengambil data dari server, dan kali saya akan membuat artikel tentan asyntack lagi, tapi berfungsi untuk menyimpan data / kirim data ke server, seperti biasa siapkan projectnya dulu, dan copas saja codenya :D
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50018
Source Host : localhost:3306
Source Database : surat_pos
Target Server Type : MYSQL
Target Server Version : 50018
File Encoding : 65001
Date: 2015-05-28 11:39:19
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `validasi`
-- ----------------------------
DROP TABLE IF EXISTS `validasi`;
CREATE TABLE `validasi` (
`id_surat` int(30) NOT NULL auto_increment,
`no_surat` int(30) NOT NULL,
`tgl_diterima` varchar(30) NOT NULL,
`nama_penerima` varchar(50) NOT NULL,
`status` varchar(50) NOT NULL,
`ket` varchar(50) NOT NULL,
PRIMARY KEY (`id_surat`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of validasi
-- ----------------------------
package com.example.demo_asyntack;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.widget.Toast;
public class Server_data
{
public void data(String no,String tgl,String nama,String status,String ket)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("no_surat", no));
postParameters.add(new BasicNameValuePair("tgl_diterima", tgl));
postParameters.add(new BasicNameValuePair("nama_penerima", nama));
postParameters.add(new BasicNameValuePair("status", status));
postParameters.add(new BasicNameValuePair("ket", ket));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/POS/validasi.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
if (res.equals("1"));
else
System.out.print("data ke simpan");
}catch (Exception e)
{
System.out.print(""+e.toString());
}
}
}
package com.example.demo_asyntack;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class Save_data extends Activity
{
EditText no,date,nama,stat,ket;
Button ok;
Server_data dat = new Server_data();
private int replyCode=200;
ListAdapter adapter;
private ProgressDialog pDialog;
static String in_judul = "judul";
static String in_waktu = "tanggal";
JSONArray Arjson = null;
public String konek;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_data);
no=(EditText)findViewById(R.id.no);
date=(EditText)findViewById(R.id.date);
nama=(EditText)findViewById(R.id.nama);
stat=(EditText)findViewById(R.id.stat);
ket=(EditText)findViewById(R.id.ket);
ok=(Button)findViewById(R.id.submit);
ok.setOnClickListener(oke);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#99CC00")));
ab.setDisplayHomeAsUpEnabled(true);
ab.show();
}
View.OnClickListener oke = new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
new push_data().execute();
}
};
private void goToMainActivity()
{
Intent in = new Intent(getApplicationContext(), MainActivity.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
}
void clear()
{
no. setText("");
date.setText("");
nama.setText("");
stat.setText("");
ket. setText("");
}
public void simpan()
{
String sno= no.getText().toString();
String sdate= date.getText().toString();
String snama= nama.getText().toString();
String sstat= stat.getText().toString();
String sket= ket.getText().toString();
dat.data(sno, sdate, snama, sstat, sket);
}
class push_data extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Save_data.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args)
{
simpan();
return null;
}
protected void onPostExecute(String res)
{
pDialog.dismiss();
clear();
if (res != null)
{
Toast.makeText(Save_data.this, res, Toast.LENGTH_LONG).show();
}
}
}
}
package com.example.demo_asyntack;
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
{
HttpClient httpClient;
HttpGet httpGet;
HttpResponse httpResponse;
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 9000000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
public CustomHttpClient()
{
httpClient=new DefaultHttpClient();
}
/**
* Get our single instance of our HttpClient object.
*
* @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();
}
}
}
}
/**
* 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();
}
}
}
}
public String get(String url) throws IOException{
httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
StringBuilder builder=new StringBuilder();
while ((line = rd.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
<ScrollView 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"
>
<AbsoluteLayout
android:id="@+id/AbsoluteLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Update_surat" >
<EditText
android:id="@+id/no"
android:layout_width="282dp"
android:layout_height="wrap_content"
android:layout_x="12dp"
android:layout_y="36dp"
android:editable="false"
android:ems="10"
android:enabled="true"
android:hint="Ex : 001"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="19dp"
android:layout_y="166dp"
android:text="Nama Penerima"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/nama"
android:layout_width="282dp"
android:layout_height="wrap_content"
android:layout_x="15dp"
android:layout_y="188dp"
android:editable="false"
android:ems="10"
android:hint="Ex : Matt"
android:inputType="textPersonName" />
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="14dp"
android:layout_y="92dp"
android:text="Tanggal"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="12dp"
android:layout_y="10dp"
android:text="No Surat"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="15dp"
android:layout_y="234dp"
android:text="Status"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/stat"
android:layout_width="282dp"
android:layout_height="wrap_content"
android:layout_x="14dp"
android:layout_y="262dp"
android:editable="false"
android:ems="10"
android:hint="Ex : Delay"
android:inputType="textPersonName" />
<EditText
android:id="@+id/ket"
android:layout_width="282dp"
android:layout_height="wrap_content"
android:layout_x="13dp"
android:layout_y="338dp"
android:editable="false"
android:ems="10"
android:hint="Ex : belum bayar"
android:inputType="textPersonName" />
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="19dp"
android:layout_y="305dp"
android:text="Keterangan"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/submit"
android:layout_width="232dp"
android:layout_height="49dp"
android:layout_x="44dp"
android:layout_y="392dp"
android:background="@drawable/konten"
android:text="Submit"
android:textColor="#ffffff"
android:textSize="20sp" />
<EditText
android:id="@+id/date"
android:layout_width="282dp"
android:layout_height="wrap_content"
android:layout_x="16dp"
android:layout_y="118dp"
android:editable="false"
android:ems="10"
android:hint="Ex : 01-02-2015"
android:inputType="textPersonName" />
</AbsoluteLayout>
</ScrollView>
Komentar
Posting Komentar