android使用json连接php mysql

时间:2014-03-05 09:56:33

标签: php android mysql json

我已经在Android系统上创建了一个需要与php和mysql连接的登录活动,并且它工作得很好但是现在我需要转换我的JSON RESPONSE,但我不知道如何在php和java中更改我的代码让我的应用程序适用于json

如果有人能帮助我,我会很感激  这是我的代码

check.php

<?php
$hostname_localhost ="localhost";
$database_localhost ="fil";
$username_localhost =********";
$password_localhost ="*******";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from members where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) { 
echo "No Such User Found"; 
}
else  {
echo "User Found"; 
}
?>

AndroidPHPConnectionDemo.java

public class AndroidPHPConnectionDemo extends Activity {
    Button b;
    EditText et,pass;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;


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

        b = (Button)findViewById(R.id.Button01);  
        et = (EditText)findViewById(R.id.username);
        pass= (EditText)findViewById(R.id.password);
        tv = (TextView)findViewById(R.id.tv);


        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            login();         
            }
        });
    }

    void login(){
        try{            

            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://10.0.2.2/check.php"); // make sure the url is correct.
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(2);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
            nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
            nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);
            // edited by James from coderzheaven.. from here....
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response); 
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText("Response from PHP : " + response);

                }
            });

            if(response.equalsIgnoreCase("User Found")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
                        TextView tv2 = (TextView)findViewById(R.id.tv2);
                        tv2.setText("hello");
                    }
                });

                startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
            }else{
                showAlert();                
            }

        }catch(Exception e){

            System.out.println("Exception : " + e.getMessage());
        }
    }




    public void showAlert(){
        AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
                builder.setTitle("Login Error.");
                builder.setMessage("User not Found.")  
                       .setCancelable(false)
                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                           }
                       });                     
                AlertDialog alert = builder.create();
                alert.show();               
            }
        });
    }
}

UserPage.java

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;

public class UserPage extends Activity {

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

    }
}

2 个答案:

答案 0 :(得分:1)

在php方面,你必须使用函数json_encode()来编码你返回的数据。查看此处的文档http://es.php.net/json_encode

示例:

header('Content-type: application/json');
echo json_encode(array('response'=>'user_found'));

在带有响应的Java / Android端,您必须使用JSONObject,如下所示:

// Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(response);

然后,当您在JSONObject中拥有数据时,您可以检查文档以根据需要使用它。 http://developer.android.com/reference/org/json/JSONObject.html

答案 1 :(得分:0)

尝试使用代码中的此response=httpclient.execute(httppost);响应,将其序列化为JSON,如string responseTxt = EntityUtils.toString(response.getEntity()); JSONObject json= new JSONObject(responseTxt);

这将使您获得对象json的响应。

将if()语句if(response.equalsIgnoreCase("User Found"))更改为if (json.has("User Found") )

U可能还需要添加缺失的导入。

希望这有帮助。