简体   繁体   中英

Unable to connect android app with mysql DB using php

The following is my code which connects android app with MySQL DB. When I run this in my android mobile it just displays a plain screen. There is no error in my logcat. When i run it in brower using "192.168.1.11/city.php" I am getting the city's extracted from DB. But the same is not working when I run it in my android device. Please help

Android class :

 public class City extends ListActivity {

     JSONArray jArray;
     String result = null;
     InputStream is = null;
     StringBuilder sb=null;

     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     //http post
     try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.11/city.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        }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();
    }catch(Exception e){
          Log.e("log_tag", "Error converting result "+e.toString());
    }
   //paring data
   int ct_id;
   String ct_name;
   try{
  jArray = new JSONArray(result);
  JSONObject json_data=null;
  for(int i=0;i<jArray.length();i++){
         json_data = jArray.getJSONObject(i);
         ct_id=json_data.getInt("CITY_ID");
         ct_name=json_data.getString("CITY_NAME");
     }
  }
  catch(JSONException e1){
      Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
  } catch (ParseException e1) {
        e1.printStackTrace();
}
   }
    }
}

activity_city.xml code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".City" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

Php Code :

 <?php
 ob_start();
 $host="localhost"; // Host name 
 $username=""; // Mysql username 
 $password=""; // Mysql password 
 $db_name="test"; // Database name 
 $tbl_name="CITY"; // Table name 
 mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
 mysql_select_db("$db_name")or die("cannot select DB");
 $sql=mysql_query("select * from CITY");
 while($row=mysql_fetch_assoc($sql))
{
$output[]=$row;
print(json_encode($output));
}
mysql_close();
?>

Included INTERNET permission in my Android Manifest file.

I dont know where I am going wrong. Please help.

Make sure you have your phone in same network as server.

Try moving

print(json_encode($output));

out of the loop

your PHP code need to be change.. So i have change it and put it back..

<?php
     ob_start();
     $host="localhost"; // Host name              Changed
     $username="root"; // Mysql username          Changed
     $password=""; // Mysql password 
     $db_name="test"; // Database name 

     $tbl_name="CITY"; // Table name 
     mysql_connect($host, $username, $password)or die("cannot connect");          //Changed
     mysql_select_db($db_name)or die("cannot select DB");           //Changed
     $sql=mysql_query("select * from CITY");
     while($row=mysql_fetch_assoc($sql))
     {
          $output[]=$row;
          print(json_encode($output));
     }
     mysql_close();
?>

Where is the PHP files located. In a local machine , or on a web server.

If the PHP files are located in local machine, you can't access it from the android application.

Also verify that you have given internet permission for the android application.

Don't use localhost when you want to test your application on your phone. Your phone can't access the PHP files on localhost.

Might I suggest hosting your PHP and SQL files online and resume testing.

1) Are you sure ur localhost ip is " http://192.168.1.11 " ? try to put two / like this " http://192.168.1.11//city.php "

i have used this IP for my xampp " http://10.0.2.2//Mobile/login2.php " or try this as well 127.0.1.1 or 127.0.0.1

2) try this link . if you have done something wrong in java or php code than this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM