Android 应用程序在 Http 请求连接到在线数据库时崩溃
Android application crashes on Http Request to connect to online database
我是 android 的新手,我需要将我的应用程序连接到在线数据库。我创建了数据库和 php 连接文件。我还创建了一个测试 index.php 文件来测试连接:
index.php
<?php
include_once 'connection.php';
echo 'hi';
?>
我也用search.php获取数据:
<?php
mysql_connect("localhost","****","*****");
mysql_select_db("*****");
$sql=mysql_query("select * from user where username like 'a%'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>
这是search.php的输出:
[{"id":"2","username":"adla","password":"123","type":null,"customer_id":null,"employee_id":null}]
我可以从应用程序外部连接到数据库,所以错误可能出在我的代码中。
我尝试了 2 个教程中的两种方法:
http://www.helloandroid.com/tutorials/connecting-mysql-database(使用Post方法)
public void connectNow(View view)
{
String result = null;
InputStream is = null;
StringBuilder sb =null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://akmiengineering.com/insurance-app/search.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Toast.makeText(getApplicationContext(),"Connection successful!! This is return:" +is , Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection" + e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Toast.makeText(getApplicationContext(),"Connection successful!! This is result:" +result , Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
String fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++) {
json_data = jArray.getJSONObject(i);
fd_id = json_data.getString("username");
fd_name = json_data.getString("password");
Toast.makeText(getApplicationContext(), "I'm here!! This is name:" + fd_id + " and this is pass: " + fd_name, Toast.LENGTH_LONG).show();
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Data Found", Toast.LENGTH_LONG).show();
}
}
我尝试在 bluestacks 上调试应用程序,因为我没有 android,所以我只是依靠断点来检测错误。当代码到达这里时,应用程序似乎崩溃了:
HttpResponse response = httpclient.execute(httppost);
http://hmkcode.com/android-internet-connection-using-http-get-httpclient/(使用 GET)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_test);
EditText etResponse;
TextView tvIsConnected;
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// show response on the EditText etResponse
etResponse.setText(GET("http://akmiengineering.com/insurance-app/index.php"));
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
// convert inputstream to String
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
// check network connection
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
此外,此代码会导致应用程序此时崩溃:
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
这两种方法都是同样的问题,但我不知道是什么原因造成的,也不知道如何解决。我试图检测来自 logcat 的错误,但我无法理解它:
07-08 15:08:06.631 2750-2750/com.bluestacks.gamepophome E/bluestacksHome﹕ Hidden apps list thru binder[com.zqgame.fr.en.androidgp, com.igg.bzbee.slotsdeluxe, com.igg.clashoflords2, com.igg.pokerdeluxe, air.com.sublinet.tastytale]
07-08 15:08:06.641 2750-2750/com.bluestacks.gamepophome E/bluestacksHome﹕ Hidden list size 5
07-08 15:08:06.731 2661-2673/com.android.inputmethod.latin W/Binder﹕ Caught a RuntimeException from the binder stub implementation.
java.lang.NullPointerException
at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280)
at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
07-08 15:08:06.731 2533-29585/system_process W/InputMethodManagerService﹕ Got RemoteException sending setActive(false) notification to pid 7192 uid 10066
我什至通过尝试连接到我的本地主机来测试它,但我遇到了同样的错误。
您是否在清单文件中声明了 Internet 许可。
我认为您可能面临 android 线程问题。通常像 GET 方法这样的方法应该在另一个扩展 AsyncTask 的 class 中,这将 运行 你的代码在主线程以外的不同线程中。
如果您不想使用 AsyncTask 并想强制您的代码 运行 都在同一个线程中,您应该在 onCreate 方法中有这样的东西:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
我是 android 的新手,我需要将我的应用程序连接到在线数据库。我创建了数据库和 php 连接文件。我还创建了一个测试 index.php 文件来测试连接:
index.php
<?php
include_once 'connection.php';
echo 'hi';
?>
我也用search.php获取数据:
<?php
mysql_connect("localhost","****","*****");
mysql_select_db("*****");
$sql=mysql_query("select * from user where username like 'a%'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>
这是search.php的输出:
[{"id":"2","username":"adla","password":"123","type":null,"customer_id":null,"employee_id":null}]
我可以从应用程序外部连接到数据库,所以错误可能出在我的代码中。
我尝试了 2 个教程中的两种方法:
http://www.helloandroid.com/tutorials/connecting-mysql-database(使用Post方法)
public void connectNow(View view) { String result = null; InputStream is = null; StringBuilder sb =null; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://akmiengineering.com/insurance-app/search.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Toast.makeText(getApplicationContext(),"Connection successful!! This is return:" +is , Toast.LENGTH_LONG).show(); }catch(Exception e){ Log.e("log_tag", "Error in http connection" + e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); Toast.makeText(getApplicationContext(),"Connection successful!! This is result:" +result , Toast.LENGTH_LONG).show(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data String fd_id; String fd_name; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++) { json_data = jArray.getJSONObject(i); fd_id = json_data.getString("username"); fd_name = json_data.getString("password"); Toast.makeText(getApplicationContext(), "I'm here!! This is name:" + fd_id + " and this is pass: " + fd_name, Toast.LENGTH_LONG).show(); } }catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Data Found", Toast.LENGTH_LONG).show(); } }
我尝试在 bluestacks 上调试应用程序,因为我没有 android,所以我只是依靠断点来检测错误。当代码到达这里时,应用程序似乎崩溃了:
HttpResponse response = httpclient.execute(httppost);
http://hmkcode.com/android-internet-connection-using-http-get-httpclient/(使用 GET)
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_http_test); EditText etResponse; TextView tvIsConnected; // get reference to the views etResponse = (EditText) findViewById(R.id.etResponse); tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); // check if you are connected or not if(isConnected()){ tvIsConnected.setBackgroundColor(0xFF00CC00); tvIsConnected.setText("You are conncted"); } else{ tvIsConnected.setText("You are NOT conncted"); } // show response on the EditText etResponse etResponse.setText(GET("http://akmiengineering.com/insurance-app/index.php")); } public static String GET(String url){ InputStream inputStream = null; String result = ""; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } return result; } // convert inputstream to String private static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } // check network connection public boolean isConnected(){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; }
此外,此代码会导致应用程序此时崩溃:
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
这两种方法都是同样的问题,但我不知道是什么原因造成的,也不知道如何解决。我试图检测来自 logcat 的错误,但我无法理解它:
07-08 15:08:06.631 2750-2750/com.bluestacks.gamepophome E/bluestacksHome﹕ Hidden apps list thru binder[com.zqgame.fr.en.androidgp, com.igg.bzbee.slotsdeluxe, com.igg.clashoflords2, com.igg.pokerdeluxe, air.com.sublinet.tastytale]
07-08 15:08:06.641 2750-2750/com.bluestacks.gamepophome E/bluestacksHome﹕ Hidden list size 5
07-08 15:08:06.731 2661-2673/com.android.inputmethod.latin W/Binder﹕ Caught a RuntimeException from the binder stub implementation.
java.lang.NullPointerException
at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(IInputMethodWrapper.java:280)
at com.android.internal.view.IInputMethod$Stub.onTransact(IInputMethod.java:129)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
07-08 15:08:06.731 2533-29585/system_process W/InputMethodManagerService﹕ Got RemoteException sending setActive(false) notification to pid 7192 uid 10066
我什至通过尝试连接到我的本地主机来测试它,但我遇到了同样的错误。
您是否在清单文件中声明了 Internet 许可。
我认为您可能面临 android 线程问题。通常像 GET 方法这样的方法应该在另一个扩展 AsyncTask 的 class 中,这将 运行 你的代码在主线程以外的不同线程中。
如果您不想使用 AsyncTask 并想强制您的代码 运行 都在同一个线程中,您应该在 onCreate 方法中有这样的东西:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}