php - Android application crashes on Http Request to connect to online database
I'm new to android and I need to connect my application to an online database. I created the database and the php connection files. I also created a test index.php file just to test the connection:
index.php
<?php
include_once 'connection.php';
echo 'hi';
?>
I also used search.php to get data:
<?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();
?>
This is the output of search.php:
[{"id":"2","username":"adla","password":"123","type":null,"customer_id":null,"employee_id":null}]
I'm able to connect to the database from outside the application, so maybe the error is in my code.
I tried two methods from 2 tutorials:
http://www.helloandroid.com/tutorials/connecting-mysql-database (Using Post Method)
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(); } }
I tried debugging the app on bluestacks as I don't have an android, so I just depended on the breakpoints to detect the error. It looks like the app is crashing when the code reaches this:
HttpResponse response = httpclient.execute(httppost);
http://hmkcode.com/android-internet-connection-using-http-get-httpclient/ (Using 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; }
Also, this code causes the application to crash at this point:
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
It's the same problem for both methods, but I don't know what is causing this and how to fix it. I tried to detect the error from the logcat, but I'm unable to understand it:
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
I even tested it by trying to connect to my local host, but I got the same error.
Answer
Solution:
I think you might be facing a android threading problem. Usually methods like your GET method should be inside another class that extends AsyncTask, which would run your code in a different thread other than the main one.
If you don't want to use AsyncTask and want to force your code to run all in the same thread, you should have something like this inside onCreate method:
Answer
Solution:
Have you declared Internet permission in manifest file .