简体   繁体   English

Volley 的 JsonObjectRequest 给出“org.json.JSONException: Value

[英]Volley's JsonObjectRequest gives "org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject" exception

Expected JSON to be send to server预期将 JSON 发送到服务器

{"syncsts":
          [
          {"status":"1","Id":"9"},
          {"status":"1","Id":"8"}
          ]
}

Expected way of retrieval of JSON Object on the server在服务器上检索 JSON 对象的预期方式

$arr = $_POST['syncsts']

(I think ) (我认为 )

$arr should have [{"status":"1","Id":"9"},{"status":"1","Id":"8"}] $arr 应该有 [{"status":"1","Id":"9"},{"status":"1","Id":"8"}]

Volley JsonObjectRequest Function along with JSON style parameter Volley JsonObjectRequest 函数以及 JSON 样式参数

public void updateMySQLSyncSts(final ArrayList<HashMap<String, String>> lt){
    JSONArray arr = new JSONArray(lt);
    JSONObject js = new JSONObject();
    try {
        js.put("syncsts",arr);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.i("MainActivity",js.toString());
    String url = "http://10.0.3.2/insight/mysqlsqlitesync/updatesyncsts.php";
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, js,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("MainActivity",error.getMessage());
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    MySingleton.getInstance(this).addToRequestQueue(req);
}

PHP script PHP脚本

/**
* Updates Sync status of Users
*/
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions(); 
//Get JSON posted by Android Application
$json = $_POST["syncsts"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->updateSyncSts($data[$i]->Id,$data[$i]->status);
//Based on inserttion, create JSON response
if($res){
    $b["id"] = $data[$i]->Id;
    $b["status"] = 'yes';
    array_push($a,$b);
}else{
    $b["id"] = $data[$i]->Id;
    $b["status"] = 'no';
    array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);

I am using the above function to send JSON formatted parameter along with my post request.我正在使用上述函数将 JSON 格式的参数与我的帖子请求一起发送。 when $_POST["syncsts"] line in PHP script executed the following error is thrown.当 PHP 脚本中的 $_POST["syncsts"] 行执行时,抛出以下错误。

JSONObject toString() and the Error as shown in the logcat JSONObject toString() 和错误如 logcat 中所示

10-04 21:59:23.523 2062-2062/? I/MainActivity: {"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}

10-04 21:59:23.767 2062-2062/? I/MainActivity: org.json.JSONException: Value    <br of type java.lang.String cannot be converted to JSONObject

PHP script to show what is received on server (Debugging) PHP 脚本显示在服务器上收到的内容(调试)

file_put_contents('test.txt', file_get_contents('php://input'));
$arr = $_POST['syncsts'];
echo $arr;
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo json_encode($age);

test.txt测试.txt

{"syncsts":[{"status":"1","Id":"9"},{"status":"1","Id":"8"}]}

Please tell me what is wrong in the JSON format which I am trying to send to our server which was generated in Java.请告诉我我试图发送到我们用 Java 生成的服务器的 JSON 格式有什么问题。

it looks like the error is at the responce from server. 看起来错误是来自服务器的响应。 the onResponse(JSONObject response) expects the results to be proper jsonobject. onResponse(JSONObject response)期望结果为正确的jsonobject。 check if there is any other elements being displayed after echoing the result(such as an error message). 在回显结果之后检查是否还有其他元素正在显示(例如错误消息)。 you can check it from browser using a chrome extension called postman using which you can try sending POST and GET requests manually to server 您可以使用称为postman的chrome扩展程序从浏览器中进行检查,您可以使用该扩展程序尝试将POST和GET请求手动发送到服务器

<?php

// array for JSON response
$response = array();

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

$email= $_POST['email'];
$password= $_POST['password'];

// include db connect class
 require_once 'DB_Connect.php';

// connecting to db
$db = new DB_CONNECT();

// mysql update row with matched pid
  $result = mysql_query("UPDATE users SET encrypted_password = 
  '$password'  WHERE email = $email");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
    // successfully updated
   $response["error"] = FALSE;
    $response["message"] = "Product successfully updated";

    // echoing JSON response
    echo json_encode($response);
} else {
    // no product found
    $response["error"] = TRUE;
    $response["message"] = "No product found";

    // echo no users JSON
    echo json_encode($response);
 }
 } else {
// required field is missing
$response["error"] = TRUE;
$response["message"] = "Required field(s) is missing";

 // echoing JSON response
echo json_encode($response);
}
------------------------------------------------------------------------

android code



   public class ChangePass extends AppCompatActivity {
   private static final String TAG = ChangePass.class.getSimpleName();
   private Button btn_ChangePass;
   private EditText ed_email,ed_pass;
    private ProgressDialog pDialog;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_change_pass);
    btn_ChangePass=(Button)findViewById(R.id.btchangepass);
    ed_email=(EditText)findViewById(R.id.email);
    ed_pass=(EditText)findViewById(R.id.newpass);
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

   btn_ChangePass.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    String email=ed_email.getText().toString();
    String password=ed_pass.getText().toString();
    if (!email.isEmpty() && !password.isEmpty()) {
        // login user
        changePassword(email, password);
    } else {
        // Prompt user to enter credentials
        Toast.makeText(getApplicationContext(),
                "Please enter the credentials!", Toast.LENGTH_LONG)
                .show();
    }

  }
  });

   }
  private void changePassword(final String email,final String password)
   {
    String tag_string_req = "req_update";

    pDialog.setMessage("Updating ...");
    showDialog();
    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_UPDATE, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error)
                {
                    Intent intent = new Intent(ChangePass.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else
                {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("message");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
         Toast.makeText(getApplicationContext(),
         "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
       }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error)
        {
            Log.e(TAG, "Response Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
        }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            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 (!pDialog.isShowing())
        pDialog.show();
    }

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

   }



  ---------------------------------------------------------------------
error
         org.json.JSONException: 
       Value <br of type java.lang.String cannot be converted to JSONObject





      please help me guys... 
                    this code code is for updating password

Android Studio org.json.JSONException:值<br of type java.lang.String cannot be converted to JSONObject< div><div id="text_translate"><p> 我正在尝试使用 volley 将一些数据发布到服务器。</p><p> 问题似乎与编码的字符串图像有关。</p><p> 在这条线上</p><pre> String name = namefield.getText().toString(); String age = agefield.getText().toString(); String gender = genderfield.getText().toString(); String color = colorfield.getText().toString(); String notes = notesfield.getText().toString(); String images = encodeImage(bitmap); updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);</pre><p> 如果我将图像更改为空字符串</p><pre> updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), "");</pre><p> 然后比数据发送到服务器,这就是我知道图像是问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074AZshIvCm48LxtUkjB5ywr4rE8WcGZXm9LhrMeMOE8oz+VODhwzV4qw 9DEuMnNr93N0qlJrm1h7NST0nBSTUurD5bmuKwdTG4bLpckUuf3oaW5m2256x1unKSdrtJ3cj78o r5J/t/8Abj/6Jp+zz/4cDx1/8y1H9v8A7cf/AETT9nn/AMOB46/+ZavtTlPraivnf4Q/FbXfGmt+ MfAPxA8GHwH8Q/A1npF/rOk2urrrvh2+0vXGuBoetaPrXlx70P8AZLK0MqLLFIGZg0jOR9EUAFFF FAHE+C/+RW8Nf9i/o/8A6aa65/8AVj8f/Qq5HwX/AMit4a/7F/R//TTXXP8A6sfj/wChVw4X/dZ/ L/0k4cL/ALrP5f8ApJYryz4p/Cf4WfHL4c+K/hT8ZfA3hz4j/DjxjY/2b4w8E+K9Ii1Tw1renGUa o0OsaPcKysDLGrEP87TFC6szmOvU6+Wv2wPCn7R3jv8AZf8AjV4I/ZI+IHg74Y/tE+J/B9/pHwk+ IPjizEvhrwh4r1FmB13XIf8AhFfGDEQaMdRMf/FK3UgumjZUSRVlHcdx/Or/AMFfv2ntN+Ivh6D/ AIN6f+CV3ws8N+LPj58VvCWk/Dz4p2XhbTY7D4PfsffAG3fSNY1ttdIUeH9A1658Py5twhL+DoZA yAfEifwPBXxB/wAF3f2U9B/Yk/4J4f8ABDn9huLxBc+Ivg78O/2wPAXgr4la9eLDpum+LNRJn1jW tZ1qONtqxzHXfHM0ZbDojudqvH5VeifsXf8ABGf/AIOKP2B7D4myfs//ALX3/BOa18V/F7xXqPjL 4mfE/wAceFPin8RPi1441WSSWTGu+OPEn7P7+ILi3eWSSYWyMoS4lMrSedtdv2</pre><p> 而其他数据响应正常,例如:</p><pre> Strings: red</pre><p> logcat 说问题出在这里:</p><pre> try { JSONObject jsonObject = new JSONObject(result); Log.i("Check", result);</pre><p> 以下是相关代码:</p><pre> public void updatedetails(final String name, final String age, final String gender, final String color, final String notes, final String owner, final String id, final String pet_image) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setMessage("Updating pet details"); progressDialog.show(); try { String url = "https://happy-paws.co.za/dogwalking/apis/v1/pet/update_pet.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { String result = response.toString(); // Log.d("zzzz","res "+result); Toast.makeText(update.this, response, Toast.LENGTH_SHORT).show(); getDataResponse1(result); Log.i("Check", result); Log.i("Check", response); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(update.this, error.getMessage(), Toast.LENGTH_SHORT).show(); Log.d("TAG", error.getMessage()); } }) { @Override public byte[] getBody() throws com.android.volley.AuthFailureError { String str = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"gender\":\"" + gender + "\",\"color\":\"" + color + "\",\"notes\":\"" + notes + "\",\"owner\":\"" + owner + "\",\"id\":\"" + id + "\",\"pet_image\":\"" + pet_image + "\"}"; return str.getBytes(); } @Override protected Map&lt;String, String&gt; getParams() { Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); // params.put("email",email); // params.put("password",password); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } catch (Exception e) { //App.handleUncaughtException(e); } progressDialog.dismiss(); } public void getDataResponse1(String result) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setMessage("Please Wait....."); progressDialog.show(); try { JSONObject jsonObject = new JSONObject(result); Log.i("Check", result); JSONObject current = jsonObject.getJSONObject(result); String message = current.getString("message"); String name = jsonObject.isNull("name")? null: jsonObject.getString("name"); String age = jsonObject.isNull("age")? null: jsonObject.getString("age"); String gender = jsonObject.isNull("gender")? null: jsonObject.getString("gender"); String notes = jsonObject.isNull("notes")? null: jsonObject.getString("notes"); String color = jsonObject.isNull("color")? null: jsonObject.getString("color"); // String android_status=jsonObject.getString("android_status"); if (message.equals("Pet was updated.")) { Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show(); // updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), pet_image); } else { Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } progressDialog.dismiss(); } private void selectImage(Context context) { final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Choose your profile picture"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals("Take Photo")) { Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePicture, 0); } else if (options[item].equals("Choose from Gallery")) { Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pickPhoto, 1); } else if (options[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode:= RESULT_CANCELED) { switch (requestCode) { case 0. if (resultCode == RESULT_OK &amp;&amp; data.= null) { bitmap = (Bitmap) data;getExtras().get("data"); profilepic;setImageBitmap(bitmap); encodeImage(bitmap): } break. case 1. if (resultCode == RESULT_OK) { bitmap = (Bitmap) data;getExtras().get("data"); Uri selectedImage = data.getData(); try { InputStream inputStream = getContentResolver().openInputStream(selectedImage); bitmap = BitmapFactory.decodeStream(inputStream); profilepic;setImageBitmap(bitmap). encodeImage(bitmap); // Glide.clear(profilepic). } catch (FileNotFoundException e) { Toast,makeText(update,this. "Pet added succesfully". Toast;LENGTH_SHORT);show(); } break. } } } } public String encodeImage(Bitmap bitmap) { ByteArrayOutputStream ba = new ByteArrayOutputStream(). bitmap.compress(Bitmap,CompressFormat,JPEG; 100. ba); byte[] imagebyte = ba.toByteArray(). encode = android.util,Base64.encodeToString(imagebyte; Base64;DEFAULT); return encode; }</pre><p> 然后我提交的地方:</p><pre> updatebutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = namefield.getText().toString(); String age = agefield.getText().toString(); String gender = genderfield.getText().toString(); String color = colorfield.getText().toString(); String notes = notesfield.getText().toString(); String images = encodeImage(bitmap); updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images); Log.d("Strings",images ); Log.d("Strings",color );</pre></div> - Android Studio org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Volley的JsonObjectRequest提供了“ org.json.JSONException:值 - Volley's JsonObjectRequest gives “org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject” exception volley.parsererror:org.json.JSONException:类型java.lang.string的值br不能转换为JSONObject - volley.parsererror:org.json.JSONException: value br of type java.lang.string cannot be converted to JSONObject 错误。 org.json.JSONException:值 - error. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值 - org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject (Andriod Studio) 遇到“ org.json.JSONException:值 - encountered “org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject” Android Studio org.json.JSONException:值<br of type java.lang.String cannot be converted to JSONObject< div><div id="text_translate"><p> 我正在尝试使用 volley 将一些数据发布到服务器。</p><p> 问题似乎与编码的字符串图像有关。</p><p> 在这条线上</p><pre> String name = namefield.getText().toString(); String age = agefield.getText().toString(); String gender = genderfield.getText().toString(); String color = colorfield.getText().toString(); String notes = notesfield.getText().toString(); String images = encodeImage(bitmap); updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);</pre><p> 如果我将图像更改为空字符串</p><pre> updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), "");</pre><p> 然后比数据发送到服务器,这就是我知道图像是问题的方式。</p><p> 我记录了图像响应,这就是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8WcGZXm9LhrMeMOE8oz+VODhwzV4qw 9DEuMnNr93N0qlJrm1h7NST0nBSTUurD5bmuKwdTG4bLpckUuf3oaW5m2256x1unKSdrtJ3cj78o r5J/t/8Abj/6Jp+zz/4cDx1/8y1H9v8A7cf/AETT9nn/AMOB46/+ZavtTlPraivnf4Q/FbXfGmt+ MfAPxA8GHwH8Q/A1npF/rOk2urrrvh2+0vXGuBoetaPrXlx70P8AZLK0MqLLFIGZg0jOR9EUAFFF FAHE+C/+RW8Nf9i/o/8A6aa65/8AVj8f/Qq5HwX/AMit4a/7F/R//TTXXP8A6sfj/wChVw4X/dZ/ L/0k4cL/ALrP5f8ApJYryz4p/Cf4WfHL4c+K/hT8ZfA3hz4j/DjxjY/2b4w8E+K9Ii1Tw1renGUa o0OsaPcKysDLGrEP87TFC6szmOvU6+Wv2wPCn7R3jv8AZf8AjV4I/ZI+IHg74Y/tE+J/B9/pHwk+ IPjizEvhrwh4r1FmB13XIf8AhFfGDEQaMdRMf/FK3UgumjZUSRVlHcdx/Or/AMFfv2ntN+Ivh6D/ AIN6f+CV3ws8N+LPj58VvCWk/Dz4p2XhbTY7D4PfsffAG3fSNY1ttdIUeH9A1658Py5twhL+DoZA yAfEifwPBXxB/wAF3f2U9B/Yk/4J4f8ABDn9huLxBc+Ivg78O/2wPAXgr4la9eLDpum+LNRJn1jW tZ1qONtqxzHXfHM0ZbDojudqvH5VeifsXf8ABGf/AIOKP2B7D4myfs//ALX3/BOa18V/F7xXqPjL 4mfE/wAceFPin8RPi1441WSSWTGu+OPEn7P7+ILi3eWSSYWyMoS4lMrSedtdv2</pre><p> 而其他数据响应正常,例如:</p><pre> Strings: red</pre><p> logcat 说问题出在这里:</p><pre> try { JSONObject jsonObject = new JSONObject(result); Log.i("Check", result);</pre><p> 以下是相关代码:</p><pre> public void updatedetails(final String name, final String age, final String gender, final String color, final String notes, final String owner, final String id, final String pet_image) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setMessage("Updating pet details"); progressDialog.show(); try { String url = "https://happy-paws.co.za/dogwalking/apis/v1/pet/update_pet.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { String result = response.toString(); // Log.d("zzzz","res "+result); Toast.makeText(update.this, response, Toast.LENGTH_SHORT).show(); getDataResponse1(result); Log.i("Check", result); Log.i("Check", response); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(update.this, error.getMessage(), Toast.LENGTH_SHORT).show(); Log.d("TAG", error.getMessage()); } }) { @Override public byte[] getBody() throws com.android.volley.AuthFailureError { String str = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"gender\":\"" + gender + "\",\"color\":\"" + color + "\",\"notes\":\"" + notes + "\",\"owner\":\"" + owner + "\",\"id\":\"" + id + "\",\"pet_image\":\"" + pet_image + "\"}"; return str.getBytes(); } @Override protected Map&lt;String, String&gt; getParams() { Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); // params.put("email",email); // params.put("password",password); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } catch (Exception e) { //App.handleUncaughtException(e); } progressDialog.dismiss(); } public void getDataResponse1(String result) { final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setMessage("Please Wait....."); progressDialog.show(); try { JSONObject jsonObject = new JSONObject(result); Log.i("Check", result); JSONObject current = jsonObject.getJSONObject(result); String message = current.getString("message"); String name = jsonObject.isNull("name")? null: jsonObject.getString("name"); String age = jsonObject.isNull("age")? null: jsonObject.getString("age"); String gender = jsonObject.isNull("gender")? null: jsonObject.getString("gender"); String notes = jsonObject.isNull("notes")? null: jsonObject.getString("notes"); String color = jsonObject.isNull("color")? null: jsonObject.getString("color"); // String android_status=jsonObject.getString("android_status"); if (message.equals("Pet was updated.")) { Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show(); // updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), pet_image); } else { Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } progressDialog.dismiss(); } private void selectImage(Context context) { final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"}; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Choose your profile picture"); builder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals("Take Photo")) { Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePicture, 0); } else if (options[item].equals("Choose from Gallery")) { Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pickPhoto, 1); } else if (options[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode:= RESULT_CANCELED) { switch (requestCode) { case 0. if (resultCode == RESULT_OK &amp;&amp; data.= null) { bitmap = (Bitmap) data;getExtras().get("data"); profilepic;setImageBitmap(bitmap); encodeImage(bitmap): } break. case 1. if (resultCode == RESULT_OK) { bitmap = (Bitmap) data;getExtras().get("data"); Uri selectedImage = data.getData(); try { InputStream inputStream = getContentResolver().openInputStream(selectedImage); bitmap = BitmapFactory.decodeStream(inputStream); profilepic;setImageBitmap(bitmap). encodeImage(bitmap); // Glide.clear(profilepic). } catch (FileNotFoundException e) { Toast,makeText(update,this. "Pet added succesfully". Toast;LENGTH_SHORT);show(); } break. } } } } public String encodeImage(Bitmap bitmap) { ByteArrayOutputStream ba = new ByteArrayOutputStream(). bitmap.compress(Bitmap,CompressFormat,JPEG; 100. ba); byte[] imagebyte = ba.toByteArray(). encode = android.util,Base64.encodeToString(imagebyte; Base64;DEFAULT); return encode; }</pre><p> 然后我提交的地方:</p><pre> updatebutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = namefield.getText().toString(); String age = agefield.getText().toString(); String gender = genderfield.getText().toString(); String color = colorfield.getText().toString(); String notes = notesfield.getText().toString(); String images = encodeImage(bitmap); updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images); Log.d("Strings",images ); Log.d("Strings",color );</pre></div> - Android Studio org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject W / System.err:org.json.JSONException:值 - W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:值<br> - Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject com.android.volley.parseerror org.json.json异常值类型为java.lang.String的无法转换为JSONObject - com.android.volley.parseerror org.json.jsonexception value yes of type java.lang.String cannot be converted to JSONObject Volley库W / System.err:org.json.JSONException:类型为java.lang.String的Value Connected无法转换为JSONObject - Volley library W/System.err: org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM