我正在尝试使用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
Especialy我看看找不到目录,我尝试在我的borowser中打开相同的地址,我打开它没有问题。有人能告诉我我做错了什么吗?
由于
答案 0 :(得分:2)
localhost
指向设备本身;所以你可以尝试以下方法:
如果您是在自己的网络上运行此测试,请尝试键入您的本地IP 而不是localhost
,例如 http://192.168.0.123
请尝试使用http://10.0.2.2
代替localhost
,在设备上的浏览器中输入,然后查看它是否正常连接。
同时查看this question。
NetworkOnMainThreadException
您尝试在应用程序的主线程上进行网络操作,这可能会导致严重延迟和无法预测的结果 。
您应始终使用AsyncTask
进行网络操作。请参阅android docs中的this article。
以下是一个示例用法;
您的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();
}
}
}
}
答案 1 :(得分:1)
我认为你有两个问题:
localhost
更改为您机器的IP地址。AsyncTask
代替或使用像Retrofit这样的库! ;)答案 2 :(得分:0)
你做错了。试试10.0.2.2/android_connect/index.php。 10.0.2.2重定向到xampp / htdoc /文件夹。