【发布时间】:2015-07-08 12:12:18
【问题描述】:
我是 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
我什至通过尝试连接到我的本地主机来测试它,但我得到了同样的错误。
【问题讨论】:
标签: php android post get httprequest