안드로이드와 mysql을 php 통해 연결하기
7. 그럼 mysql은 구성 완료!!
php를 구성해보자
이제
1. 그냥 아래 코드 쓰면 테이블에 있는 내용을 싸그리 긁어온다.
<?php
$servername = "mysql 서버이름";
$username = "아이디";
$password = "비번";
$dbname = "테이블이 포함된 DB이름";
if( isset($_POST['userToken']) && $_POST['userToken']=="그냥 인증을 위한 토큰 사실 이 이프문은 필요가 없음" ) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content FROM tbl_notice";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - title: " . $row["title"]. " -content: " . $row["content"]. "<br>"; //id ,title, content라는 내용을 모조리 긁어온다.
}
} else {
echo "0 results";
}
$conn->close();
}
?>
이제는 안드로이드 클래스 두개를 일단 추가해준다.
PostResponseAsncTask.java
/**
* Created by Juan on 16. 3. 10..
*/
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class PostResponseAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private AsyncResponse delegate;
private Context context;
private HashMap<String, String> postData =
new HashMap<String, String>();
private String loadingMessage = "Loading...";
//Constructor
public PostResponseAsyncTask(AsyncResponse delegate){
this.delegate = delegate;
this.context = (Context)delegate;
}
public PostResponseAsyncTask(AsyncResponse delegate,
HashMap<String, String> postData){
this.delegate = delegate;
this.context = (Context)delegate;
this.postData = postData;
}
public PostResponseAsyncTask(AsyncResponse delegate, String loadingMessage){
this.delegate = delegate;
this.context = (Context)delegate;
this.loadingMessage = loadingMessage;
}
public PostResponseAsyncTask(AsyncResponse delegate,
HashMap<String, String> postData, String loadingMessage){
this.delegate = delegate;
this.context = (Context)delegate;
this.postData = postData;
this.loadingMessage = loadingMessage;
}
//End Constructor
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(loadingMessage);
progressDialog.show();
super.onPreExecute();
}//onPreExecute
@Override
protected String doInBackground(String... urls){
String result = "";
for(int i = 0; i <= 0; i++){
result = invokePost(urls[i], postData);
}
return result;
}//doInBackground
private String invokePost(String requestURL, HashMap<String,
String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response+=line;
}
}
else {
response="";
Log.i("PostResponseAsyncTask", responseCode + "");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}//invokePost
private String getPostDataString(HashMap<String, String> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}//getPostDataString
@Override
protected void onPostExecute(String result) {
if(progressDialog.isShowing()){
progressDialog.dismiss();
}
result = result.trim();
delegate.processFinish(result);
}//onPostExecute
//Setter and Getter
public String getLoadingMessage() {
return loadingMessage;
}
public void setLoadingMessage(String loadingMessage) {
this.loadingMessage = loadingMessage;
}
public HashMap<String, String> getPostData() {
return postData;
}
public void setPostData(HashMap<String, String> postData) {
this.postData = postData;
}
public Context getContext() {
return context;
}
public AsyncResponse getDelegate() {
return delegate;
}
//End Setter & Getter
}
AsyncResponse.java
/*
* Created by Juan on 16. 3. 10..
*/
public interface AsyncResponse {
void processFinish(String output);
}
다음과 같이 써주면 바로 실행된다.
HashMap postData = new HashMap();
postData.put("userToken", "인증토큰");
PostResponseAsyncTask loginTask =
new PostResponseAsyncTask(NoticeActivity.this, postData);
loginTask.execute("주소");
그러면 결과는 여기에서 받게된다. 참고로 AsyncResponse를 implements를 하면 다음과 같은 함수가 만들어진다.
@Override
public void processFinish(String output) {
String temp=output.replaceAll("<br>", "\n");
LLog.d(TAG,"server result:"+temp);
textView.setText(temp);
}
여기까지 하면 끝!!