2017-11-27 1 views
0

data.police.uk 웹 사이트에서 배열을 가져 오려고합니다.URL null 객체 참조에서 Json을 가져 오는 중

package com.example.cosmin.crimerate.Latest_crimes; 

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

import com.example.cosmin.crimerate.R; 

import java.util.List; 

import retrofit2.Call; 
import retrofit2.Callback; 
import retrofit2.Response; 
import retrofit2.Retrofit; 
import retrofit2.converter.gson.GsonConverterFactory; 

public class JsonCrimesActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_json_crimes); 

     final ListView listView = findViewById(R.id.crimesList); 


     Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(Api.BASE_URL) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

     Api api = retrofit.create(Api.class); 

     Call<List<Crime>> call = api.getCrimes(); 

     call.enqueue(new Callback<List<Crime>>() { 
      @Override 
      public void onResponse(Call<List<Crime>> call, Response<List<Crime>> response) { 
       List<Crime> Crimes = response.body(); 

       String[] crimeCategories = new String[Crimes.size()]; 

        for (int i=0; i < Crimes.size();i++){ 
         crimeCategories[i]= Crimes.get(i).getCategory(); 
        } 

        listView.setAdapter(
          new ArrayAdapter<String>(
            getApplicationContext(), 
            android.R.layout.simple_list_item_1, 
            crimeCategories 

          ) 
        ); 

       } 


      @Override 
      public void onFailure(Call<List<Crime>> call, Throwable t) { 
       Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); 

      } 
     }); 


    } 
} 

API를 클래스의 :

public interface Api{ 

    String BASE_URL = "https://data.police.uk/api/"; 

    @GET("/crimes-no-location?category=all-crime&force=leicestershire&date=2017-02") 
    Call<List<Crime>> getCrimes(); 
다음

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference 내가 뭘 잘못 코드, 아니 아이디어입니다 : 코드를 실행할 때까지

불행하게도, 오류가 온다

배열 때문일 수 있다고 생각하십니까?

나 한테 힌트를 주거나 무슨 일이 일어나고 있는지 알려주세요.

도움 주셔서 감사합니다.

LE : 범죄 MODEL : 잘 작동하는 경우

public class Crime { 

    private String category; 
    private String persistent_id; 
    private String location_subtype; 
    private String id; 
    private String location; 
    private String context; 
    private String month; 
    private String location_type; 
    private String outcome_status; 

    public Crime(String category, String persistent_id, String location_subtype, String id, String location, String context, String month, String location_type, String outcome_status) { 
     this.category = category; 
     this.persistent_id = persistent_id; 
     this.location_subtype = location_subtype; 
     this.id = id; 
     this.location = location; 
     this.context = context; 
     this.month = month; 
     this.location_type = location_type; 
     this.outcome_status = outcome_status; 

    } 

    public String getCategory() { 
     return category; 
    } 

    public String getPersistent_id() { 
     return persistent_id; 
    } 

    public String getLocation_subtype() { 
     return location_subtype; 
    } 

    public String getId() { 
     return id; 
    } 

    public String getLocation() { 
     return location; 
    } 

    public String getContext() { 
     return context; 
    } 

    public String getMonth() { 
     return month; 
    } 

    public String getLocation_type() { 
     return location_type; 
    } 

    public String getOutcome_status() { 
     return outcome_status; 
    } 
} 
+0

'response.body()'무엇을 반환하지에 선도적 인 슬래시를 제거 :있는 그대로, 다음 URI에 HTTP 호출 (알 이중 //)을 만들고 있어요? – joao86

+0

먼저 URL에 여분의'/'가 있음을 확인하고 제거한 후 다시 테스트하십시오. 문제가 계속 발생하면 범죄 모델 클래스를 알려주실 수 있습니까? –

+0

답장을 보내 주셔서 감사합니다. /를 제거했습니다. 불행히도 새로운 오류가 발생합니다 : java.lang.IllegalStateException : 문자열을 예상했지만 행 1 열 93의 경로 BEGIN_OBJECT 경로 $ [0] .outcome_status입니다. – SamSu

답변

0

코드의 확인이 조각을합니다.

List<Crime> Crimes = response.body(); 

귀하의 범죄 목록은 아마 비어 있거나 null입니다.

0

response.body()null입니다. 나는 당신이 당신의 Api을 잘못 구성했기 때문에 그것이 확실하다고 확신합니다.

https://data.police.uk/api//crimes-no-location?category=all-crime&force=leicestershire&date=2017-02 

@GET

+0

답장을 보내 주셔서 감사합니다. /를 제거했습니다. 불행히도 새로운 오류가 발생합니다 : java.lang.IllegalStateException : 문자열을 예상했지만 행 1 열 93의 경로 BEGIN_OBJECT 경로 $ [0] .outcome_status입니다. – SamSu

+0

그래서 두 가지 이상의 문제가있었습니다. 즉, 모델을 파싱하는 데 문제가있을 수 있습니다. 'outcome_status'는 문자열을 기대하지만 대신 json 객체를 반환합니다. 이를 고려하여 모델을 업데이트해야합니다. 끝점에서 반환 된 json을 자세히 살펴 봅니다. 여기에서 멋지게 형식을 지정했습니다 (https://pastebin.com/tWV7rhvS). – Jon

관련 문제