开发者

connecting android apps to mysql database

I have been trying out the tutorial shown on various websites on connecting a MySQL database using php to android. I dont know whats wrong with my code below. Can anyone tell me what i need to do.

This is my php code

 <?php
 mysql_connect("localhost","root","sugi");
 mysql_select_db("android");
 $q=mysql_query("SELECT * FROM people
 WHERE
 birthyear>'".$_REQUEST['year']."'");
 while($e=mysql_fetch_assoc($q))
             $output[]=$e;
       print(json_encode($output));
       mysql_close(); ?>

This is my sql query

CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`sex` BOOL NOT NULL DEFAULT '1',
`birthyear` INT NOT NULL 
)

This is my java code in android

public class main extends Activity {
    InputStream is;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String result = "";
        //the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1990"));

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://localhost/index.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("log_tag", "connection success ");
                Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
                Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();

        }
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
                }
                is.close();

                result=sb.toString();
        }catch(Exception e){
               Log.e("log_tag", "Error converting result "+e.toString());
            Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();

        }

        //parse json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                       JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_t开发者_运维知识库ag","id: "+json_data.getInt("id")+
                                ", name: "+json_data.getString("name")+
                                ", sex: "+json_data.getInt("sex")+
                                ", birthyear: "+json_data.getInt("birthyear")
                        );
                        Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
               }

        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
                Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
        }
    }
}

The program work fine. but i cant connect to http://localhost/index.php. The program display fail 3 times. Can help me see where i goes wrong?

Thank everyone for the help. Now i am able to connect to mysql. But i cant get the value of json data. The prog toast a msg 2 pass and 1 fail. Can anyone help me? The image below is when i type http://localhost/index.php in my IE. And line 6 is all this

$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");

I dont know where i goes wrong.

connecting android apps to mysql database


If your php script is deployed at localhost and you are deploying your android app on emulator then you should use this constructor: HttpPost httppost = new HttpPost("http://10.0.2.2/index.php");

See: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking


the problem is that you're trying to access something on localhost. Localhost will be your phone when the code is ran. If you use the emulator you can use the solution of Andrey.

Otherwise you have to know the ip address of your computer if you're using wifi on a local network. Or if you use 3G, Edge, GSM internet. You should input the ip of your computer.

You can go there: http://whatismyip.com

If you use a router or your isp is blocking the http port (80). You have to do a port redirect to something different. My guess is that you should test the url using your phone and the web browser.


HttpPost httppost = new HttpPost("http://localhost/index.php"); 

Change that to your localhost's ip address.

I am pretty new to android apps, but I know if you change your post to http://192.168.x.x (your localhost local ip address within your router) you should be able to view it just fine. I run a WAMP environment and before I would have problems accessing my development computer localhost from other computers within my network. All I did was make sure I put my WAMP server ONLINE. If you click on WAMP icon you will see "Put Online" or "Put Offline". Then I could view my websites on other laptops within my localnetwork via http://192.168.x.x/android/index.php just fine.


try http://127.0.0.1/index.php instead of localhost

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜