Error when converting a string to JSONObject. What can it be caused by? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 14 hours ago.
Improve this question
When trying to convert a JSON string to a JSONObject in Java, a RuntimeError comes out
Here is my implementation of this in Java
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewError.setVisibility(View.GONE);
phone = String.valueOf(editTextPhone.getText());
password = String.valueOf(editTextPassword.getText());
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="http://192.168.0.113/microgatgets/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("success")) {
Toast.makeText(MainActivity.this, "Авторизация успешна!", Toast.LENGTH_SHORT).show();
name = jsonObject.getString("name");
phone = jsonObject.getString("phone");
apiKey = jsonObject.getString("apiKey");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("logged", "true");
editor.putString("name", name);
editor.putString("phone", phone);
editor.putString("apiKey", apiKey);
editor.apply();
Intent intent = new Intent(getApplicationContext(), CardActivity.class);
startActivity(intent);
finish();
}
else {
textViewError.setText(message);
textViewError.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textViewError.setText(error.getLocalizedMessage());
textViewError.setVisibility(View.VISIBLE);
}
}){
protected Map<String, String> getParams(){
Map<String, String> paramV = new HashMap<>();
paramV.put("phone", phone);
paramV.put("password", password);
return paramV;
}
};
queue.add(stringRequest);
}
});
And here is the JSON string itself
{ "status": "failed", "message": "All fields are required" }
Stack trace
FATAL EXCEPTION: main
Process: com.example.microgadgets, PID: 25538
java.lang.RuntimeException: org.json.JSONException: Value <br of
java.lang.String cannot be converted to JSONObject at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:96)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:955)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:8689)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085)
Caused by: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:169)
at org.json.JSONObject.<init>(JSONObject.java:182)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:68)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29) 
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102) 
at android.os.Handler.handleCallback(Handler.java:955) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:228) 
at android.app.ActivityThread.main(ActivityThread.java:8689) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085) 
I hope I added what I needed. If that's not the case, correct me, and I'm also writing all this because I just need to add some text. In response, I get a JSON string from the backend for my application

Related

How fix " Not a primitive array"

I trying to parse this json.
[
{
"id": 2,
"name": "612",
"code": "auditorium 612"
},
{
"id": 3,
"name": "613",
"code": "auditorium 613"
}
]
JSONException returns an error " Not a primitive array". I tryed to parse JsonObjectRequest, but another error occurred. Finally I came to option JsonArrayRequest
W/System.err: org.json.JSONException: Not a primitive array: class org.json.JSONArray
at org.json.JSONArray.<init>(JSONArray.java:116)
at com.example.dyplom.MainActivity$4.onResponse(MainActivity.java:126)
at com.example.dyplom.MainActivity$4.onResponse(MainActivity.java:122)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:90)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:790)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is the parser method.
private void loadStrings()
{
String url_head = "http://10.0.2.2:8080/rStrings";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,url_head, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray_string_list = new JSONArray(response);
main_name_rString = new String[jsonArray_string_list.length()];
main_code_rString = new String[jsonArray_string_list.length()];
for (int i = 0; i < jsonArray_string_list.length();i++){
JSONObject string_params_string_list = jsonArray_string_list.getJSONObject(i);
Long string_id = string_params_string_list.getLong("id");
String string_name = string_params_string_list.getString("name");
String string_code = string_params_string_list.getString("code");
main_id_rSting[i]=string_id;
main_name_rString[i] = string_name;
main_code_rString[i] = string_code;
Log.i("Id", String.valueOf(main_id_rSting[i]));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mQueue.add(request);
}
I looked at similar questions, but I didn't really find anything. How can I fix it? Maybe I don't see smth.
If the onResponse method already received the (JSONArray response), you don't need to create again a new JSONArray in the next line in your code. It would help if I can see the line where the error happen.

value Data of type java.lang.String cannot be converted to JSONObject # java android

Can you help, why I'm getting this error in logcat?
Recently it was OK since I moved to SDK 28, it is failing. But I'm not sure that this is an issue of SDK 28.
Payment is getting OK (user receives a payment, but Intent isn't working and in Logcat I got this error)
Can you suggest something?
thank you
public void sendPayment(String type) {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MAKE_PAYMENT_API, getParms(type), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
ProjectUtils.pauseProgressDialog();
if (flag) {
ProjectUtils.showToast(mContext, msg);
Intent in = new Intent(mContext, WriteReview.class);
in.putExtra(Consts.HISTORY_DTO, historyDTO);
startActivity(in);
finish();
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public Map<String, String> getParms(String type) {
HashMap<String, String> params = new HashMap<>();
params.put(Consts.INVOICE_ID, historyDTO.getInvoice_id());
params.put(Consts.USER_ID, userDTO.getUser_id());
params.put(Consts.COUPON_CODE, coupon_code);
params.put(Consts.FINAL_AMOUNT, final_amount);
params.put(Consts.PAYMENT_STATUS, "1");
params.put(Consts.PAYMENT_TYPE, type);
params.put(Consts.DISCOUNT_AMOUNT, discount_amount);
Log.e("sendPaymentConfirm", params.toString());
return params;
}
UPD:
errors
sendPaymentConfirm: {payment_type=1, final_amount=150, discount_amount=0, invoice_id=RCVG2QNWBHCP, payment_status=1, user_id=614, coupon_code=}
PaymentProActivity: error body --->null error msg --->org.json.JSONException: Value <div of type java.lang.String cannot be converted to JSONObject
Issue solved, by downgrade from PHP 7.2, to PHP 7.1

Android getting html response instead of json response | Value <br of type java.lang.String cannot be converted to JSONObject

Hi I am having a hard time figuring out what could be the cause of this error. until I tried to use the debug and found out that instead of a json response I am getting an html response. Please help me figure this out.
Check this java code :
from this point the error is triggered
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_SUBMIT_CLIENT, response -> {
Log.d(TAG, "Submission Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.d("Debug", jObj.toString());
boolean error = jObj.getBoolean("success");
if (!error) {
Toast.makeText(getContext(), "Client successfully submitted.", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and also this is my hp script. I have it also test in some websites and found no error so I'm pretty sure that there is no problem here. I will still post it and leave it to you guys and If there is a problem please point it out.
require_once __DIR__ . '/DB_Connect.php';
$db = new DB_CONNECT();
$query = mysqli_query("INSERT INTO clientinformation(amountApplied, mop, term, lastname, firstname, middlename, birthdate, age, sex, status, marriageDate, noChildren, nationality, acr, address, cityMunicipality, province, telNo, years, offAddress, offCityMunicipality, offProvince, offTelNo, offYears, busAddress, busCityMunicipality, busProvince, busTelNo, busYears, productServiceOffered) VALUES('$amountApplied','$mop','$term','$lastname','$firstname','$middlename','$birthdate','$age','$sex','$status','$marriageDate','$noChildren','$nationality','$acr','$address','$cityMunicipality','$province','$telNo','$years','$offAddress','$offCityMunicipality','$offProvince','$offTelNo','$offYears','$busAddress','$busCityMunicipality','$busProvince','$busTelNo','$busYears','$productServiceOffered')");
$result = $mysqli->query($query);
if ($result) {
$response["success"] = 1;
$response["error_msg"] = "Application successfully made.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["error_msg"] = "Oops! An error occurred.";
echo json_encode($response);
}
and lastly here is my log
W/System.err: org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:112) W/System.err: at
org.json.JSONObject.(JSONObject.java:163)
at org.json.JSONObject.(JSONObject.java:176)
at info.androidhive.bottomnavigation.fragment.ApplicationFragment.lambda$submitClient$4$ApplicationFragment(ApplicationFragment.java:253)
at info.androidhive.bottomnavigation.fragment.-$$Lambda$ApplicationFragment$8jvL3OnFiDofc9nz50lAoSvp9ew.onResponse(Unknown
Source:4)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:873)

How To send array in params in fast android networking library

I am using Fast-Android-Networking and I want to send data to server which contains strings and arrays. It's ok to send string but I am unable to send array its not array list. It's simple array.
I have search other solution but all are regarding volley.
can anyone help?
Please dont mark duplicate.
The last 5 parameters are arrays. I tried it as String.valueOf(ReadQuran) but it also didn't work.
My Code:
AndroidNetworking.post(Api.ROOT_URL +"api/stageFiveFormData")
.addBodyParameter("mto_id",idu)
.addBodyParameter("school_id", scholid)
.addBodyParameter("person_name", personnameS)
.addBodyParameter("designation", designantionS)
.addBodyParameter("cell_number",personcellS)
.addBodyParameter("email",emailpersonS)
.addBodyParameter("whatsapp_number",whatsApppersonS)
.addBodyParameter("school_name",schoolNameS)
.addBodyParameter("postal_address",postalAdressS)
.addBodyParameter("city",cityS)
.addBodyParameter("tehsil",tehsilS)
.addBodyParameter("district",districtS)
.addBodyParameter("s_primary", priamryChecked)
.addBodyParameter("s_middle", middleChecked)
.addBodyParameter("s_high", highChecked)
.addBodyParameter("s_higher", hsChecked)
.addBodyParameter("principal_name", nameOfPrincipalS)
.addBodyParameter("p_contact_num",cellNoPrincipalS)
.addBodyParameter("p_email",emailPrincipalS)
.addBodyParameter("p_whatsapp_number",whatsAppPrincipalS)
.addBodyParameter("class", Class)
.addBodyParameter("rq_book", String.valueOf(ReadQuran))
.addBodyParameter("rqb_qty", String.valueOf(ReadQuranQty))
.addBodyParameter("fq_book", String.valueOf(FehamQuran))
.addBodyParameter("fqb_qty", String.valueOf(FehamQuranQty))
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String result = jsonObject.getString("result");
String message = jsonObject.getString("message");
if (result.equalsIgnoreCase("success")) {
Toast.makeText(FormStage5.this, "" + message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(FormStage5.this, formstage2submittedmsg.class);
startActivity(intent);
pDialog.dismiss();
} else/* (result.equalsIgnoreCase("0"))*/ {
Toast.makeText(FormStage5.this, ""+message, Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
} catch (JSONException e) {
pDialog.dismiss();
Toast.makeText(FormStage5.this, "Something Went Wrong , Try Again", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(FormStage5.this, "Please Check Your Internet Connection" + anError.toString(), Toast.LENGTH_LONG).show();
pDialog.hide();
}
});
The best way is to create a POJO class and set Array value, then pass it. It will automatically gets converted into JSON, if you are using retrofit with GSONConverter factory.
The accepted answer to this question talks about Retrofit and GSON, while the question is about Fast Android Networking. The accepted answer did not work for me.
I found that the only way to do this was to build the body myself and add it to the request with .addJSONObjectBody.
I wanted a body that looks like:
{
"roles": [
"customer-admin"
]
}
The final way I found which works is:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
JSONObject roles;
try {
roles = new JSONObject();
JSONArray rolesArr = new JSONArray();
rolesArr.put("customer-admin");
roles.put("roles", rolesArr);
} catch (JSONException e) {
// Make error toast here
return;
}
AndroidNetworking.post(url)
.addJSONObjectBody(roles)
.build()
pass the arrayname.toString() as a value

PHP if-else bodies both executing

I'm a beginner in PHP and i've got this code where both if and else parts are executed in the same "run". I know it's logically impossible but that's what I'm getting.
Here's my PHP Code:
<?php
require_once 'create_request_form.php';
$db = new create_request_form();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {
// receiving the post params
$rqTitle = $_POST['rqTitle'];
$rqMname = $_POST['rqMname'];
$rqUname = $_POST['rqUname'];
$rqBranch = $_POST['rqBranch'];
$rqText = $_POST['rqText'];
$rqMinPrice = $_POST['rqMinPrice'];
$rqMaxPrice = $_POST['rqMaxPrice'];
$rqImage = $_POST['rqImage'];
$rqCategory = $_POST['rqCategory'];
$rqDateTime = $_POST['rqDateTime'];
// check if there is a request with the same title
if ($db->checkReqTitle($rqTitle)) {
// Request already exists
$response["error"] = TRUE;
$response["error_msg"] = "Request already exists with the title: " . $rqTitle;
echo json_encode($response);
} else {
// create a new request
$request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);
if ($request) {
// request stored successfully
$response["error"] = FALSE;
$response["request"]["rqTitle"] = $request["rqTitle"];
$response["request"]["rqMname"] = $request["rqMname"];
$response["request"]["rqUname"] = $request["rqUname"];
$response["request"]["rqBranch"] = $request["rqBranch"];
$response["request"]["rqText"] = $request["rqText"];
$response["request"]["rqMinPrice"] = $request["rqMinPrice"];
$response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
$response["request"]["rqImage"] = $request["rqImage"];
$response["request"]["rqCategory"] = $request["rqCategory"];
$response["request"]["rqDateTime"] = $request["rqDateTime"];
echo json_encode($response);
} else {
// request failed to store
$response["error"] = TRUE;
$response["error_msg"] = "An error occurred while creating the request. Please try again.";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
The required behavior (storing data in the database) is all performed well but the $response I'm getting is the error string i've assigned to when a request title already exists instead of the JSON formatted array of the stored request (Both if and else bodies are executed but i get the result of if body as a response).
A screenshot of the $response using Postman to send the request:
A screenshot from my Samsung Galaxy Note 3:
I'm also using Galaxy Note 4 for testing and it just shows me a blank Toast message and doesn't start the intent(doesn't move to home screen).
So far the only possible explanation is that the script is being executed twice, however I can't find anywhere that called it a second time.
This is the java code responsible for sending a request with required paramters to the php script above.
private void storeRequest(final String rTitle, final String rMname, final String rUname,
final String rBranch, final String rText, final String rMinPrice,
final String rMaxPrice, final String imagePath, final String rCategory) {
// Tag used to cancel the request
String cancel_req_tag = "request";
//A progress dialog message to let the user know they are being registered
progressDialog.setMessage("Please wait while we add your request...");
showDialog();
//creating a StringRequest to send the registration info to the script
// at the server for processing
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REQUEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Request Response: " + response.toString());
hideDialog();
try { //json objects must be surrounded by try catch statement
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
// Launch home activity
Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(CreateRequestActivity.this,
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("rqTitle", rTitle);
params.put("rqText", rText);
params.put("rqMname", rMname);
params.put("rqUname", rUname);
params.put("rqBranch", rBranch);
params.put("rqMinPrice", rMinPrice);
params.put("rqMaxPrice", rMaxPrice);
params.put("rqImage", imagePath);
params.put("rqCategory", rCategory);
params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
Any ideas?
Thanks in advance!
So turns out the problem stemmed from the Java code and not PHP (poor PHP ;P). More accurately, Volley requests have a problem with request timeouts, especially when sending requests using POST method.
So what worked for me was adding this line right before adding the request to the queue:
strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
*Replace strReq with your request name. Basically what this line does is that it prevents volley from sending a duplicate request when the first request takes too long.
The original & more datailed answer:
The DefaultRetryPolicy.class's hasAttemptRemaining() class looks like this:
protected boolean hasAttemptRemaining() {
return this.mCurrentRetryCount <= this.mMaxNumRetries;
}
From what I can see, setting the maxNumRetries to 0 will still make that return true if it hasn't done a retry yet.
I fixed it with a
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0);
Source: Android Volley makes 2 requests to the server when retry policy is set to 0

Categories