簡體   English   中英

android與使用json的php mysql連接

[英]android with connection with php mysql using json

我已經在需要與php和mysql進行連接的android系統上創建了一個登錄活動,並且它工作正常,但是現在我需要轉換我的以獲得JSON響應,但是我不知道如何更改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);

    }
}

在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

嘗試使用此響應response=httpclient.execute(httppost); 從您的代碼中,將其序列化為JSON,就像這樣的string responseTxt = EntityUtils.toString(response.getEntity()); JSONObject json= new JSONObject(responseTxt); string responseTxt = EntityUtils.toString(response.getEntity()); JSONObject json= new JSONObject(responseTxt);

這將使您獲得對對象json的響應。

將您的if()語句if(response.equalsIgnoreCase("User Found"))更改為if (json.has("User Found") )

您可能還需要添加缺失的進口商品。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM