2012-03-05 145 views
2

我想創建一個簡單的android應用程序,它使用php連接mysql。我嘗試登錄this site登錄教程。請幫忙。Android的mysql連接問題

我的代碼是:

  • LoginScreen

package com.project.test; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.R.integer; 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class TestingInstanceExpenseActivity extends Activity { 
    /** Called when the activity is first created. */ 

    private Button login; 
    private Button newUser; 
    private EditText username; 
    private EditText password; 

    // JSON Response node names 
    private static String KEY_SUCCESS = "success"; 
    private static String KEY_ERROR = "error"; 
    private static String KEY_ERROR_MSG = "error_msg"; 
    UserFunctions userFunctions = new UserFunctions(); 

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

     // Importing all assets like buttons, text fields 
     login = (Button)findViewById(R.id.bt_login); 
     username = (EditText)findViewById(R.id.username); 
     password = (EditText)findViewById(R.id.password); 
     newUser = (Button)findViewById(R.id.bt_newuser); 

     // Login button Click Event 
     login.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       String uname = username.getText().toString(); 
       String pass = password.getText().toString(); 

       Log.d("Button", "Login"); 
       JSONObject jsonObject = userFunctions.loginUser(uname, pass); 
       Log.i("loginuser","called login user function"); 
       /*try { 
        JSONArray x = jsonObject.getJSONArray("success"); 
       } catch (JSONException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       }*/ 
       try { 
        if(!(jsonObject.getString(KEY_SUCCESS).equals(null))) { 
         String res = jsonObject.getString(KEY_SUCCESS); 
         if(Integer.parseInt(res) == 1) { 
          Toast.makeText(getApplicationContext(), "Valid Credential", Toast.LENGTH_LONG).show(); 
         } else { 
          Toast.makeText(getApplicationContext(), "Invalid Credential", Toast.LENGTH_LONG).show();    
         } 
        } 
       } catch (JSONException e){ 
        e.printStackTrace(); 
       } 
      } 
     }); 

     newUser.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       Intent intent = new Intent(getApplicationContext(), Createuser.class); 
       startActivity(intent); 
      } 
     }); 
    } 
} 
  • UserFunctions

package com.project.test; 

import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONObject; 

import android.content.Context; 
import android.util.Log; 

public class UserFunctions { 

private JSONParser jsonParser; 

    private static String URL = "http://10.0.2.2/instance_expense_calculator/"; 

    private static String login_tag = "login"; 
    private static String register_tag = "register"; 

    // constructor 
    public UserFunctions(){ 
     jsonParser = new JSONParser(); 
    } 

    public JSONObject loginUser(String username, String password){ 
     // Building Parameters 
     Log.i("JSON Parser class", "json class method invoked"); 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", login_tag)); 
     params.add(new BasicNameValuePair("username", username)); 
     params.add(new BasicNameValuePair("password", password)); 
     JSONObject json = jsonParser.getJSONFromUrl(URL, params); 
     // return json 
     return json; 
    } 

    /** 
    * function make Login Request 
    * @param name 
    * @param email 
    * @param password 
    * */ 
    public JSONObject registerUser(String firstname, String lastname, String username, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", register_tag)); 
     params.add(new BasicNameValuePair("firstname", firstname)); 
     params.add(new BasicNameValuePair("lastname", lastname)); 
     params.add(new BasicNameValuePair("username", username)); 
     params.add(new BasicNameValuePair("password", password)); 

     // getting JSON Object 
     JSONObject json = jsonParser.getJSONFromUrl(URL, params); 
     // return json 
     return json; 
    } 

} 
  • JSONParser

package com.project.test; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
      Log.e("JSON", json); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     try { 
      JSONArray jsonArray = new JSONArray(json); 
      for(int i=0;i<jsonArray.length();i++) { 
       jObj = jsonArray.getJSONObject(i); 
       Log.i("testing", jObj.getString("tag")); 
       Log.i("testing", jObj.getString("success")); 
       Log.i("testing", jObj.getString("error")); 
      } 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     // return JSON String 
     return jObj; 

    } 
} 

我的PHP文件是:

  • 的index.php

<?php 
if(isset($_POST['tag'])){ 
    //get tag 
    $tag = $_POST['tag']; 
    //include db handler 
    require_once 'DB_Functions.php'; 
    $db = new DB_Functions(); 
    //response Array 
    $response = array('tag' => $tag, 'success' => 0, 'error' => 0); 
    //check for tag type 
    if($tag == 'login') { 
     //request type is check login 
     $username = $_POST['username']; 
     $password = $_POST['password']; 
     //check for user 
     $user = $db->getUserByEmailAndPassword($username, $password); 

     if($user) { 
      //user found 
      //echo json with success = 1 
      $response['success'] = 1; 
      echo json_encode($response); 
     } else { 
      //user not found 
      //echo jason with error = 1 
      $response['error'] = 1; 
      $response['error_msg'] = "Incorrect email or password!"; 
      echo json_encode($response); 
     } 
    } else if ($tag == 'register') { 
     //request type is register new user 
     $name = $_POST['first_name']; 
     $name = $_POST['lasst_name']; 
     $username = $_POST['username']; 
     $password = $_POST['password']; 
     //check if user already exists 

     if($db-> isUserExisted($username)){ 
      //user exist - error responbse 
      $response['error'] = 2; 
      $response['error_msg'] = "User already existed"; 
      echo json_encode($response); 

     } else { 
      //store user information 
      $user = $db->storeUser($first_name, $last_name, $username, $password); 

      if($user) { 
       //stored successfully 
       $response['success'] = 1; 
       echo json_encode($response); 
      } else { 
       //user failed to store 
       $response['error'] = 1; 
       $response['error_msg'] = "Error occured while Registring the user"; 
       echo json_encode($response); 
      } 
     } 
    } else { 
     echo "Invalid Request"; 
    } 
} else { 
    echo "Access Denied"; 
} 
?> 
  • DB_Functions.php

<?php 
    class DB_Functions { 
     private $db; 
     //put code here 
     //constructor 
     function construct() { 
     require_once 'DB_Connect.php'; 
     //connecting to database 
     $this ->db = new DB_Connect(); 
     $this ->db->connect(); 
    } 
    //destructor 
    /** 
    *storing new user 
    *returns user details 
    */ 
    public function storeUser($username, $first_name, $last_name, $password) { 
     mysql_query("Insert into user_registration values ('$username', '$first_name', '$last_name', '$password')"); 
    } 
    /** 
    *Get user by email and password 
    */ 
    public function getUserInformation($username, $password) { 
     $result = mysql_query("Select * from user_registration where username = '$username' and password = '$password'") or die(mysql_error()); 
     //check for result 
     $no_of_rows = mysql_num_rows($result); 
     if($no_of_rows > 0) { 
      return true; 
     } else { 
      // user not found 
      return false; 
     } 
    } 
    /** 
    *check user is existed or not 
    */ 
    public function isUserExisted($username) { 
     $result = mysql_query("Select username from users where username = '$username'"); 
     $no_of_rows = mysql_num_rows($result); 
     if($no_of_rows >0) { 
      //user existed 
      return true; 
     } else { 
      //user not existed 
      return false; 
     } 
    } 
    /** 
    *Encrypting password 
    *@param password 
    * returns salt and encrypted password 
    */ 
} 
?> 

  • DB_Connect.php

    • 的config.php

Mysql數據庫包含的字段名字,姓氏,用戶名和密碼錶user_registration。

錯誤接收:

03-05 16:39:00.589: D/Button(827): Login 
03-05 16:39:00.589: I/JSON Parser class(827): json class method invoked 
03-05 16:39:00.908: E/JSON(827): <br /> 
03-05 16:39:00.908: E/JSON(827): <font size='1'><table class='xdebug-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'> 
03-05 16:39:00.908: E/JSON(827): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>(!)</span> Fatal error: Call to undefined method DB_Functions::getUserByEmailAndPassword() in C:\wamp\www\instance_expense_calculator\index.php on line <i>16</i></th></tr> 
03-05 16:39:00.908: E/JSON(827): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr> 
03-05 16:39:00.908: E/JSON(827): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr> 
03-05 16:39:00.908: E/JSON(827): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0011</td><td bgcolor='#eeeeec' align='right'>377960</td><td bgcolor='#eeeeec'>{main}()</td><td title='C:\wamp\www\instance_expense_calculator\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>0</td></tr> 
03-05 16:39:00.908: E/JSON(827): </table></font> 
03-05 16:39:00.908: W/System.err(827): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray 
03-05 16:39:00.908: W/System.err(827): at org.json.JSON.typeMismatch(JSON.java:107) 
03-05 16:39:00.919: W/System.err(827): at org.json.JSONArray.<init>(JSONArray.java:91) 
03-05 16:39:00.919: W/System.err(827): at org.json.JSONArray.<init>(JSONArray.java:103) 
03-05 16:39:00.919: W/System.err(827): at com.project.test.JSONParser.getJSONFromUrl(JSONParser.java:70) 
03-05 16:39:00.919: W/System.err(827): at com.project.test.UserFunctions.loginUser(UserFunctions.java:34) 
03-05 16:39:00.919: W/System.err(827): at com.project.test.TestingInstanceExpenseActivity$1.onClick(TestingInstanceExpenseActivity.java:53) 
03-05 16:39:00.919: W/System.err(827): at android.view.View.performClick(View.java:2408) 
03-05 16:39:00.919: W/System.err(827): at android.view.View$PerformClick.run(View.java:8816) 
03-05 16:39:00.919: W/System.err(827): at android.os.Handler.handleCallback(Handler.java:587) 
03-05 16:39:00.929: W/System.err(827): at android.os.Handler.dispatchMessage(Handler.java:92) 
03-05 16:39:00.929: W/System.err(827): at android.os.Looper.loop(Looper.java:123) 
03-05 16:39:00.929: W/System.err(827): at android.app.ActivityThread.main(ActivityThread.java:4627) 
03-05 16:39:00.929: W/System.err(827): at java.lang.reflect.Method.invokeNative(Native Method) 
03-05 16:39:00.929: W/System.err(827): at java.lang.reflect.Method.invoke(Method.java:521) 
03-05 16:39:00.929: W/System.err(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
03-05 16:39:00.929: W/System.err(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
03-05 16:39:00.929: W/System.err(827): at dalvik.system.NativeStart.main(Native Method) 
03-05 16:39:00.929: I/loginuser(827): called login user function 
03-05 16:39:00.939: D/AndroidRuntime(827): Shutting down VM 
03-05 16:39:00.939: W/dalvikvm(827): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 
03-05 16:39:00.949: E/AndroidRuntime(827): FATAL EXCEPTION: main 
03-05 16:39:00.949: E/AndroidRuntime(827): java.lang.NullPointerException 
03-05 16:39:00.949: E/AndroidRuntime(827): at com.project.test.TestingInstanceExpenseActivity$1.onClick(TestingInstanceExpenseActivity.java:62) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.view.View.performClick(View.java:2408) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.view.View$PerformClick.run(View.java:8816) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.os.Handler.handleCallback(Handler.java:587) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.os.Handler.dispatchMessage(Handler.java:92) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.os.Looper.loop(Looper.java:123) 
03-05 16:39:00.949: E/AndroidRuntime(827): at android.app.ActivityThread.main(ActivityThread.java:4627) 
03-05 16:39:00.949: E/AndroidRuntime(827): at java.lang.reflect.Method.invokeNative(Native Method) 
03-05 16:39:00.949: E/AndroidRuntime(827): at java.lang.reflect.Method.invoke(Method.java:521) 
03-05 16:39:00.949: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
03-05 16:39:00.949: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
03-05 16:39:00.949: E/AndroidRuntime(827): at dalvik.system.NativeStart.main(Native Method) 
03-05 16:39:10.488: I/Process(827): Sending signal. PID: 827 SIG: 9 
+1

這個問題有太多的代碼,沒有足夠的解釋什麼是錯的。你已經花時間試圖評估這種情況,不要強迫我們花費相同的時間,以便到達現在的位置。您還應該編輯問題,以便代碼被格式化爲塊。 – unholysampler 2012-03-05 12:44:33

回答

3

你有沒有名爲getUserByEmailAndPassword()在DB_functions功能,但你把它的index.php文件。

然後在JSONParser.getJSONFromUrl()中存在一個問題 - 您可能需要檢查「json」變量的內容 - 這不是有效的JSON數組。

2

您的網址未發送JSON數據。檢查你的服務器端實現。嘗試打印日誌以瞭解您從服務器接收的數據。

希望這會幫助你。