注册android mySQL Volley时出错

时间:2018-01-09 10:14:41

标签: android mysql json nullpointerexception android-volley

我是Android的新手这是我的第一个使用mysql数据库的应用程序。我完成了登录和忘记密码活动,但卡在注册。我得到nullPointException,我不知道如何摆脱这个我正在分享我的注册代码。请给我指导。

public class Resgistration3 extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    TextView click;
    EditText et_email, et_password;



    SharedPreferences preferences, preferences1, preferences2;
    Button btn_signup;
    SharedPreferences preferences3;
    SharedPreferences.Editor editor3;

    EditText et_business, et_Ntn, et_Strn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resgistration3);
        preferences3 = getSharedPreferences("MyPrefs2", MODE_PRIVATE);

        et_business = (EditText) findViewById(R.id.et_business);
        et_Ntn = (EditText) findViewById(R.id.et_Ntn);
        et_Strn = (EditText) findViewById(R.id.et_Strn);
        btn_signup = (Button) findViewById(R.id.btn_signup);
        preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
        preferences1 = getSharedPreferences("MyPrefs1", MODE_PRIVATE);
        preferences2 = getSharedPreferences("MyPrefs2", MODE_PRIVATE);

        et_email = (EditText) findViewById(R.id.et_email);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_signup = (Button) findViewById(R.id.btn_signup);

        click = (TextView) findViewById(R.id.txt_Click);
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(Resgistration3.this, Screen1.class);
            startActivity(intent);
            finish();
        }

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

            public void onClick(View view) {

                final String userName = preferences.getString("Name", null);
                final String userEmail = preferences.getString("Email", null);
                final String userPassword = preferences.getString("Password", null);
                final String userMobile = preferences.getString("Mobile", null);
                final String userCity = preferences1.getString("City", null);
                final String userDob = preferences1.getString("Dob", null);
                final String userTax = preferences1.getString("Tax", null);
                final String userCnic = preferences1.getString("Cnic", null);
                final String userBusiness = preferences2.getString("Business", null);
                final String userNtn = preferences2.getString("Ntn", null);

                registerUser(userName,userEmail,userPassword,userMobile,userCity,userDob,userTax,userCnic,userBusiness,userNtn);
                 /*Toast.makeText(getApplicationContext(),userName,Toast.LENGTH_LONG).show();*/


            }
        });
    }

    private void registerUser(final String userName, final String userEmail, final String userPassword, final String userMobile, final String userCity, final String userDob, final String userTax, final String userCnic, final String userBusiness, final String userNtn) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_REGISTER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());


             /*   try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL

                        Toast.makeText(getApplicationContext(),
                                "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                        // Launch login activity
                        Intent intent = new Intent(Resgistration3.this, WithoutLogin.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
*/
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("txtemail", userEmail);
                params.put("fname", userName);
                params.put("city", userCity);
                params.put("txtpassword", userPassword);
                params.put("mphone", userMobile);
                params.put("ntn", userNtn);
                params.put("cnic", userCnic);
                params.put("bname", userBusiness);
                params.put("tpay", userTax);
                params.put("dob", userDob);
                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

}

PHP代码:

<?PHP

$use_real_escapes = false;
require_once("connection.php");
error_reporting(0);
header( "Content-type: text/json" );    
       if (isset($_POST['fname'])){

    $fnameq = mysqli_real_escape_string( $conn, $_POST['fname']);   
    $uname = mysqli_real_escape_string( $conn,$_POST['txtname'] );
    $email = mysqli_real_escape_string( $conn,$_POST['txtemail'] );
    $city = mysqli_real_escape_string( $conn,$_POST['city'] );
    $hash = mysqli_real_escape_string( $conn,$_POST['txtpassword'] );
    $sk = "I6PnEPbQNLslYMj7ChKxDJ2yenuHLkXn";
    $password = hash('sha512', $hash.$sk);
    $phone = mysqli_real_escape_string( $conn,$_POST['phone'] );
    $mobile = mysqli_real_escape_string( $conn,$_POST['mphone'] );
    $ntn = mysqli_real_escape_string( $conn,$_POST['ntn'] );
    $strn = mysqli_real_escape_string( $conn,$_POST['strn'] );
    $cnic = mysqli_real_escape_string( $conn,$_POST['cnic'] );
    $bname = mysqli_real_escape_string( $conn, $_POST['bname'] );
    $tpay = mysqli_real_escape_string( $conn,$_POST['tpay'] );
    $dob = mysqli_real_escape_string( $conn,$_POST['dob'] );

    //file uploading//image name hre
      $image = $_FILES['photo']['name'];
      //image temp name
      $temp_name =  $_FILES['photo']['tmp_name'];  

      //uploading image to folder
      move_uploaded_file($temp_name,"uploads/salary/$image");
$check = "SELECT * FROM `tbl_users` where username = '$uname' or email = '$email'";
$crr = mysqli_query($conn , $check);

if (mysqli_num_rows($crr) <=0){


$query ="INSERT INTO `tbl_users` (username, email, password,last_login,created)
   VALUES ('$uname', '$email', '$password',NOW(),NOW());"; 
    $result = mysqli_query($conn, $query);

    $select ="Select user_id from tbl_users where username = '$uname' ";  
    $sr = mysqli_query($conn, $select);
    $row = mysqli_fetch_assoc($sr);
    $userid = $row['user_id'];

    $query2 = "INSERT INTO `tbl_account_details` (`user_id`, `fullname`, `company`, `city`, `country`, `locale`, `address`, `phone`, `phone_2`, `mobile`, `mobile_2`, `skype`, `language`, `departments_id`, `avatar`, `ntn`, `ntn_2`, `cnic`, `business_name`, `researcher`, `age`, `file_no`, `status`, `gender`, `sale_tax_no`, `dob`, `first_name`, `last_name`, `bus_emp_name`, `bus_emp_add`, `resi_add`, `rto`, `zone`, `consultancy`, `name_consultant`, `tax_category`, `activity`, `name_of_city`, `fbr_password`, `fbr_pincode`, `sbr_password`, `email_Add`) VALUES ('$userid', '$fnameq', 'NULL', '$city', 'NULL', 'en_US', 'NULL', '$phone', 'NULL', '$mobile', 'NULL', 'NULL', 'english', '0', '$image', '$ntn', 'NULL', '$cnic', '$bname', '$tpay', '$dob', 'NULL', 'NULL', 'NULL', 'NULL', '$dob', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL');";

    $result2 = mysqli_query($conn, $query2);

if($result2 > 0){

        $response = mysqli_fetch_array( $sr );
        $response["error"] = FALSE;
         $response["response1"]["user-id"] = $row["user_id"];
        $response['status'] = 'Registration Successful,Wait For Admin To Activate Your Account';
         $json =  json_encode($response);
 echo $json;
           exit;
    }
    else{
           $response['status'] = 'Registration Unsuccessful';
            $json =  json_encode($response);
            echo $json;
            exit;


               } 
            }
               else{

                       $response['status'] = 'Username Already Exists';
                       $json =  json_encode($response);
                       echo $json;
                       exit;


               }
         }

?>

我使用相同的代码进行登录及其工作! 请指导我,以便我可以再次开始工作!!

错误Logcat:

01-09 15:49:12.824 7571-7622/? E/Volley: [292] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                         java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                             at java.net.URLEncoder.encode(URLEncoder.java:205)
                                             at com.android.volley.Request.encodeParameters(Request.java:450)
                                             at com.android.volley.Request.getBody(Request.java:436)
                                             at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)
                                             at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
                                             at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
                                             at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
                                             at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
01-09 15:49:12.825 7571-7571/? E/MainActivity: Registration Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

1 个答案:

答案 0 :(得分:0)

尝试使用onErrorResponse()

中的代码

而不是

@Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            }

使用

 @Override
            public void onErrorResponse(VolleyError error) {
 NetworkResponse errorRes = error.networkResponse;
                    String stringData = "";
                    if(errorRes != null && errorRes.data != null){
                        try {
                            stringData = new String(errorRes.data,"UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.e("Error",stringData);
}
相关问题