简体   繁体   English

解析数据org.json.JSONException时出错:值<br>

[英]Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject

I'm trying to display information depending on the item pressed in a ListView. 我试图根据ListView中按下的项目显示信息。 I'm using a HTTP GET request to get the information. 我正在使用HTTP GET请求来获取信息。

When you click on an item (profile) in the ListView the application gets that profile name and depending on that it should display that profile's information in the next activity but that's not working and I keep getting a JSONException error. 当您在ListView中单击某个项目(配置文件)时,应用程序将获取该配置文件名称,并根据该名称在下一个活动中显示该配置文件的信息,但这不起作用,并且我不断收到JSONException错误。 I don't know what is causing or if my approach to achieve this is wrong, any help would be great. 我不知道是什么原因造成的,或者如果我实现此目标的方法有误,那么任何帮助都会很大。 Thanks. 谢谢。

Here I'm sending the profile's name to the next activity (This class has more code but it's not relevant for this question): 在这里,我将个人资料的名称发送到下一个活动(此类具有更多代码,但与该问题无关):

public class EditProfiles extends BaseListActivity implements GetProfilesListener{ 公共类EditProfiles扩展BaseListActivity实现GetProfilesListener {

TextView errorMessage;
String email;

private static final String TAG_PNAME = "profilename";


/**
 * Called when activity is first created.
 */
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profiles);


ListView list = getListView();
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,                   
                int position, long id) {
            // getting values from selected ListItem
            String profilename = ((TextView) view.findViewById(R.id.editProfiles_profile_name)).getText()
                    .toString();

            Intent in = new Intent(getApplicationContext(), EditSingleProfile.class);

            // sending profilename to next activity
            in.putExtra(TAG_PNAME, profilename);

            // Starts activity 
            startActivity(in);

        }

    });

}

This is the activity where I want to get the details from the profile: 这是我要从配置文件中获取详细信息的活动:

public class EditSingleProfile extends BaseViewEditProfile{

Spinner inputType;
EditText inputName;
EditText inputAge;
EditText inputBreed;
EditText inputAbout;
ImageView selectPicture;
Button change;
TextView message;

//Json node names.
private static final String TAG_SUCCESS = "success";
private static final String TAG_PROFILE = "profile";
private static final String TAG_PNAME = "profilename";
private static final String TAG_PAGE = "petage";
private static final String TAG_BREED = "petbreed";
private static final String TAG_ABOUT = "profileabout";

//JSON parser class
JSONParser jsonParser = new JSONParser();

// single profile url
private static final String url_profile_details = "http://gatoandroidapp.comeze.com/profile_details.php";

//Create field SELECT_PICTURE to be used in the class.
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
String pimage;
String profilename;

    /**
     * Called when activity is created.
     */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile_view);  
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

        // getting profile details from intent
        Intent i = getIntent();

        // getting profile name from intent
        profilename = i.getStringExtra(TAG_PNAME);

        // Sets view title.
        this.setTitle(profilename);

        // Get profile's details in Background Thread
        new GetProfiles().execute();

               /**
         * Background AsyncTask to Get profile details.
         */
        class GetProfiles extends AsyncTask<String, String, String> {

            // Progress Dialog
            private ProgressDialog pDialog;
            /**
             * Before starting background thread Show Progress Dialog
             */
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(EditSingleProfile.this);
                pDialog.setMessage("Loading profile details...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            /**
             * Getting profile details in background thread
             */
            protected String doInBackground(String... params) {

                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        // Check for success tag
                        int success;
                        try {
                            // Building Parameters
                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                            params.add(new BasicNameValuePair("profilename", profilename));

                            // getting profile details by making HTTP request
                            JSONObject json = jsonParser.makeHttpRequest(
                                    url_profile_details, "GET", params);

                            // check your log for json response
                            Log.d("Single Profile Details", json.toString());

                            // json success tag
                            success = json.getInt(TAG_SUCCESS);
                            if (success == 1) {
                                // successfully received product details
                                JSONArray profileObj = json
                                        .getJSONArray(TAG_PROFILE); // JSON Array

                                // get first profile object from JSON Array
                                JSONObject profile = profileObj.getJSONObject(0);

                                inputName = (EditText) findViewById(R.id.editProfile_profileName_editText);
                                inputAge = (EditText) findViewById(R.id.editProfile_age_editText);
                                inputBreed = (EditText) findViewById(R.id.editProfile_breed_editText);
                                inputAbout = (EditText) findViewById(R.id.editProfile_about_editText);

                                // display product data in EditText
                                inputName.setText(profile.getString(TAG_PNAME));
                                inputAge.setText(profile.getString(TAG_PAGE));
                                inputBreed.setText(profile.getString(TAG_BREED));
                                inputAbout.setText(profile.getString(TAG_ABOUT));

                            }else{
                                // profile with name not found
                            }
                        } 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 got all details
                pDialog.dismiss();
            }
        }

This is my JSON parser: 这是我的JSON解析器:

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 mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method.equalsIgnoreCase("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.equalsIgnoreCase("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 my PHP code: 这是我的PHP代码:

<?php

/*
 * Gets single profile details
 * A profile is identified by profile name (pname)
 */

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


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

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

// check for post data
if (isset($_GET["profilename"])) {
    $profilename = $_GET['profilename'];

    // get a profile from profiles table
    $result = mysql_query("SELECT * FROM profiles WHERE profilename = $profilename");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $profile = array();
            $profile["profilename"] = $result["profilename"];
            $profile["petage"] = $result["petage"];
            $profile["petbreed"] = $result["petbreed"];
            $profile["profileabout"] = $result["profileabout"];

            // success
            $response["success"] = 1;

            // user node
            $response["profile"] = array();

            array_push($response["profile"], $profile);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no profile found
            $response["success"] = 0;
            $response["message"] = "No profile found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no profile found
        $response["success"] = 0;
        $response["message"] = "No profile found";

        // echo no users JSON
        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);
}
?>

This is the error log: 这是错误日志:

04-07 16:22:00.156: E/JSON Parser(15588): Error parsing data org.json.JSONException: Value <br><table of type java.lang.String cannot be converted to JSONObject
04-07 16:22:00.156: D/AndroidRuntime(15588): Shutting down VM
04-07 16:22:00.156: W/dalvikvm(15588): threadid=1: thread exiting with uncaught exception (group=0x4123f908)
04-07 16:22:00.159: E/AndroidRuntime(15588): FATAL EXCEPTION: main
04-07 16:22:00.159: E/AndroidRuntime(15588): java.lang.NullPointerException
04-07 16:22:00.159: E/AndroidRuntime(15588):    at com.gmail.lucsantisf.software_project.views.EditSingleProfile$GetProfiles$1.run(EditSingleProfile.java:249)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at android.os.Handler.handleCallback(Handler.java:615)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at android.os.Looper.loop(Looper.java:153)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at android.app.ActivityThread.main(ActivityThread.java:5006)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at java.lang.reflect.Method.invokeNative(Native Method)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at java.lang.reflect.Method.invoke(Method.java:511)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
04-07 16:22:00.159: E/AndroidRuntime(15588):    at dalvik.system.NativeStart.main(Native Method)

Thanks for any help. 谢谢你的帮助。

Well I fixed the error, the problem had to do with the connection in the PHP file and this line : require_once DIR . 好吧,我修复了错误,问题与PHP文件中的连接以及以下行有关:require_once DIR '/DB_Connect.php';. '/DB_Connect.php' ;.

I used Log.d("JSON Parser", json ); 我使用了Log.d(“ JSON Parser”,json); to read the PHP error in logcat in eclipse and it kept telling me that failed to open stream: no such file or directory and fail opening requires so I put the file required in the same directory as my php file and in the php file and I replaced this line: require_once _ DIR _ . 读取eclipse中logcat中的PHP错误,它一直告诉我无法打开流:没有这样的文件或目录,也无法打开失败,所以我将所需的文件与php文件放在同一目录中,并将其放在php文件中,替换此行: require_once _ DIR _。 '/DB_Connect.php'; '/DB_Connect.php'; with this: require_once 'DB_Connect.php '; 与此:require_once 'DB_Connect.php';

The java code is perfect in case that someone is trying to do something similar. 如果有人尝试做类似的事情,那么Java代码是完美的。

It looks like the response you are getting is not valid JSON. 您收到的响应似乎是无效的JSON。 The Value <br><table of type java.lang.String indicates you are getting HTML code as the response which it cannot map to your objects. Value <br><table of type java.lang.StringValue <br><table of type java.lang.String表示您正在获取HTML代码作为响应,它无法映射到您的对象。

Try doing a 尝试做一个

Log.d("JSON Parser", json);

Just before your comment // try parse the string to a JSON object 就在您的评论之前// try parse the string to a JSON object

With Logcat output the url you are requesting and try to visualize the response, and pay attention to the symbols and tags like < />, they should be escaped. 使用Logcat输出您所请求的URL并尝试可视化响应,并注意符号和标记(如</>),应将其转义。 May be the parser has encounter an array and you are telling to convert to an object. 可能是解析器遇到了一个数组,并且您正在告诉要转换为对象。

this error can be because when you execute PHP code appear this error: 该错误可能是因为执行PHP代码时出现此错误:

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in

And it gets this error through JSON: 它通过JSON收到此错误:

<br>Deprecated</br>...

So, if you put in your php code something like this: 因此,如果您在php代码中输入如下内容:

error_reporting(E_ALL ^ E_DEPRECATED);

This error will be fixed. 该错误将得到解决。

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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x074AZshIvCm48LxtUkjB5ywr4rE8WcGZXm9LhrMeMOE8oz+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.

相关问题 解析数据org.json.JSONException时出错:值 - Error parsing data org.json.JSONException: Value <!— 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时出错:类型java.lang.String无法转换为JSONObject - Error parsing data org.json.JSONException: 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> 我记录了图像响应,这就是我得到的:</p><pre> Strings: /9j/4AAQSkZJRgAB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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 解析数据org.json.JSONException时出错:值 - Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray 解析数据org.json.JSONException的另一个错误:值 - Another Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 解析数据时出错 org.json.JSONException: Value<html> java.lang.String 类型无法转换为 JSONObject - Error parsing data org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:类型为java.lang.String的值db_connect.php无法转换为JSONObject - Error parsing data org.json.JSONException: Value db_connect.php of type java.lang.String cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM