使用RecylcerView和Retrofit2最新没有数据

时间:2018-09-16 15:46:46

标签: android json android-recyclerview retrofit

我是Retrofit2 android的新手。我正在尝试使用可通过改造和RecyclerView显示地震信息的应用程序。但是我无法以JSON格式显示从URL提取的任何数据。 大多数时候,我没有连接任何适配器。跳过布局错误。我已经搜索了很多,但是没有解决。 我正在使用HttpLoggingInterceptor查看响应。我的JSON数据的响应主体显示在Logcat的详细信息中,而不显示在RecyclerView中。 有时没有错误,冗长的话什么都没有,即使应用程序是空白,也没有数据。 请帮我解决我的问题。

我从中获取数据的URL。我将其限制为2,以便您可以清楚地看到它。 https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=2

这是我的MainActivity。

public class EarthquakeActivity extends AppCompatActivity {

    private static final String TAG = EarthquakeActivity.class.getSimpleName();

    private RecyclerView recyclerView;
    private List<Feature> featureList;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.d(TAG,"onCreate() method called...");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earthquke);

        recyclerView = findViewById(R.id.earthquake_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClientBuilder.addInterceptor(loggingInterceptor);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://earthquake.usgs.gov/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClientBuilder.build())
                .build();

        EarthquakeRequestInterface requestInterface = retrofit.create(EarthquakeRequestInterface.class);
        Call<EarthquakeResponse> responseCall =requestInterface.getJSON("geojson");
        responseCall.enqueue(new Callback<EarthquakeResponse>() {
            @Override
            public void onResponse(Call<EarthquakeResponse> call, Response<EarthquakeResponse> response) {

                if (response.isSuccessful()){
                    EarthquakeResponse earthquakeResponse = response.body();
                    adapter = new DataAdapter(earthquakeResponse.getFeatures());
                    recyclerView.setAdapter(adapter);
                }
                else {
                    Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<EarthquakeResponse> call, Throwable t) {
                Log.e("Error",t.getMessage());
            }
        });
    }
}`

这是我的适配器类。

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private List<Feature> features;

    public DataAdapter(List<Feature> features1) {
        this.features = features1;
    }


    @NonNull
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.earthquake_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DataAdapter.ViewHolder viewHolder, int i) {

        viewHolder.earthquakeMag.setText(features.get(i).getProperties().getMag().toString());
        viewHolder.earthquakePlace.setText(features.get(i).getProperties().getPlace());
        viewHolder.earthquakeUrl.setText(features.get(i).getProperties().getUrl());
    }

    @Override
    public int getItemCount() {
        return features.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView earthquakeMag,earthquakePlace,earthquakeUrl;
        public ViewHolder(View view) {
            super(view);

            earthquakeMag = view.findViewById(R.id.earthquake_mag);
            earthquakePlace = view.findViewById(R.id.earthquake_place);
            earthquakeUrl = view.findViewById(R.id.earthquake_url);
        }
    }
}

这是我的API接口。

public interface EarthquakeRequestInterface {

    @GET ("fdsnws/event/1/query")
    Call<EarthquakeResponse> getJSON(@Query("format") String format);
}

这是我的Response java类(POJO或Model类)。

public class EarthquakeResponse {

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("metadata")
    @Expose
    private Metadata metadata;
    @SerializedName("features")
    @Expose
    private List<Feature> features = null;
    @SerializedName("bbox")
    @Expose
    private List<Double> bbox = null;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Metadata getMetadata() {
        return metadata;
    }

    public void setMetadata(Metadata metadata) {
        this.metadata = metadata;
    }

    public List<Feature> getFeatures() {
        return features;
    }

    public void setFeatures(List<Feature> features) {
        this.features = features;
    }

    public List<Double> getBbox() {
        return bbox;
    }

    public void setBbox(List<Double> bbox) {
        this.bbox = bbox;
    }

}

这是我的Feature类(POJO类)

public class Feature {

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("properties")
    @Expose
    private Properties properties;
    @SerializedName("geometry")
    @Expose
    private Geometry geometry;
    @SerializedName("id")
    @Expose
    private String id;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Geometry getGeometry() {
        return geometry;
    }

    public void setGeometry(Geometry geometry) {
        this.geometry = geometry;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

这是Properties Java类(POJO类)。它包含我感兴趣的数据。为了检查我的代码是否正常工作,我将其减少到只有3个。

public class Properties {

    @SerializedName("mag")
    @Expose
    private Double mag;
    @SerializedName("place")
    @Expose
    private String place;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("detail")
    @Expose
    private String detail;


    public Double getMag() {
        return mag;
    }

    public void setMag(Double mag) {
        this.mag = mag;
    }

    public String getPlace() {
        return place;
    }

    public void setPlace(String place) {
        this.place = place;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDetail() {
        return detail;
    }

}

JSON响应中还存在其他POJO类,例如Geometry,Metadata,但我对此并不感兴趣。

这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for a list of earthquakes -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/earthquake_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

    </android.support.v7.widget.RecyclerView>
</LinearLayout>

这是我的自定义适配器布局文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/earthquake_layout"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/earthquake_mag"
        android:layout_gravity="top"
        android:textStyle="bold"
        android:textSize="16sp"
        android:textColor="@android:color/black"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        tools:text="Place"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/earthquake_place"
        android:layout_gravity="top"
        android:textStyle="bold"
        android:textSize="16sp"
        android:textColor="@android:color/black"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        tools:text="Place"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/earthquake_url"
        android:layout_gravity="top"
        android:textStyle="bold"
        android:textSize="16sp"
        android:textColor="@android:color/black"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        tools:text="Place"
        />

</LinearLayout>

抱歉,我的英语不好,或者有任何不正当的提问方式。我是stackoverflow的新手。我最近注册了。 请真的需要一些认真的帮助来克服这个问题。

1 个答案:

答案 0 :(得分:0)

尝试在Retrofit方法之外设置适配器。像这样:

    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    mItems = new ArrayList<Feature>;
    adapter = new DataAdapter(mItems);
    recyclerView.setAdapter(adapter);

   // .. other code 

    EarthquakeRequestInterface requestInterface = retrofit.create(EarthquakeRequestInterface.class);
    Call<EarthquakeResponse> responseCall =requestInterface.getJSON("geojson");
    responseCall.enqueue(new Callback<EarthquakeResponse>() {
        @Override
        public void onResponse(Call<EarthquakeResponse> call, Response<EarthquakeResponse> response) {

            if (response.isSuccessful()){
                EarthquakeResponse earthquakeResponse = response.body();
                mItems.addAll(earthquakeResponse.getFeatures());
                adapter.notifyDatasetChanged();

            } else {
                Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<EarthquakeResponse> call, Throwable t) {
            Log.e("Error",t.getMessage());
        }
    });