2014-03-05 35 views
0

我已經在android系統上創建了一個需要連接php和mysql的登錄活動,它完美的工作,但現在我需要轉換我的JSON響應,但我不知道如何改變我在PHP和Java代碼,使我的應用程序適用於JSONandroid與php的連接使用json的mysql mysql

如果有人能幫助我,我會理解, 這是我的代碼

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

    } 
} 

回答

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"))

ü可能需要添加缺少的進口,以及。

希望這會有所幫助。

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