时间:2014-02-14 01:48:13

标签: java php android json jsonobject

我目前正在开发Android应用程序,每当按下“登录”按钮时我都会收到错误消息。我知道有很多这种错误的例子,但我找不到一个与我相同的结构。这是我的代码:

LoginActivity.java:

package com.example.sabre8;

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

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.sabre8.library.DatabaseHandler;
import com.example.sabre8.library.UserFunctions;

public class LoginActivity extends Activity {
    Button btnLogin;
    //Button btnLinkToRegister;
    EditText inputUserID;
    EditText inputPassword;
    TextView loginErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    //private static String KEY_ERROR = "error";
    //private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UserID = "UserID";
    private static String KEY_PASSWORD = "Password";
    private static String KEY_FNAME = "Fname";
    private static String KEY_MNAME = "Mname";
    private static String KEY_LNAME = "Lname";
    private static String KEY_POSITION= "position";
    private static String KEY_DEPARTMENT = "department";
   // private static String KEY_NAME = "Fname";
    private static String KEY_ADMINTYPE = "admintype";
    private static String KEY_EMAIL = "email";
    private static String KEY_VERIFIER = "verifier";
   // private static String KEY_EMAIL = "email";
   // private static String KEY_CREATED_AT = "created_at";

    private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {

        protected JSONObject doInBackground(String... params) {
                UserFunctions userFunction = new UserFunctions();
                if (params.length != 2)
                        return null;
                JSONObject json = userFunction.loginUser(params[0], params[1]);
                return json;
        }

        protected void onPostExecute(JSONObject json) {
                try {
            if (json != null && json.getString(KEY_SUCCESS) != null) {
                loginErrorMsg.setText("");
                String res = json.getString(KEY_SUCCESS);
                if(Integer.parseInt(res) == 1){
                    // user successfully logged in
                    // Store user details in SQLite Database
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    JSONObject json_user = json.getJSONObject("userID");

                    // Clear all previous data in database
                    UserFunctions userFunction = new UserFunctions();
                    userFunction.logoutUser(getApplicationContext());
                    //db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        

                    // Launch Main Screen
                    Intent main = new Intent(getApplicationContext(), MainActivity.class);

                    // Close all views before launching Dashboard
                    main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(main);

                    // Close Login Screen
                    finish();
                }else{
                    // Error in login
                    loginErrorMsg.setText("Incorrect username/password");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        }
}

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

        // Importing all assets like buttons, text fields
        inputUserID = (EditText) findViewById(R.id.loginUserID);
        inputPassword = (EditText) findViewById(R.id.loginPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        loginErrorMsg = (TextView) findViewById(R.id.login_error);

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

            public void onClick(View view) {
                String userid = inputUserID.getText().toString();
                String password = inputPassword.getText().toString();                
                new MyAsyncTask().execute(userid, password);
            }

        });

    }
}

DatabaseHandler.java:

    package com.example.sabre8.library;

    import java.util.HashMap;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    public class DatabaseHandler extends SQLiteOpenHelper {

        // All Static variables
        // Database Version
        private static final int DATABASE_VERSION = 1;

        // Database Name
        private static final String DATABASE_NAME = "adserve";

        // Login table name
        private static final String TABLE_LOGIN = "login";

        // Login Table Columns names
        private static final String KEY_USERID = "userid";
        private static final String KEY_PASSWORD = "password";
        private static final String KEY_FNAME = "fname";
        private static final String KEY_MNAME = "mname";
        private static final String KEY_LNAME = "lname";   
        private static final String KEY_POSITION = "position";
        private static final String KEY_DEPARTMENT = "department";
        private static final String KEY_ADMINTYPE = "admintype";
        private static final String KEY_EMAIL = "email";
        private static final String KEY_VERIFIER = "verifier";

        public DatabaseHandler(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        // Creating Tables
        @Override
        public void onCreate(SQLiteDatabase db) {
            String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
                    + KEY_USERID + " TEXT PRIMARY KEY,"
                    + KEY_PASSWORD + "TEXT,"
                    + KEY_FNAME  + " TEXT,"
                    + KEY_MNAME + "TEXT,"
                    + KEY_LNAME + "TEXT,"
                    + KEY_POSITION+ "TEXT,"
                    + KEY_DEPARTMENT + "TEXT,"
                    + KEY_ADMINTYPE + " TEXT"
                    + KEY_EMAIL + " TEXT UNIQUE,"
                    + KEY_VERIFIER + "TEXT"  + ")";

            db.execSQL(CREATE_LOGIN_TABLE);
        }

        // Upgrading database
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);

            // Create tables again
            onCreate(db);
        }

        /**
         * Storing user details in database
         */
        public void addUser(String userid, String password, String fname, String mname, String lname, String position, String department, String admintype,String email, String verifier ) {
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(KEY_USERID, userid); // Userid
            values.put(KEY_PASSWORD, password); //Pas
            values.put(KEY_FNAME, fname); // Fname
            values.put(KEY_MNAME, mname);   // Mname
            values.put(KEY_LNAME, lname); // Lname
            values.put(KEY_POSITION, position); //Position
            values.put(KEY_DEPARTMENT, department); // Department
            values.put(KEY_ADMINTYPE, admintype);
            values.put(KEY_EMAIL, email); // Department
            values.put(KEY_VERIFIER, verifier);

            // M]
        //    values.put(KEY_UID, uid); // Email
      //      values.put(KEY_CREATED_AT, created_at); // Created At

            // Inserting Row
            db.insert(TABLE_LOGIN, null, values);
            db.close(); // Closing database connection
        }

        /**
         * Getting user data from database
         * */
        public HashMap<String, String> getUserDetails(){
            HashMap<String,String> userID = new HashMap<String,String>();
            String selectQuery = "SELECT  * FROM " + TABLE_LOGIN;

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            // Move to first row
            cursor.moveToFirst();
            if(cursor.getCount() > 0){
                userID.put("userid", cursor.getString(1));
                userID.put("password", cursor.getString(2));
                userID.put("fname", cursor.getString(3));
                userID.put("mname", cursor.getString(4));
                userID.put("lname", cursor.getString(5));
                userID.put("position", cursor.getString(6));
                userID.put("department", cursor.getString(7));
                userID.put("admintype", cursor.getString(8));
                userID.put("email", cursor.getString(9));
                userID.put("verifier", cursor.getString(10));
            }
            cursor.close();
            db.close();
            // return user
            return userID;
        }

        /**
         * Getting user login status
         * return true if rows are there in table
         * */
        public int getRowCount() {
            String countQuery = "SELECT  * FROM " + TABLE_LOGIN;
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(countQuery, null);
            int rowCount = cursor.getCount();
            db.close();
            cursor.close();

            // return row count
            return rowCount;
        }

        /**
         * Re create database
         * Delete all tables and create them again
         * */
        public void resetTables(){
            SQLiteDatabase db = this.getWritableDatabase();
            // Delete All Rows
            db.delete(TABLE_LOGIN, null, null);
            db.close();
        }
    }

UserFunctions.java:

package com.example.sabre8.library;

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;

public class UserFunctions {

    private JSONParser jsonParser;

    // Testing in localhost using wamp or xampp 
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/
    private static String loginURL = "http://10.0.2.2/Adserve1/";
    //private static String registerURL = "http://10.0.2.2/Sabre1/";

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

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

    /**
     * function make Login Request
     * @param email
     * @param password
     * */
    public JSONObject loginUser(String userid, String password){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("userid", userid));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }


    /**
     * Function get Login status
     **/
    public boolean isUserLoggedIn(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCount();
        if(count > 0){
            // user logged in
            return true;
        }
        return false;
    }

    /**
     * Function to logout user
     * Reset Database
     * */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }
}

我的logcat错误:

02-13 20:09:39.481:E / JSON Parser(1305):解析数据时出错org.json.JSONException:Value

为了更好的衡量,我的DB_Functions.php:

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Get user by email and password
     */
    public function getUserByEmailAndPassword($userid, $password) {
        $result = mysql_query("SELECT * FROM user_tb WHERE UserID = '$userid'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            // check for password equality
            $pass = $result['password'];
            if ($pass == $password) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
               return false;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($userid) {
        $result = mysql_query("SELECT UserID from user_tb WHERE UserID = '$userid'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

}

?>

对于冗长的代码感到抱歉,但我被困住了。希望你能帮忙。

1 个答案:

答案 0 :(得分:0)

JSON库无法解析来自服务器的响应,这就是它抛出JSONException的原因。无论出于何种原因,您的PHP脚本都没有返回有效的JSON。

首先,使用curl或其他HTTP工具向您的脚本发送请求并查看响应是什么。如果有任何PHP错误,您可能会在响应中看到它们的HTML代码。 Postman for Chrome非常适合调试Web服务。

然后,一旦您修复了PHP脚本的任何错误,您就可以使用JSONLint之类的工具来确保它返回的JSON有效。