java - 用户未创建 -JSON 异常:输入在字符 0 处结束
问题描述
我正在尝试将用户详细信息从我的应用程序添加到 php 后端。该应用程序位于android studio中。但由于某种原因,我无法在数据库中添加用户,当我在 android studio 中运行登录时,我看到这些错误弹出。在模拟器或实际设备上运行应用程序时,它说用户未创建。
这是我的错误日志:
2019-12-17 13:03:49.521 18785-18785 E/EnhancedIntentService: binding to the service failed
2019-12-17 13:04:04.203 18785-18891 E/Buffer Error: Error converting result java.lang.NullPointerException
2019-12-17 13:04:04.204 18785-18891 E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
主要活动
public class MainActivity extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
private final JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url = config.mainurl + "create_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_USERNAME = "username";
private static final String TAG_GUSERNAME = "gusername";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
private static final String TAG_PASSWORD = "password";
private static final String TAG_OTHER = "other";
private static final String TAG_PROMOCODE = "promocode";
//Textbox
private EditText firstname;
private EditText lastname;
private EditText username;
private EditText gusername;
private EditText email;
private EditText mobile;
private EditText password;
private EditText promocode;
private Button signup;
private Button signin;
private int success;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
gusername = (EditText) findViewById(R.id.gusername);
email = (EditText) findViewById(R.id.email);
mobile = (EditText) findViewById(R.id.mobileNumber);
password = (EditText) findViewById(R.id.password);
promocode = (EditText) findViewById(R.id.promocode);
signup = (Button) findViewById(R.id.registerBtn);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkdetails()) {
// Loading offers in Background Thread
new OneLoadAllProducts().execute();
}
}
});
signin = (Button) findViewById(R.id.loginFromRegister);
signin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
private boolean checkdetails() {
//special character checking
Pattern p = Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string"+username.getText().toString());
boolean b = m.find();
if (b)
System.out.println("Rajan_There is a special character in my string");
if (email.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Email", Toast.LENGTH_SHORT).show();
email.requestFocus();
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()) {
Toast.makeText(MainActivity.this, "Enter valid Value for Email", Toast.LENGTH_SHORT).show();
email.requestFocus();
return false;
} else if (password.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Password", Toast.LENGTH_SHORT).show();
password.requestFocus();
return false;
} else if (firstname.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for FirstName", Toast.LENGTH_SHORT).show();
firstname.requestFocus();
return false;
} else if (lastname.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for LastName", Toast.LENGTH_SHORT).show();
lastname.requestFocus();
return false;
} else if (username.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Username", Toast.LENGTH_SHORT).show();
username.requestFocus();
return false;
} else if (p.matcher(username.getText().toString()).find()) {
Toast.makeText(MainActivity.this, "Enter Username without any special characters", Toast.LENGTH_SHORT).show();
username.requestFocus();
return false;
} else if (gusername.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for G Username", Toast.LENGTH_SHORT).show();
pubgusername.requestFocus();
return false;
} else if (mobile.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Mobile", Toast.LENGTH_SHORT).show();
mobile.requestFocus();
return false;
} else if (!Patterns.PHONE.matcher(mobile.getText().toString().trim()).matches()) {
Toast.makeText(MainActivity.this, "Enter Valid Value for MobileNumber", Toast.LENGTH_SHORT).show();
mobile.requestFocus();
return false;
}
return true;
}
class OneLoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
Map<String, String> params = new HashMap<>();
params.put(TAG_FIRSTNAME, firstname.getText().toString().trim());
params.put(TAG_LASTNAME, lastname.getText().toString().trim());
params.put(TAG_USERNAME, username.getText().toString().trim());
params.put(TAG_GUSERNAME, gusername.getText().toString().trim());
params.put(TAG_EMAIL, email.getText().toString().trim());
params.put(TAG_MOBILE, mobile.getText().toString().trim());
params.put(TAG_PASSWORD, password.getText().toString().trim());
params.put(TAG_OTHER, "");
params.put(TAG_PROMOCODE, promocode.getText().toString().trim());
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/*
Updating parsed JSON data into ListView
*/
if (success == 1) {
// offers found
// Getting Array of offers
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this,"Registration done Succsessfully",Toast.LENGTH_LONG).show();
} else if(success == 2){
// no offers found
Toast.makeText(MainActivity.this,"Email/mobile/username is already exist. change it and try again!",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"User not created",Toast.LENGTH_LONG).show();
}
}
});
}
}
}
JSONparser.java
import android.util.Log;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
public class JSONParser {
private static InputStream is = null;
private static JSONObject jObj = null;
private static String json = "";
private Integer status = 0;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
//for builing a parameter
StringBuilder result = new StringBuilder();
boolean first = true;
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
result.append("&");
}
result.append(key).append("=")
.append(URLEncoder.encode(params.get(key), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
System.out.println("string"+result.toString());
// Making HTTP request
try {
// check for request method
if(Objects.equals(method, "POST")){
// request method is POST
// defaultHttpClient
URL urlr = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlr.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
/* for Get request */
conn.setRequestMethod("POST");
conn.setDoInput(true);
// You need to set it to true if you want to send (output) a request body,
//for example with POST or PUT requests.
//Sending the request body itself is done via the connection's output stream
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
int statusCode = conn.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
status = 1; // Successful
}else{
status = 0; //"Failed to fetch data!";
}
conn.connect();
is = conn.getInputStream();
}else if(Objects.equals(method, "GET")){
// request method is GET
if (result.length() != 0) {
url += "?" + result.toString();
}
// request method is GET
// defaultHttpClient
URL urlr = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlr.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
/* for Get request */
conn.setRequestMethod("GET");
// You need to set it to true if you want to send (output) a request body,
//for example with POST or PUT requests.
//Sending the request body itself is done via the connection's output stream
conn.setDoOutput(true);
conn.connect();
is = conn.getInputStream();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
创建用户.php
<?php
header('Content-Type: application/json');
/*
* Following code will create a new product row
* All product details are read from HTTP POST Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_REQUEST['firstname']) && isset($_REQUEST['lastname']) && isset($_REQUEST['username']) && isset($_REQUEST['gusername']) && isset($_REQUEST['email']) && isset($_REQUEST['mobile']) && isset($_REQUEST['password']) && isset($_REQUEST['other']) && isset($_REQUEST['promocode'])) {
$firstname= $_REQUEST['firstname'];
$lastname= $_REQUEST['lastname'];
$username= $_REQUEST['username'];
$gusername= $_REQUEST['gusername'];
$email= $_REQUEST['email'];
$mobile= $_REQUEST['mobile'];
$password= $_REQUEST['password'];
$other= $_REQUEST['other'];
$promocode= $_REQUEST['promocode'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$conn = $db->connect();
// POST all iid from users table
$results = mysqli_query($conn,"SELECT * FROM user WHERE mobile='$mobile' or email='$email' or username='$username'") or die(mysql_error());
// check for empty result
if (mysqli_num_rows($results) == 0) {
date_default_timezone_set("Asia/Calcutta");
$cur = date("Y-m-d H:i:s");
// mysql inserting a new row
$result = mysqli_query($conn,"INSERT INTO user (`userid`, `firstname`, `lastname`, `username`, `gusername`, `gender`, `email`, `mobile`, `password`, `other`, `promocode`, `log_entdate`) VALUES (NULL, '$firstname', '$lastname', '$username', '$gusername', NULL, '$email', '$mobile', '$password', '$other', '$promocode', '$cur')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
$rows = mysqli_fetch_array($results, MYSQLI_BOTH);
// echo $rows['mobile'];
// echo $mobile;
if($rows['mobile']==$mobile){
// successfully updated
$response["success"] = 2;
$response["message"] = "mobile is same.";
// echoing JSON response
echo json_encode($response);
} else if($rows['email']==$email){
// successfully updated
$response["success"] = 2;
$response["message"] = "email is same.";
// echoing JSON response
echo json_encode($response);
} else if($rows['username']==$username){
// successfully updated
$response["success"] = 2;
$response["message"] = "username is same.";
// echoing JSON response
echo json_encode($response);
}
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
解决方案
推荐阅读
- python - SQLite JSON查询以计算嵌套列表中的项目数
- python - 无法提供图表作为 youtube 搜索 API 的参数
- c# - Selenium C# Click() 在使用 Jenkins 时无法访问另一个 URL
- r - 在不同的列中分隔一串以空格分隔的数据框
- python - OSX 上的加密升级问题
- c - 查找具有最大/最小位数集的数字
- vue.js - 从 vuex 获取时,Vue 路由器 id 未定义
- pdf - 支持在 Xamarin Forms 中将 HTML 转换为 PDF
- python - 基于两列中的模糊匹配合并两个数据帧
- python - 修复python中的弹丸运动公式