데이터 구문 분석 오류 org.json.JSONException : 값 <br> <java.lang.String 유형의 테이블을 JSONObject로 변환 할 수 없습니다.

Luciano Santis

ListView에서 누른 항목에 따라 정보를 표시하려고합니다. 정보를 얻기 위해 HTTP GET 요청을 사용하고 있습니다.

ListView에서 항목 (프로필)을 클릭하면 응용 프로그램이 해당 프로필 이름을 가져오고 이에 따라 다음 활동에서 해당 프로필 정보를 표시해야하지만 작동하지 않고 계속 JSONException오류가 발생합니다. 나는 원인을 모르거나 이것을 달성하기위한 나의 접근 방식이 잘못된 경우 도움이 될 것입니다. 감사.

여기에서 프로필 이름을 다음 활동으로 보냅니다 (이 클래스에는 더 많은 코드가 있지만이 질문과 관련이 없음).

공용 클래스 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);

        }

    });

}

프로필에서 세부 정보를 얻으려는 활동입니다.

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();
            }
        }

이것은 내 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;

}
}

이것은 내 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);
}
?>

다음은 오류 로그입니다.

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)

도움을 주셔서 감사합니다.

Luciano Santis

오류를 수정했는데 문제는 PHP 파일과이 줄의 연결과 관련이 있습니다. require_once DIR . '/DB_Connect.php';.

Log.d ( "JSON Parser", json); 이클립스에서 logcat의 PHP 오류를 읽으려면 스트림을 열지 못했다고 계속 말했습니다. 그런 파일이나 디렉토리가 없으며 열리지 않으면 필요한 파일을 내 PHP 파일과 동일한 디렉토리에 넣고 PHP 파일에 넣습니다. 이 줄을 바꿨 습니다 : require_once _ DIR _. '/DB_Connect.php'; 이것으로 : require_once 'DB_Connect.php ';

누군가가 비슷한 일을하려고 할 때 자바 코드는 완벽합니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관