Android สอบถามเรื่องการส่งข้อมูลเข้าฐานข้อมูลทำไมมันไม่เป็นภาษาไทยคับ
สอบถามหน่อยคับ
(ส่วนของ Android)
Code (Android-Java)
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class BackgroundTask_2 extends AppCompatActivity {
Context context;
String name1, tel1, subject1, message1;
public BackgroundTask_2(Context context,String name, String tel, String subject, String message) {
this.context = context;
this.name1 = name;
this.tel1 = tel;
this.subject1 = subject;
this.message1 = message;
}
public void get_Data() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
OkHttpClient okHttpClient = new OkHttpClient();
String name = convertToUTF8(name1);
String tel = convertToUTF8(tel1);
String subject = convertToUTF8(subject1);
String message = convertToUTF8(message1);
Request.Builder builder = new Request.Builder();
Request request = builder.url("http://192.168.178.1/webapp/addDATA.php?user="
+name+"&tel="+tel+"&subject="+subject+"&message="+message).build();
try {
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
return "Not Success - code : " + response.code();
}
} catch (IOException e) {
e.printStackTrace();
return "Error - " + e.getMessage();
}
}
@Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
// Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
}
}.execute();
}
public static String convertToUTF8(String s) {
String out = null;
try {
out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (java.io.UnsupportedEncodingException e) {
return null;
}
return out;
}
}
Tag : PHP, MySQL, Android, JAVA
Date :
2016-01-29 16:53:32
By :
Spike
View :
880
Reply :
4
(ส่วน PHP)
Code (PHP)
<?php
header("content-type:text/javascript;charset=utf-8");
$con=mysql_connect('localhost','root','1234')or die(mysql_error());
mysql_select_db('webappdb')or die(mysql_error());
mysql_query("SET NAMES UTF8");
$name = $_POST['user'];
$tel = $_POST['tel'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$sql = "INSERT INTO user (name, tel, subject, message) values('$name','$tel','$subject','$message')";
$res=mysql_query($sql);
$arr = array('id' => mysql_insert_id()."");
print('['.json_encode($arr).']');
mysql_close();
?>
Date :
2016-01-29 16:54:09
By :
Spike
น่าจะใช้แบบ PostString นะครับ
Code (Android-Java)
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Date :
2016-01-29 21:20:22
By :
mr.win
ยังไงคับ คือไม่ค่อยเข้าใจอะคับ
Date :
2016-01-30 00:22:00
By :
Spike
อันนี้หน้า MainActivity
อันที่ส่งไปครั้งเป็นหน้า BackgroundTask_2 คับ
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity6 extends Activity {
private Button home;
EditText ET_NAME,ET_TEL,ET_SUBJECT,ET_MESSAGE;
String name,tel,subject,message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main6);
home = (Button)findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
ET_NAME = (EditText)findViewById(R.id.name);
ET_TEL = (EditText)findViewById(R.id.tel);
ET_SUBJECT = (EditText)findViewById(R.id.subject);
ET_MESSAGE = (EditText)findViewById(R.id.message);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
tel = ET_TEL.getText().toString();
subject = ET_SUBJECT.getText().toString();
message = ET_MESSAGE.getText().toString();
String method = "register";
//BackgroundTask backgroundTask = new BackgroundTask(this);
//backgroundTask.execute(method,name,tel,subject,message);
//เธญเธฑเธเธเธตเน เน€เธเธดเนเธกเธเนเธญเธกเธนเธฅเธฅเธเนเธ”เนเนเธฅเนเธง เนเธ•เนเธขเธฑเธเนเธกเนเนเธ”เนเธ เธฒเธฉเธฒเนเธ—เธข เน€เธ”เธตเนเธขเธงเธเธกเน€เธเธดเธ”เธญเธฑเธเธเธตเนเนเธซเนเนเธเนเธเนเธญเธ
BackgroundTask_2 backgroundTask_2 = new BackgroundTask_2(this,name,tel,subject,message);
backgroundTask_2.get_Data();
//int a = insertUser(name,tel,subject,message);
Toast.makeText(getApplicationContext(), name+"\n"+tel+"\n"+subject+"\n"+message+"\n", Toast.LENGTH_SHORT).show();
finish();
}
public static int insertUser(final String name, final String tel, final String subject, final String message){ //------------ Method to insert data ---------------//
final InputStream[] is = {};
String js_result = "";
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
// Define Data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user",name));
nameValuePairs.add(new BasicNameValuePair("tel",tel));
nameValuePairs.add(new BasicNameValuePair("subject",subject));
nameValuePairs.add(new BasicNameValuePair("message",message));
// Connect Server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.178.1/webapp/register2.php"); // https://10.0.2.2/
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is[0] = entity.getContent();
} catch (Exception e) {
Log.d("log_err", "Error in http connection " + e.toString());
}
}
});
thread.start();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is[0],"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is[0].close();
js_result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
return -1;
}
int id = -1;
try {
final JSONArray jArray = new JSONArray(js_result);
for (int i = 0; i < jArray.length(); i++) {
String[] comment = new String[3];
JSONObject jo = jArray.getJSONObject(i);
id = Integer.parseInt((jo.get("id").toString()));
//tv_res.append(hn+","+name+","+age+","+date_serv+"\n");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
return -1;
}
return id;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity6, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Date :
2016-01-30 00:31:23
By :
Spike
Load balance : Server 05