dousui6193 2014-12-19 16:56
浏览 67

Android JSON空指针解析

I am trying to modify a bit of code from the working state to add more functionality to understand how the code is working. So basically I am trying to add additional functionality by giving the user an option to create a new bet. Before I modified it was working fine, by fine I mean the user was able to login and register with out anyproblem. Even the layout are also being displayed with out any problem.

For comparison purpose I am going to add the same php files before and after version.

index.php Before

<?php

/**
 * File to handle all API requests
 * Accepts GET and POST
 * 
 * Each request will be identified by TAG
 * Response will be JSON data

  /**
 * check for POST request 
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') 
{
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/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
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) 
        {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else 
        {
            // user not found
            // echo json 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['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $prefered_username = $_POST['preffered'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
        else 
        {
            // store user
            $user = $db->storeUser($name, $email, $password, $prefered_username);
            if ($user) 
            {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } 
            else
             {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    }
     else
      {
        echo "Invalid Request";
    }
} 
else
 {
    echo "Access Denied";
}


?>

index.php After

  <?php

/**
 * File to handle all API requests
 * Accepts GET and POST
 * 
 * Each request will be identified by TAG
 * Response will be JSON data

  /**
 * check for POST request 
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') 
{
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/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
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) 
        {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else 
        {
            // user not found
            // echo json 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['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $prefered_username = $_POST['preffered'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } 
        else 
        {
            // store user
            $user = $db->storeUser($name, $email, $password, $prefered_username);
            if ($user) 
            {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } 
            else
             {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    }
    /********************************************************************************************************************************************************/
     else if ($tag == 'betregister') 
     {
     /*
        // Request type is New Bet Register
        $bet_uid = $_POST['uid'];
        $bet_id = $_POST['betid'];        
        $bet_starttime = $_POST['start_time'];
        $bet_updated = $_POST['updated'];
        $bet_status = $_POST['bet_status'];
        $bet_users = $_POST['bet_users'];
        */


        $bet_name = $_POST['bet_name'];
        $bet_brief = $_POST['bet_brief'];
        $bet_description = $_POST['bet_description'];
        $bet_value = $_POST['bet_value'];
        $bet_endtime = $_POST['end_time'];

        // check if bet already exists
        if ($db->betExists($bet_name)) 
        {
            // bet already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "bet already existed";
            echo json_encode($response);
        } 
        else 
        {
            // create bet
            $bet = $db->createNewBet($bet_name, $bet_brief, $bet_description, $bet_value,$bet_endtime);
            if ($bet) 
            {
                // bet created successfully
                $response["success"] = 1;
                $response["uid"] = $bet["uid"];
                $response["betid"] = $bet["betid"];
                $response["bet"]["bet_name"] = $bet["bet_name"];
                $response["bet"]["bet_brief"] = $bet["bet_brief"];
                $response["bet"]["bet_description"] = $bet["bet_description"];
                echo json_encode($response);
            } 
            else
             {
                // bet failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in creating new bet";
                echo json_encode($response);
            }
        }
    }
     else
      {
        echo "Invalid Request";
    }
} 
else
 {
    echo "Access Denied";
}


?>

DBFunctions Before

<?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() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password, $preferred_name) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }
    }

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

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        if(!$result){
            return false;
        }

        $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
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>

DBFunctions After

    <?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() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password, $preferred_name) 
    {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }
    }

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

    /**
     * Check user is existed or not
     */
    public function isUserExisted($email) {
        $result = mysql_query("SELECT email from users WHERE email = '$email'");
        if(!$result){
            return false;
        }

        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

     /**
     * Check user is betExists or not
     */
    public function isbetExists($betName) {
        $result = mysql_query("SELECT bet_name from bets WHERE bet_name = '$betName'");
        if(!$result){
            return false;
        }

        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // bet exists 
            return true;
        } else {
            // bet doesnot exist
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) 
    {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password)
    {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

    /**
     * Adding new bet (my new code)
     */
     public function createNewBet($betname, $betbrief, $betdescription, $betvalue)
     {
        $uid = uniqid('',true);
        $bet_id = betid('',true);
        $result = mysql_query("INSERT INTO bets(bet_name,bet_brief,bet_description) VALUES('$betname','$betbrief','$betdescription')");


     }
     /*
         public function storeUser($name, $email, $password, $preferred_name) 
    {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, preffered_usrname, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$preferred_name', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
        echo mysql_error();
            return false;
        }
    }*/



}

?>

And finally this is the java class that my android app that is going to be utilizing the code.

package com.techiequickie.james.boadraf;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

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

import databasehandler.DatabaseHandler;
import databasehandler.UserFunctions;

/**
 * Created by YP on 17-Nov-14.
 */
public class newBet_activity extends ActionBarActivity
{
    EditText inputBetname, inputBetbrief, inputBetdescription;
    SeekBar valueSeekbar; //= null;
    Button btn_newbet;


    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    @SuppressWarnings("unused")
    private static String KEY_ERROR = "error";
    @SuppressWarnings("unused")
    private static String KEY_ERROR_MSG = "error_msg";
    //private static String KEY_UID = "uid";
    private static String KEY_BETNAME = "bet_name";
    private static String KEY_BETBRIEF = "bet_brief";
    private static String KEY_BETDESCRIPTION = "bet_description";
    private static String KEY_BETVALUE = "bet_value";
   // private static String KEY_CREATED_AT = "created_at";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newbet);
        // Importing all assets like buttons, text fields
        inputBetname = (EditText) findViewById(R.id.betName_et);
        inputBetbrief = (EditText) findViewById(R.id.betBriefDescription_et);
        inputBetdescription = (EditText) findViewById(R.id.betDescription_et);
        btn_newbet = (Button) findViewById(R.id.bet_btn);

        //valueSeekbar = (SeekBar) findViewById(R.id.betValue_bar);

        /*
        valueSeekbar.setOnSeekBarChangeListener
       (

         new SeekBar.OnSeekBarChangeListener()
        {
            int progressChanged = 0;

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressChanged = progress;
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(newBet_activity.this, "seek bar progress:" + progressChanged, Toast.LENGTH_SHORT).show();
            }
        }
       );*/


        btn_newbet.setOnClickListener(new View.OnClickListener()
         {


            public void onClick(View view)
            {
                String betname = inputBetname.getText().toString();
                String betBrief = inputBetbrief.getText().toString();
                String betDescription = inputBetdescription.getText().toString();
                //StringBuilder betValue = ((toString()) valueSeekbar.getProgress());

                new BetRegisterTask().execute(betname,betBrief,betDescription);
            }
         }
        );


    }


        class BetRegisterTask extends AsyncTask<String, Void, String>
        {

            @Override
            protected String doInBackground(String... params)
            {

                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.createBet(params[0], params[1], params[2]);

                // check for login response
                try
                {
                    if (json.getString(KEY_SUCCESS) != null)
                    {

                        String res = json.getString(KEY_SUCCESS);
                        if (Integer.parseInt(res) == 1)
                        {
                            // user successfully registred
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                            JSONObject json_user;
                            json_user = json.optJSONObject("user");

                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.newBet(json_user.getString(KEY_BETNAME), json_user.getString(KEY_BETBRIEF), json.getString(KEY_BETDESCRIPTION));
                            return "1";

                        }

                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }

                return "0";
            }

            @Override
            protected void onPostExecute(String s)
            {
                super.onPostExecute(s);
                if (s.equals("1"))
                {

                    // Launch Dashboard Screen
                    Intent dashboard = new Intent(getApplicationContext(), Loginactivity.class);
                    // Close all views before launching Dashboard
                    dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(dashboard);
                    // Close Registration Screen
                    finish();
                    showToastforSucessfulBetCreation();

                }
                else
                {
                    // Error in registration
                    //registerErrorMsg.setText("Error occurred in registration");
                    showToastforUnsucessfulBetCreation();
                }
            }
        }

    public void showToastforSucessfulBetCreation() {
        Toast toast = Toast.makeText(this, "Registration Sucessfull", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, 0, 30);
        toast.show();

    }


    public void showToastforUnsucessfulBetCreation() {
        Toast toast = Toast.makeText(this, "Registration UnSucessfull", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, 0, 30);
        toast.show();

    }

}

But for now I am NOT able to login to the app itself, which I was able to before.

EDIT adding a dropbox link as exceeding the character limit https://www.dropbox.com/s/iszqh2mjw23kyvq/register_java_class.txt?dl=0

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?