错误:org.json.JSONException:java.lang.String类型的值<br无法转换为JSONObject

I know I have seen all similar questions on SO. I tried to solve this error but I failed. I tried almost everything but does not get solution.

My code is as follows:-

public class Tab2 extends Fragment {

private static String TAG = Tab2.class.getSimpleName();
private EditText editText1,editText2,editText3;
private Button button;
private String name,email,password;
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
private ProgressDialog pDialog;
private SessionManager session;
private database db;
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.tab2,container,false);

    pDialog = new ProgressDialog(getActivity());
    pDialog.setCancelable(false);

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

    // SQLite database handler
    db = new database(getActivity());

    // 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(getActivity(),MainActivity.class);
        startActivity(intent);
    }


    editText1 = (EditText)view.findViewById(R.id.name);
    editText2 = (EditText)view.findViewById(R.id.email);
    editText3 = (EditText)view.findViewById(R.id.password);
    inputLayoutEmail = (TextInputLayout)view. findViewById(R.id.view1);
    inputLayoutPassword = (TextInputLayout)view. findViewById(R.id.view2);
    inputLayoutName = (TextInputLayout)view. findViewById(R.id.view3);

    button = (Button)view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view1) {

            name = editText1.getText().toString().trim();
            email = editText2.getText().toString().trim();
            password = editText3.getText().toString().trim();

            if (!validateName() || !validateEmail() || !validatePassword() ) {
                Log.d(TAG, "Successfull");
                return;
            }
               try {
                   new Thread(new Runnable() {
                       @Override
                       public void run() {
                           registerUser(name, email, password);
                       }
                   }).start();
               }catch (NullPointerException e){
                   e.printStackTrace();
               }


            Toast.makeText(getActivity(), "Account Created Successfully!", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getActivity(), MainActivity.class);
            startActivity(i);
        }



    });



    return view;
}
public boolean validateName(){

    if(name.isEmpty() ) {
        inputLayoutName.setError(getString(R.string.error_name1));
        return false;
    }
    else if(name.length()<3){
        inputLayoutName.setError(getString(R.string.error_name2));
        return false;
    }
    else
        inputLayoutName.setErrorEnabled(false);
    return true;
}
public boolean validateEmail(){

    if(email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
        inputLayoutEmail.setError(getString(R.string.error_email));
        return false;
    }
    else
        inputLayoutEmail.setErrorEnabled(false);
    return true;
}
public boolean validatePassword(){

    if(password.isEmpty() ){
        inputLayoutPassword.setError(getString(R.string.error_password1));
        return false;
    }
    else if(password.length()<4){
        inputLayoutPassword.setError(getString(R.string.error_password2));
        return false;
    }
    else
        inputLayoutPassword.setErrorEnabled(false);
    return true;
}


public void registerUser(final String name, final String email, final String password){

    String req = "req_request";
    pDialog.setMessage("Registering ...");
    showDialog();

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    StringRequest strReq = new StringRequest(Request.Method.POST, appConfig.url_sign, new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
          try {


               JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                Log.d(TAG,name + " " + email + " " + password );
                if (!error) {
                    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");
                    db.addUser(name, email, uid, created_at);

                  Toast.makeText(getActivity(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
                    // Launch login activity
                    Intent i = new Intent(
                            getActivity(),
                            Login.class);
                    startActivity(i);


                }
                else {
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getActivity(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }




            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            NetworkResponse networkResponse = error.networkResponse;
            if (networkResponse != null) {
                Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode);
            }
            if (error instanceof TimeoutError) {
                Log.e("Volley", "TimeoutError");
            }else if(error instanceof NoConnectionError){
                Log.e("Volley", "NoConnectionError");
            } else if (error instanceof AuthFailureError) {

                Log.e("Volley", "AuthFailureError");
            } else if (error instanceof ServerError) {
                Log.e("Volley", "ServerError");
            } else if (error instanceof NetworkError) {
                Log.e("Volley", "NetworkError");
            } else if (error instanceof ParseError) {
                Log.e("Volley", "ParseError");
            }
            //Log.e(TAG, "Registration Error: " + error.getMessage());
         //   Toast.makeText(getActivity(),
           //         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;
        }

    };

    int socketTimeout = 10000;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    strReq.setRetryPolicy(policy);

    requestQueue.add(strReq);
}
private void showDialog() {

    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

This is my php file

<?php
$response = array();
if (isset($_POST['name']) && isset($_POST['email']) && isset   ($_POST['password'] ))   
{  
  $name = $_POST['name'];
  $email = $_POST['email'];
  $password = $_POST['password'];


require_once __DIR__ . '/db_connection.php';
$db = new DB_CONNECT();
$result = mysql_query("Insert into words(name,email,password) values('$name','$email','$password')");

if ($result)
{
    $response["success"] = 1;
    $response["message"] = "Registration successfully.";
    echo json_encode($response);
}
else
{
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred.";
  echo json_encode($response);  
}
}

 else 
 {
   $response["success"] = 0;
   $response["message"] = "Required field(s) is missing";
   echo json_encode($response);
  } 
 ?>

My JSON response is:-

{"success":0,"message":"Required field(s) is missing"}

Can you identify the error please tell me.

2个回答



@Kartikeya Garg,您可能会从API获得HTML响应或错误,并且您正在尝试将这些响应转换为JSON对象, 响应没有有效的json。</ p>

你可以在postman上试试,你可以在chrome上安装它。 这样您就可以直接从API获得响应。 你实际上得到了什么</ p>
</ div>

展开原文

原文

@Kartikeya Garg, you may be getting html response or error from API, and you are trying to convert these response into JSON object,your response doesn't have a valid json.

you can try it on postman,you can install it on chrome. so that you can get directly response from API. what you are getting in actually




您可以通过编程打印您的回复,我相信您的回复与您发布的回复不一样</ p>
</ blockquote>
</ div>

展开原文

原文

You can print your response through programming, i am sure your response is not same as what ever you post

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问