我是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(使用发布方法)
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();
}
}
我没有在Android上尝试在bluestacks上调试该应用程序,因此我仅依靠断点来检测错误。代码到达以下位置时,应用似乎崩溃了:
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
我什至尝试连接到我的本地主机进行了测试,但是出现了同样的错误。
最佳答案
我认为您可能会遇到android线程问题。通常,诸如GET方法之类的方法应位于扩展AsyncTask的另一个类内,该类将在不同于主线程的其他线程中运行您的代码。
如果您不想使用AsyncTask并希望强制您的代码在同一线程中全部运行,则onCreate方法内部应具有以下内容:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
关于php - Android应用程序因连接到在线数据库的Http请求而崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31292305/