[英]Android connecting on MySQL using PHP
我试图做我的第一个与MySQL上的连接的android应用程序,我谷歌很多,找到一些教程和类似的东西。 基于它们,我有以下代码:
package com.example.helloworld;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
final EditText e_name=(EditText) findViewById(R.id.editText2);
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
id = e_id.getText().toString();
name = e_name.getText().toString();
insert();
}
});
}
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/xampp/android_connect/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我看不到任何错误或任何东西,但是当我尝试加载它时,它说:“无效的IP地址”(这是catch {}的错误消息)。 我尝试研究哪里可能有问题,在LogCat中我发现此错误:
11-16 10:39:10.036: I/ActivityManager(150): Start proc com.example.helloworld for activity com.example.helloworld/.MainActivity: pid=612 uid=10045 gids={3003, 1028}
11-16 10:39:10.386: E/Trace(612): error opening trace file: No such file or directory (2)
11-16 10:39:10.966: D/gralloc_goldfish(612): Emulator without GPU emulation detected.
11-16 10:39:11.016: I/ActivityManager(150): Displayed com.example.helloworld/.MainActivity: +1s32ms
11-16 10:39:11.066: I/Choreographer(150): Skipped 34 frames! The application may be doing too much work on its main thread.
11-16 10:39:18.945: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:18.975: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:18.975: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:19.195: D/dalvikvm(612): GC_CONCURRENT freed 191K, 4% free 6229K/6471K, paused 17ms+65ms, total 206ms
11-16 10:39:20.065: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.075: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.075: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.645: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.055: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.065: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.065: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.535: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.545: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.545: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.728: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.735: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.735: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.925: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:22.535: I/Choreographer(612): Skipped 37 frames! The application may be doing too much work on its main thread.
: E/(): Device disconnected: 1
: E/(): Device disconnected
尤其是我看找不到目录,我尝试在浏览器中打开相同的地址,并且我没有问题地打开它。 有人可以告诉我我在做什么错吗?
谢谢
localhost
指向设备本身; 因此,您可以尝试以下操作:
如果出于测试目的在自己的网络上运行此程序,请尝试键入本地ip而不是localhost
, 例如 http://192.168.0.123
尝试使用http://10.0.2.2
而不是localhost
,在设备上的浏览器中键入它,然后查看其是否正确连接。
还要检查这个问题 。
NetworkOnMainThreadException
您正在尝试在应用程序的主线程上进行网络操作,这可能会导致严重的延迟和不可预测的结果 。
您应该始终使用AsyncTask
进行网络操作。 请参阅android docs中的这篇文章 。
这是一个示例用法;
您的AsyncTask
应该如下所示:
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Initialize your parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
nameValuePairs.add(new BasicNameValuePair("name",urls[2]));
// Make your HTTP Request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// Return the response.
return result;
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute gets the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// Read your response into a JSONObject and do stuff...
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
}
}
}
您可以像这样使用它:
// Params : url, id, name
new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", "12345", "Foo Bar");
这是一个完整的示例,您的代码应如下所示:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
final EditText e_name=(EditText) findViewById(R.id.editText2);
Button insert=(Button) findViewById(R.id.button1);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
id = e_id.getText().toString();
name = e_name.getText().toString();
insert();
}
});
}
public void insert()
{
new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", id, name);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Initialize your parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
nameValuePairs.add(new BasicNameValuePair("name",urls[2]));
// Make your HTTP Request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
// Return the response.
return result;
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute gets the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// Read your response into a JSONObject and do stuff...
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
}
}
}
}
我认为您有两个问题:
localhost
更改为计算机的IP地址 。 AsyncTask
或使用像Retrofit这样的库! ;) 你做错了。 尝试10.0.2.2/android_connect/index.php。 10.0.2.2重定向到您的xampp / htdoc /文件夹。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.