Android JSON 구문 분석이 null을 반환합니다.

올리다.

PHP 및 JSON 파일을 사용하여 MYSQL을 Android 응용 프로그램과 연결하려고 시도하고 있는데, 현재 직면하고있는 문제는 JSONParser 클래스가 항상 null을 반환한다는 것입니다. JSON 파일을 볼 수 있고 유효하기 때문에 이유를 모르겠습니다.

내 코드에는 두 가지 예외가 있습니다. 첫 번째는 다음과 같습니다.

        12-08 09:17:43.486 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from GradienCache
        12-08 09:17:43.498 29666-29666/alharbi.astrong texttheer.gym_managment_system E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384
        12-08 09:17:43.518 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
        12-08 09:17:43.522 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384

두 번째는 다음과 같습니다.

12-08 09:17:46.526 29666-29740/alharbi.atheer.gym_managment_system E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
12-08 09:17:46.526 29666-29740/alharbi.atheer.gym_managment_system E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 

이것은 문제를 포함하는 클래스입니다

public class ViewInfo extends AppCompatActivity {
    JSONParser jsonParser;
    ProgressDialog progressDialog;
    int value;
    String[] names,emails,levels,ids, weights,hieghts,genders,bds,addresses,ages,phones;
    ListView listView2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_info);
        jsonParser=new JSONParser();
        listView2=(ListView)findViewById(R.id.listView2);

        new DisplayViewInfo().execute();
    }




    class DisplayViewInfo extends AsyncTask<String,String,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog=new ProgressDialog(ViewInfo.this);
            progressDialog.setTitle("Wait...");
            progressDialog.show();
        }




        @Override
        protected String doInBackground(String... strings) {

          List<NameValuePair> list= new ArrayList<NameValuePair>();
          //  HashMap<String,String> list = new HashMap<>();


            // jsonObject=jsonParser.makeHttpRequest("http://192.168.56.1/myapp/ViewInfo.php","POST",list);
           JSONObject jsonObject=jsonParser.makeHttpRequest("http://192.168.56.1/myapp/ViewInfo.php", "POST", list);


            try{
                if(jsonObject!=null && !jsonObject.isNull("value")){


                    value=jsonObject.getInt("value");
                    JSONArray jsonArray=jsonObject.getJSONArray("Customers");
                    names=new String[jsonArray.length()];
                    emails=new String[jsonArray.length()];
                    phones=new String[jsonArray.length()];
                    ids=new String[jsonArray.length()];
                    weights=new String[jsonArray.length()];
                    hieghts=new String[jsonArray.length()];
                    genders=new String[jsonArray.length()];
                    levels=new String[jsonArray.length()];
                   ages=new String[jsonArray.length()];
                    addresses=new String[jsonArray.length()];
                    bds=new String[jsonArray.length()];
                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject objcet=jsonArray.getJSONObject(i);
                        ids[i]=objcet.getString("Customer_ID");
                        names[i]=objcet.getString("Name");
                        emails[i]=objcet.getString("Email");
                        phones[i]=objcet.getString("Phone_number");
                        weights[i]=objcet.getString("Weight");
                        hieghts[i]=objcet.getString("Height");
                        genders[i]=objcet.getString("Gender");
                        levels[i]=objcet.getString("Level");
                        ages[i]=objcet.getString("age");
                        addresses[i]=objcet.getString("address");
                        bds[i]=objcet.getString("Date_of_birth");


                    }
                }else{
                    value=0;
                }

            }catch (Exception e){
                Log.d("ERROR", e.getMessage());
            }

            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(value==1){
                Toast.makeText(getApplicationContext(), "Done...", Toast.LENGTH_LONG).show();
                ArrayAdapter<String> adapter=new ArrayAdapter<String>(ViewInfo.this,android.R.layout.simple_list_item_1,android.R.id.text1,names);
                listView2.setAdapter(adapter);
            }else if(value==0)
                Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show();
            else Toast.makeText(getApplicationContext(),"OUT...",Toast.LENGTH_LONG).show();

            progressDialog.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.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method.equals("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;

}

}

누구든지 나를 도울 수 있습니까? 이 오류 때문에 며칠 동안 걸림돌이되었습니다.

NoChinDeluxe

JSON 오류의 모양에서 보면 유효한 응답을받지 못하는 것 같고 응답 문자열이 비어 있습니다. 이런 일이 발생하면 일반적으로 웹 서비스 호출의 html 응답 코드와 빌드 후 실제 문자열을 모두 확인합니다. 이것은 웹 서비스가 문제인지 또는 웹 서비스 호출이 문제인지 식별하는 데 도움이됩니다.

제가 언급해야 할 또 다른 사항은 웹 호출에 더 이상 사용되지 않는 코드를 사용하고 있다는 것입니다. 아파치 http 코드는 Android 프레임 워크에서 제거되었으므로 HttpURLConnection대신 웹 서비스 호출에을 사용해야합니다 .

저는 오늘 기분이 꽤 좋으며 도움이 되었으니이 JSON 응답을 얻기 위해 사용해야하는 코드를 알려 드리겠습니다. :)

//The JSON we will get back as a response from the server
JSONObject jsonResponse = null;

//Http connections and data streams
URL url;
HttpURLConnection httpURLConnection = null;
OutputStreamWriter outputStreamWriter = null;

try {

    //open connection to the server
    url = new URL("your_url_to_web_service");
    httpURLConnection = (HttpURLConnection) url.openConnection();

    //set request properties
    httpURLConnection.setDoOutput(true); //defaults request method to POST
    httpURLConnection.setDoInput(true);  //allow input to this HttpURLConnection
    httpURLConnection.setRequestProperty("Content-Type", "application/json"); //header params
    httpURLConnection.setRequestProperty("Accept", "application/json"); //header params
    httpURLConnection.setFixedLengthStreamingMode(jsonToSend.toString().getBytes().length); //header param "content-length"

    //open output stream and POST our JSON data to server
    outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
    outputStreamWriter.write(jsonToSend.toString());
    outputStreamWriter.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination

    //prepare input buffer and get the http response from server
    StringBuilder stringBuilder = new StringBuilder();
    int responseCode = httpURLConnection.getResponseCode();

    //Check to make sure we got a valid status response from the server,
    //then get the server JSON response if we did.
    if(responseCode == HttpURLConnection.HTTP_OK) {

        //read in each line of the response to the input buffer
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }

        bufferedReader.close(); //close out the input stream

    try {
        //Copy the JSON response to a local JSONObject
        jsonResponse = new JSONObject(stringBuilder.toString());
    } catch (JSONException je) {
        je.printStackTrace();
    }

} catch (IOException ioe) {
    ioe.printStackTrace();
} finally {
    if(httpURLConnection != null) {
        httpURLConnection.disconnect(); //close out our http connection
    }

    if(outputStreamWriter != null) {
        try {
            outputStreamWriter.close(); //close our output stream
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

//Return the JSON response from the server.
return jsonResponse;

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

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

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Xcode 구문 분석 JSON이 NULL을 반환합니다.

JSON을 구문 분석하면 Android에서 null 개체가 반환됩니다.

GSON으로 JSON을 구문 분석하면 null이 반환됩니다.

제품 링크 구문 분석이 null을 반환합니다.

d3 dateformat 구문 분석이 null을 반환합니다.

Android는 Json 문자열 배열을 구문 분석합니다.

Android는 배열의 JSON 배열을 구문 분석합니다.

Android에서 json 데이터를 구문 분석하는 동안 null 값을 가져옵니다.

Json은 gson을 사용하여 POJO로 구문 분석할 때 항상 null을 반환합니다.

Newtonsoft.Json이 잘못된 JSON을 구문 분석합니다.

파이썬은 모든 null 값에 대해 Json을 구문 분석합니다.

JS의 URL에서 JSON 파일을 구문 분석하면 null이 반환됩니다.

Java 구문 분석 된 JSON 배열 (GSON)은 0 또는 null을 반환합니다.

JSON / GSON 구문 분석은 특정 속성에 대해 null 값을 반환합니다.

SimpleDateFormat 구문 분석이 잘못된 값을 반환합니다.

ConvertTo-JSON이 배열을 잘못 구문 분석합니다.

Google Places API가 문자열을 반환합니다. JSON 객체를 어떻게 구문 분석합니까?

Android 앱이 JSON 구문 분석에서 닫힙니다.

GSON은 일반 Json 배열을 구문 분석합니다.

GSON은 일반 Json 배열을 구문 분석합니다.

json 구문 분석 후 null을 반환하는 flutter 모델

JSON 응답을 구문 분석하면 null 값이 제공됩니다.

json 구문 분석에 문자열을 추가하면 문자열 리터럴이 반환됩니다.

Json을 String Android Studio로 구문 분석

Android - XML을 JSON으로 구문 분석

html 문자를 반환하는 Android JSON 구문 분석 데이터

배열 이름없이 Android Json 구문 분석을 작성하려면 어떻게해야합니까?

JSON Android 구문 분석 jsonObject 변환

JSON을 구문 분석하면 nil이 반환됩니다. 이유는 무엇입니까?

TOP 리스트

  1. 1

    PrematureCloseException : 연결이 너무 일찍 닫혔습니다.

  2. 2

    MDRotatingPieChart를 회전하면 각도 대신 x / y 위치가 변경됩니다.

  3. 3

    c # 웹 사이트에서 텍스트를 복사하는 방법 (소스 코드 아님)

  4. 4

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  5. 5

    ArrayBufferLike의 typescript 정의의 깊은 의미

  6. 6

    Ionic 2 로더가 적시에 표시되지 않음

  7. 7

    복사 / 붙여 넣기 비활성화

  8. 8

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    QT Designer를 사용하여 GUI에 이미지 삽입

  11. 11

    java Apache POI Word 기존 테이블 셀 스타일 및 서식이있는 행 삽입

  12. 12

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

  13. 13

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  14. 14

    C # HttpWebRequest 기본 연결이 닫혔습니다. 전송시 예기치 않은 오류가 발생했습니다.

  15. 15

    어떻게 같은 CustomInfoWindow 다른 이벤트를 할 수 있습니다

  16. 16

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  17. 17

    dataSnapShot.getValue () 반환 데이터베이스에 그겁니다 데이터 종료 널 (null)

  18. 18

    ORA-12557 TNS : 프로토콜 어댑터를로드 할 수 없습니다

  19. 19

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  20. 20

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  21. 21

    C # Asp.net 웹 API-JSON / XML 변환기 API 만들기

뜨겁다태그

보관