dongpangfu6322 2017-01-25 09:52
浏览 87

JSONException:java.lang.String类型的值require_once无法转换为JSONObject

I am still new to android development, I am trying to make an app that will register a user and store the information on an online server but I keep getting the following error.

Error code:

01-25 08:13:18.036 1123-1123/com.mintech.hubcalabar D/RegistrationActivity: Register Response: require_once 'include/DB_Functions.php';
                                                                            $db = new DB_Functions();

                                                                            // json response array
                                                                            $response = array("error" => FALSE);

                                                                            if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {

                                                                            // receiving the post params
                                                                            $name = $_POST['name'];
                                                                            $email = $_POST['email'];
                                                                            $password = $_POST['password'];

                                                                            // check if user is already existed with the same email
                                                                            if ($db->isUserExisted($email)) {
                                                                            // user already existed
                                                                            $response["error"] = TRUE;
                                                                            $response["error_msg"] = "User already existed with " . $email;
                                                                            echo json_encode($response);
                                                                            } else {
                                                                            // create a new user
                                                                            $user = $db->storeUser($name, $email, $password);
                                                                            if ($user) {
                                                                            // user stored successfully
                                                                            $response["error"] = FALSE;
                                                                            $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"] = TRUE;
                                                                            $response["error_msg"] = "Unknown error occurred in registration!";
                                                                            echo json_encode($response);
                                                                            }
                                                                            }
                                                                            } else {
                                                                            $response["error"] = TRUE;
                                                                            $response["error_msg"] = "Required parameters (name, email or password) is missing!";
                                                                            echo json_encode($response);
                                                                            }
                                                                            ?>
01-25 08:13:18.056 1123-1123/com.mintech.hubcalabar W/System.err: org.json.JSONException: Value require_once of type java.lang.String cannot be converted to JSONObject
01-25 08:13:18.060 1123-1123/com.mintech.hubcalabar W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
01-25 08:13:18.060 1123-1123/com.mintech.hubcalabar W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:158)
01-25 08:13:18.060 1123-1123/com.mintech.hubcalabar W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:171)
01-25 08:13:18.060 1123-1123/com.mintech.hubcalabar W/System.err:     at com.mintech.hubcalabar.RegistrationActivity$1.onResponse(RegistrationActivity.java:125)
01-25 08:13:18.064 1123-1123/com.mintech.hubcalabar W/System.err:     at com.mintech.hubcalabar.RegistrationActivity$1.onResponse(RegistrationActivity.java:119)
01-25 08:13:18.064 1123-1123/com.mintech.hubcalabar W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
01-25 08:13:18.068 1123-1123/com.mintech.hubcalabar W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
01-25 08:13:18.068 1123-1123/com.mintech.hubcalabar W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
01-25 08:13:18.072 1123-1123/com.mintech.hubcalabar W/System.err:     at android.os.Handler.handleCallback(Handler.java:725)
01-25 08:13:18.072 1123-1123/com.mintech.hubcalabar W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:92)
01-25 08:13:18.072 1123-1123/com.mintech.hubcalabar W/System.err:     at android.os.Looper.loop(Looper.java:137)
01-25 08:13:18.072 1123-1123/com.mintech.hubcalabar W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-25 08:13:18.076 1123-1123/com.mintech.hubcalabar W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
01-25 08:13:18.076 1123-1123/com.mintech.hubcalabar W/System.err:     at java.lang.reflect.Method.invoke(Method.java:511)
01-25 08:13:18.080 1123-1123/com.mintech.hubcalabar W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-25 08:13:18.080 1123-1123/com.mintech.hubcalabar W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-25 08:13:18.084 1123-1123/com.mintech.hubcalabar W/System.err:     at dalvik.system.NativeStart.main(Native Method)
01-25 08:13:18.088 1123-1123/com.mintech.hubcalabar D/Volley: [1] Request.finish: 4149 ms: [ ] http://templefoundation.com.ng/hubcalabar/register.php 0xa3649634 NORMAL 1

Here is my java code:

public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener{

private static final String TAG = RegistrationActivity.class.getSimpleName();;
private Button btnRegister;
private EditText inputName, inputEmail, inputPassword;
private TextView login;

private ProgressDialog progressDialog;
private Session session;
private SQLiteHandler db;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);


    inputName = (EditText) findViewById(R.id.etName);
    inputEmail = (EditText) findViewById(R.id.etEmail);
    inputPassword = (EditText) findViewById(R.id.etPassword);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    login = (TextView)findViewById(R.id.tvLogin);
    login.setOnClickListener(this);
    btnRegister.setOnClickListener(this);

    progressDialog = new ProgressDialog(this);
    progressDialog.setCancelable(false);

    db = new SQLiteHandler(getApplicationContext());

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

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

    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btnRegister:
            String name = inputName.getText().toString().trim();
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
            registerUser(name, email, password);
           } else {
           Toast.makeText(getApplicationContext(),
           "Please enter your details!", Toast.LENGTH_LONG)
           .show();
           }
           break;
        case R.id.tvLogin:
            startActivity(new Intent(RegistrationActivity.this, LoginActivity.class));
            finish();
            break;
        default:
    }
}
/**
      * Function to store user in MySQL database will post params(tag, name,
      * email, password) to register url
      * */
        private void registerUser(final String name, final String email,
        final String password) {
    // Tag used to cancel the request
   String tag_string_req = "req_register";

   progressDialog.setMessage("Registering ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST,
    AppConfig.URL_REGISTER, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
    Log.d(TAG, "Register Response: " + response.toString());
    hideDialog();
    try {
    JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user.getString("created_at");
                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

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

                    // Launch login activity
                    Intent intent = new Intent(RegistrationActivity.this, LoginActivity.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();
            hideDialog();
            }
        }) {
        @Override
        protected Map<String, String> getParams() {
        // Posting params to register url
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", name);
        params.put("email", email);
        params.put("password", password);

        return params;
        }
        };

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

private void showDialog() {
    if (!progressDialog.isShowing())
    progressDialog.show();
}
private void hideDialog() {
    if (progressDialog.isShowing())
    progressDialog.dismiss();
    }}

And here is my php code:

require_once 'include/DB_Functions.php';
$db = new DB_Functions();
 
// json response array
$response = array("error" => FALSE);
 
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {
 
    // receiving the post params
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
 
    // check if user is already existed with the same email
    if ($db->isUserExisted($email)) {
        // user already existed
        $response["error"] = TRUE;
        $response["error_msg"] = "User already existed with " . $email;
        echo json_encode($response);
    } else {
        // create a new user
        $user = $db->storeUser($name, $email, $password);
        if ($user) {
            // user stored successfully
            $response["error"] = FALSE;
            $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"] = TRUE;
            $response["error_msg"] = "Unknown error occurred in registration!";
            echo json_encode($response);
        }
    }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters (name, email or password) is missing!";
    echo json_encode($response);
}
?>

Please how do I go about fixing this error? Thanks in advance :D

  • 写回答

1条回答 默认 最新

  • duanhe4155 2017-01-25 10:20
    关注

    JSONObject jObj = new JSONObject(response);

    turn it to like this JSONObject jObj = new JSONObject(response.toString());

    maybe it can work.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测