android与使用json的php mysql连接 [英] android with connection with php mysql using json

查看:64
本文介绍了android与使用json的php mysql连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在需要与php和mysql进行连接的android系统上创建了一个登录活动,并且它可以正常运行,但是现在我需要转换以获得JSON响应,但是我不知道如何将php和java中的代码更改为使我的应用程序适用于json

i have create a login activity on android system that need connection with php and mysql and it work perfectly but now i need to transform my to get JSON RESPONSE but i do not know how to change my code in php and in java to make my app be applicable to the json

如果有人可以帮助我,我将不胜感激 这是我的代码

if anyone can help me i will appreciate that this is my code

<?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);

    }
}

推荐答案

在php端,您必须使用函数json_encode()对返回的数据进行编码.在此处查看文档 http://es.php.net/json_encode

In the php side you have to use the function json_encode() to encode the data you return. Check the documentation here http://es.php.net/json_encode

示例:

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

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

In the Java/Android side with the response you have to use JSONObject, something like this:

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

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

Then when you have the data in JSONObject you can check the documentation to use it as you want. http://developer.android.com/reference/org/json/JSONObject.html

这篇关于android与使用json的php mysql连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆