为什么我的应用程序没有显示数据,从API中获取JSON,使用retrofit,在android中的recyclerview?

时间:2016-10-19 14:10:23

标签: java android json api retrofit

在此之前,让我告诉你,我是Android开发的初学者。我一直在开发一个音乐流应用程序,它从API中获取JSON中的数据。我正在使用 retrofit2作为HTTP客户端和GSON库用于JSON解析。

所以我正在研究一种API方法来获取TopArtist信息。以下是课程和布局:

MainActicity.java:这是主要的活动

package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import com.example.myapplication.APIServices.API_Service;
import com.example.myapplication.Models.Artist;
import com.example.myapplication.Models.LastAPIRecyclerViewAdapter;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends AppCompatActivity {

    public static final String API_Url = "http://ws.audioscrobbler.com/2.0/";
    public static final String API_Key = "//my API-key";

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

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

        ButterKnife.bind(this);

        StaggeredGridLayoutManager mStaggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mStaggeredGridLayoutManager);

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

        API_Service api_service = retrofit.create(API_Service.class);
        Call<List<Artist>> call = api_service.getTopArtist();

        call.enqueue(new Callback<List<Artist>>() {
            @Override
            public void onResponse(Response<List<Artist>> response, Retrofit retrofit)      
            {
                List<Artist> artist = response.body();
                Log.d("Artist", "onResponse: " + response.code());
                LastAPIRecyclerViewAdapter lastAPIRecyclerViewAdapter = new LastAPIRecyclerViewAdapter(artist);
                recyclerView.setAdapter(lastAPIRecyclerViewAdapter);
            }
            @Override
            public void onFailure(Throwable t) 
            {
                Log.d("Artist", "onFailure: " + t.getMessage());
            }
        });
    }
}

APIService.java:

import com.example.myapplication.MainActivity;
import com.example.myapplication.Models.Artist;
import java.util.List;
import retrofit.Call;
import retrofit.http.GET;

public interface API_Service {
    @GET("?method=tag.gettoptracks&tag=pop&api_key=" + MainActivity.API_Key + "&format=json")
    Call<List<Artist>> getTopArtist();
}

Artist.java:这是Model / POJO类,它将存储从API的GET请求中获取的所有数据。

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Artist {
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("mbid")
    @Expose
    private String mbid;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("streamable")
    @Expose
    private String streamable;
    @SerializedName("image")
    @Expose
    private List<Image> image = new ArrayList<Image>();
    @SerializedName("@attr")
    @Expose
    private Attr attr;

    /**
    * 
    * @return
    * The name
    */
    public String getName() {
        return name;
    }

    /**
    * 
    * @param name
    * The name
    */
    public void setName(String name) {
        this.name = name;
    }

    /**
    * 
    * @return
    * The mbid
    */
    public String getMbid() {
        return mbid;
    }

    /**
    * 
    * @param mbid
    * The mbid
    */
    public void setMbid(String mbid) {
        this.mbid = mbid;
    }

    /**
    * 
    * @return
    * The url
    */
    public String getUrl() {
        return url;
    }

    /**
    * 
    * @param url
    * The url
    */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
    * 
    * @return
    * The streamable
    */
    public String getStreamable() {
        return streamable;
    }

    /**
    * 
    * @param streamable
    * The streamable
    */
    public void setStreamable(String streamable) {
        this.streamable = streamable;
    }

    /**
    * 
    * @return
    * The image
    */
    public List<Image> getImage() {
        return image;
    }

    /**
    * 
    * @param image
    * The image
    */
    public void setImage(List<Image> image) {
        this.image = image;
    }

    /**
    * 
    * @return
    * The attr
    */
    public Attr getAttr() {
        return attr;
    }

    /**
    * 
    * @param attr
    * The @attr
    */
    public void setAttr(Attr attr) {
        this.attr = attr;
    }
}

LastAPIRecyclerViewAdapter.java:

import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myapplication.R;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;

public class LastAPIRecyclerViewAdapter extends RecyclerView.Adapter<LastAPIRecyclerViewAdapter.LastAPIRecyclerViewHolder>{

    private List<Artist> artists;

    public LastAPIRecyclerViewAdapter(List<Artist> _artist) {
        this.artists = _artist;
    }

    @Override
    public LastAPIRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View viewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_cardview, parent, false);
        return new LastAPIRecyclerViewHolder(viewItem);
    }

    @Override
    public void onBindViewHolder(LastAPIRecyclerViewHolder holder, int position) {
        holder.title.setText(artists.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    class LastAPIRecyclerViewHolder extends RecyclerView.ViewHolder{

        @Bind(R.id.cardView)
        CardView cardView;

        @Bind(R.id.textView)
        TextView title;

        @Bind(R.id.imageView)
        ImageView image;

        LastAPIRecyclerViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

custom_cardview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cardView"
        app:cardElevation="2dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:contentDescription="ImageView of the Recycler View" />

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView" />

    </android.support.v7.widget.CardView>

</LinearLayout>

activity_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.myapplication.MainActivity">

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

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

因此,每当我运行此应用程序时,它都不会向我显示任何视图。只是一个空白活动。我哪里出错了?

2 个答案:

答案 0 :(得分:1)

需要更新此项以返回列表的长度

@Override
public int getItemCount() {
    return 0;
}

据我所知,其他一切看起来都不错

答案 1 :(得分:0)

请记住检查“艺术家”是否有值并返回其大小。

您应该添加以下内容:

@Override
public int getItemCount() {
    return (null != artist ? artist.size() : 0);
}