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:


include_once 'connection.php';
echo 'hi';

I also used search.php to get data:


      $sql=mysql_query("select * from user where username like 'a%'");
      while($row=mysql_fetch_assoc($sql)) $output[]=$row;


This is the output of search.php:


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:

  1. (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
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("");
            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
            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");
            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;
            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);
  1. (Using GET)

        protected void onCreate(Bundle savedInstanceState) {
        EditText etResponse;
        TextView tvIsConnected;
            // get reference to the views
            etResponse = (EditText) findViewById(;
            tvIsConnected = (TextView) findViewById(;
            // check if you are connected or not
                tvIsConnected.setText("You are conncted");
                tvIsConnected.setText("You are NOT conncted");
            // show response on the EditText etResponse
    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);
                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;
        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;
            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.igg.bzbee.slotsdeluxe, com.igg.clashoflords2, com.igg.pokerdeluxe,]
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/ W/Binder﹕ Caught a RuntimeException from the binder stub implementation.
            at android.inputmethodservice.IInputMethodWrapper.setSessionEnabled(
            at android.os.Binder.execTransact(
            at 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.




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:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();



Have you declared Internet permission in manifest file .

People are also looking for solutions to the problem: php - Error Android java.lang.NullPointerException: lock == null


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.