2014-10-27 25 views
0

我目前正在創建一個Android Application,該鏈接到 Hosting24.com上的一個PHPMyAdminMYSQL數據庫,該活動旨在允許用戶註冊以在將輸入到MYSQL的應用程序的EditText框中輸入詳細信息數據庫。Android/JSON:Json響應是錯誤的?

,我嘗試運行給人一種Toast輸出代碼:

"Sorry, Username already chosen. Please choose another. " eventhough的datbase完全是空的。

這似乎是因爲JSON response是錯誤的,我的查詢是爲什麼這會是錯誤的?

這是否意味着PHP腳本中的Access details不正確?

的Android代碼:

public class SignUp extends Activity { 

    EditText UserName, Password; 
    Button btnSignUp; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_sign_up_screen); 

     UserName = (EditText) findViewById(R.id.euUserName); 
     Password = (EditText) findViewById(R.id.euPass); 
     Password.setTransformationMethod(PasswordTransformationMethod.getInstance()); 
     btnSignUp = (Button) findViewById(R.id.btnSingUp); 
     btnSignUp.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 

       // get The User name and Password to sign up with 
       String userName = UserName.getText().toString(); 
       String password = Password.getText().toString(); 

       // Url to login PHP script on server 
       String serverURL = "http://r999hosting.com/UserRegistrationService.php?username=" 
         + userName + "&password=" + password; 

       new LongOperation().execute(serverURL); 

      } 
     }); 

    } 

    /** 
    * Contains logic related to communication with PHP script over server 
    * 
    * @author 
    * 
    */ 
    private class LongOperation extends AsyncTask<String, Void, Void> { 

     private final HttpClient Client = new DefaultHttpClient(); 
     private String Content; 
     private String Error = null; 
     private ProgressDialog Dialog = new ProgressDialog(SignUp.this); 
     String data = ""; 
     int sizeData = 0; 

     protected void onPreExecute() { 

      Dialog.setMessage("Please wait.. "); 
      Dialog.show(); 

     } 

     // Call after onPreExecute method 
     protected Void doInBackground(String... urls) { 

      // make POST call to web server 
      BufferedReader reader = null; 

      try { 

       // Define URL where to send data 
       URL url = new URL(urls[0]); 

       // Send POST data request 
       URLConnection conn = url.openConnection(); 
       conn.setDoOutput(true); 
       OutputStreamWriter wr = new OutputStreamWriter(
         conn.getOutputStream()); 
       wr.write(data); 
       wr.flush(); 

       // Get the server response 
       reader = new BufferedReader(new InputStreamReader(
         conn.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 

       // Read Server Response 
       while ((line = reader.readLine()) != null) { 
        // Append server response in string 
        sb.append(line + ""); 
       } 

       // Append Server Response To Content String 
       Content = sb.toString(); 
      } catch (Exception ex) { 
       Error = ex.getMessage(); 
      } finally { 
       try { 

        reader.close(); 
       } 

       catch (Exception ex) { 
       } 
      } 

      return null; 
     } 

     protected void onPostExecute(Void unused) { 

      // Close progress dialog 
      Dialog.dismiss(); 

      if (Error != null) { 

      } else { 

       // Start Parse Response JSON Data 
       String OutputData = ""; 
       JSONObject jsonResponse; 

       try { 

        // Creates a new JSONObject with name/value mappings from 
        // the JSON string 
        jsonResponse = new JSONObject(Content); 

        String result = jsonResponse.get("result").toString(); 

        if (result.equals("true")) { 
         // inform user they have signed up successfully 
         Toast.makeText(SignUp.this, 
           "Congrats: Sign Up Successfull", 
           Toast.LENGTH_LONG).show(); 

         Intent i = new Intent(SignUp.this, 
           LoginHome.class); 
         startActivity(i); 
         // inform user of error signing up 
         Toast.makeText(getApplicationContext(), 
           "Congrats: Sign Up Successfull", 
           Toast.LENGTH_LONG).show(); 

        } else { 
         Toast.makeText(
           SignUp.this, 
           "Sorry, Username already chosen. Please choose another. ", 
           Toast.LENGTH_LONG).show(); 
        } 

       } 

       catch (JSONException e) { 

        e.printStackTrace(); 
       } 

      } 
     } 

    } 


} 

PHP腳本(注:未表現出真正的細節出於安全原因)

<?php 



if(isset($_GET['username']) && isset($_GET['password'])) 
{ 

$mysql_host = " "; 
$mysql_database = " "; 
$mysql_user = " "; 
$mysql_password = " "; 


// Provide host ip, mysql user name, password 
$con = mysql_connect($mysql_host,$mysql_user,$mysql_password); 

// Provide database name. 
mysql_select_db($mysql_database); 



    $username=$_GET['username']; 

    $password=$_GET['password']; 

    $flag="false"; 


    if(!empty($username) && !empty($password)) 
    { 

     $sql="Insert into `Login` (`UserName`,`Password`) values ('$username','$password') "; 

     $result=mysql_query($sql); 

     if($result) 
     { 
      $count= mysql_affected_rows(); 
      if($count > 0) 
      { 
       $flag="true"; //result true 

      }    

     } 

        mysql_close($con); 
     echo json_encode(array("result"=>$flag)); 
    } 



} 

?> 
+0

數據庫是否存在?它有正確的模式嗎?很多事情可能會出錯。爲什麼不檢查mysql錯誤並將它返回結果呢? – 323go 2014-10-27 20:52:33

回答

0

你有userNamepassword硬編碼到URL,這對於GET是可以的,但對於POST不會;對於POST請求,您需要在請求正文中發送查詢參數。

將查詢字符串單獨傳遞給後臺任務,因此您可以使用它設置data字段。

// Url to login PHP script on server 
     String serverURL = "http://r999hosting.com/UserRegistrationService.php" 

     String query = "username=" + userName + "&password=" + password; 
     new LongOperation().execute(serverURL, query); 

可能要properly encode the query see this question

改變你的doInBackground設置本地data變量。

 protected Void doInBackground(String... urls) { 
      data = urls[1] 
      ...