I am getting the errors like while running this app. "Error parsing data org.json.JSONException: Value
我在运行这个应用程序时遇到了错误。 “解析数据时出错org.json.JSONException:Value
this is my register_user.java
这是我的register_user.java
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class register_user extends Activity{
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText signup_username;
EditText signup_email;
EditText signup_password;
Button registerBtn;
TextView registerErrorMsg;
// url to create new product
private static String url_create_users = "http://10.0.2.2/http://10.0.2.2/android_iwant/signup_success.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_form);
// Edit Text
signup_username = (EditText) findViewById(R.id.signup_username);
signup_email = (EditText) findViewById(R.id.signup_email);
signup_password = (EditText) findViewById(R.id.signup_password);
registerBtn = (Button) findViewById(R.id.regiserBtn);
// button click event
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewUser().execute();
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(register_user.this);
pDialog.setMessage("Creating Users..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
/*String username = signup_username.getText().toString();
String email = signup_email.getText().toString();
String password = signup_password.getText().toString();*/
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", signup_username.getText().toString()));
params.add(new BasicNameValuePair("email",signup_email.getText().toString()));
params.add(new BasicNameValuePair("password", signup_password.getText().toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_users,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created users
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create users
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
This is the JSONParser.java. this is the data parsing class of android
这是JSONParser.java。这是android的数据解析类
package com.iwantnew.www;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
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() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
}
this is the PHP code(signup_success.php)
这是PHP代码(signup_success.php)
<?php
// array for JSON response
$response = array();
if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$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, salt, created_at) VALUES('$uuid', '$username', '$email', '$encrypted_password', '$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 {
return false;
}
$result = mysql_query("INSERT INTO users(name,email,password) VALUES ('$username','$email,$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "successfully signed Up.";
// 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 {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
1 个解决方案
#1
0
Error parsing data org.json.JSONException
解析数据org.json.JSONException时出错
This error is because paring json response is failed because the response from the server side is not what is expected.
此错误是因为配对json响应失败,因为来自服务器端的响应不是预期的。
In your PHP Script i saw an problem
在您的PHP脚本中我看到了一个问题
// 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 {
return false;
}
In this block there is return statement in if and else both so the code which is written after that is not reachable. I don't get it what the bellow code do but if data is inserted you have to use json_encode for response in form of json. So for that you have to remove return from if block
在这个块中,if和else都有return语句,因此之后写的代码是不可访问的。我没有得到它的波纹管代码,但如果插入数据,你必须使用json_encode以json的形式进行响应。因此,您必须从if块中删除return
// 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
echo json_encode(mysql_fetch_array($result));
exit;
}
Some advice wile using api 1. First check your result from web by postmen and confirm that the output is as per your requirement. 2. In android use debugging to find out the error.
一些建议使用api 1.首先通过邮递员检查您的结果,并确认输出符合您的要求。 2.在android中使用调试来查找错误。
Debugging your code is very useful.
调试代码非常有用。
#1
0
Error parsing data org.json.JSONException
解析数据org.json.JSONException时出错
This error is because paring json response is failed because the response from the server side is not what is expected.
此错误是因为配对json响应失败,因为来自服务器端的响应不是预期的。
In your PHP Script i saw an problem
在您的PHP脚本中我看到了一个问题
// 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 {
return false;
}
In this block there is return statement in if and else both so the code which is written after that is not reachable. I don't get it what the bellow code do but if data is inserted you have to use json_encode for response in form of json. So for that you have to remove return from if block
在这个块中,if和else都有return语句,因此之后写的代码是不可访问的。我没有得到它的波纹管代码,但如果插入数据,你必须使用json_encode以json的形式进行响应。因此,您必须从if块中删除return
// 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
echo json_encode(mysql_fetch_array($result));
exit;
}
Some advice wile using api 1. First check your result from web by postmen and confirm that the output is as per your requirement. 2. In android use debugging to find out the error.
一些建议使用api 1.首先通过邮递员检查您的结果,并确认输出符合您的要求。 2.在android中使用调试来查找错误。
Debugging your code is very useful.
调试代码非常有用。