【问题标题】:onResponse method not called in Retrofit?改造中未调用 onResponse 方法?
【发布时间】:2017-10-24 05:14:24
【问题描述】:

我正在使用 RetroFit 创建一个应用程序。我从 URL 获取 JSON 字符串中的数据,并使用 RetroFit 将其填充到回收视图中。

我的问题

我的问题是,当应用程序执行时,它显示以下错误::

E/RecyclerView:没有附加适配器;跳过布局
E/RecyclerView: 未连接适配器;跳过布局
D/错误: java.lang.IllegalStateException:应为 BEGIN_OBJECT,但为 BEGIN_ARRAY 在第 1 行第 2 列路径 $

我的支票

  • 检查网址
  • 使用浏览器检查 URL.. 成功返回 json

我努力解决这个问题,但没有解决方案。

我手动运行了json url,成功返回了json数据。但是在程序上,它返回错误。

JSON 数据样本

[
  {
    "user_id": "59e4897140d1666c6e8b4567",
    "post_id": "59eeb10d40d16686168b4567",
    "post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
    "post_type": "image",
    "caption": "vvnnk",
    "created": 1508815117,
    "time_diff": "1 hours ago",
    "first_name": null,
    "last_name": null,
    "user_name": null,
    "email": null,
    "profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
    "category": "New release"
  },
  {
    "user_id": "59e4897140d1666c6e8b4567",
    "post_id": "59ee306940d166697f8b4567",
    "post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
    "post_type": "image",
    "caption": "cutyy",
    "created": 1508782185,
    "time_diff": "10 hours ago",
    "first_name": null,
    "last_name": null,
    "user_name": null,
    "email": null,
    "profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
    "category": "Super Star"
  }
]

Post.java(JSON 的 POJO)

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Post {

    @SerializedName("user_id")
    @Expose
    private String userId;
    @SerializedName("post_id")
    @Expose
    private String postId;
    @SerializedName("post_url")
    @Expose
    private String postUrl;
    @SerializedName("post_type")
    @Expose
    private String postType;
    @SerializedName("caption")
    @Expose
    private String caption;
    @SerializedName("created")
    @Expose
    private Integer created;
    @SerializedName("time_diff")
    @Expose
    private String timeDiff;
    @SerializedName("first_name")
    @Expose
    private Object firstName;
    @SerializedName("last_name")
    @Expose
    private Object lastName;
    @SerializedName("user_name")
    @Expose
    private Object userName;
    @SerializedName("email")
    @Expose
    private Object email;
    @SerializedName("profile_pic")
    @Expose
    private String profilePic;
    @SerializedName("category")
    @Expose
    private String category;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getPostUrl() {
        return postUrl;
    }

    public void setPostUrl(String postUrl) {
        this.postUrl = postUrl;
    }

    public String getPostType() {
        return postType;
    }

    public void setPostType(String postType) {
        this.postType = postType;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public Integer getCreated() {
        return created;
    }

    public void setCreated(Integer created) {
        this.created = created;
    }

    public String getTimeDiff() {
        return timeDiff;
    }

    public void setTimeDiff(String timeDiff) {
        this.timeDiff = timeDiff;
    }

    public Object getFirstName() {
        return firstName;
    }

    public void setFirstName(Object firstName) {
        this.firstName = firstName;
    }

    public Object getLastName() {
        return lastName;
    }

    public void setLastName(Object lastName) {
        this.lastName = lastName;
    }

    public Object getUserName() {
        return userName;
    }

    public void setUserName(Object userName) {
        this.userName = userName;
    }

    public Object getEmail() {
        return email;
    }

    public void setEmail(Object email) {
        this.email = email;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

}


DataAdapter.java

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private ArrayList<Post> post;

    public DataAdapter(ArrayList<Post> post) {
        this.post = post;
    }

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

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

        viewHolder.tv_userId.setText(post.get(i).getUserId());
        viewHolder.tv_postId.setText(post.get(i).getPostId());
        viewHolder.tv_postType.setText(post.get(i).getPostType());
        viewHolder.tv_caption.setText(post.get(i).getCaption());

        Picasso.with(viewHolder.tv_postUrl.getContext()).load(post.get(i).getPostUrl()).into(viewHolder.tv_postUrl);
        Picasso.with(viewHolder.tv_profilePic.getContext()).load(post.get(i).getProfilePic()).into(viewHolder.tv_profilePic);

        viewHolder.tv_timeDiff.setText(post.get(i).getTimeDiff());
        viewHolder.tv_category.setText(post.get(i).getCategory());
        viewHolder.tv_created.setText(post.get(i).getCreated());


    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_userId,tv_postId,tv_postType,tv_caption,tv_timeDiff,tv_category,tv_created;
        ImageView  tv_profilePic,tv_postUrl;
        public ViewHolder(View view) {
            super(view);

            tv_userId = (TextView)view.findViewById(R.id.tv_userId);
            tv_postUrl = (ImageView) view.findViewById(R.id.tv_postUrl);
            tv_postType = (TextView)view.findViewById(R.id.tv_postType);
            tv_caption = (TextView)view.findViewById(R.id.tv_caption);
            tv_postId = (TextView)view.findViewById(R.id.tv_postId);



            tv_timeDiff = (TextView)view.findViewById(R.id.tv_timeDiff);
            tv_profilePic = (ImageView)view.findViewById(R.id.tv_profilePic);
            tv_category = (TextView)view.findViewById(R.id.tv_category);
            tv_created = (TextView)view.findViewById(R.id.tv_created);

        }
    }

}

JSONResponse.java

public class JSONResponse {
    private Post[] post;

    public Post[] getPost() {
        return post;
    }
}

RequestInterface.java

import retrofit2.Call;
import retrofit2.http.GET;

public interface RequestInterface {

    @GET("anan/mobile/posts/viewall_Posts")
    Call<JSONResponse> getJSON();
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ArrayList<Post> data;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    private void initViews(){
        recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }
    private void loadJSON(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://demo.cogzideltemplates.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        System.out.println("enter the url: "+call.request().url());

        call.enqueue(new Callback<JSONResponse>() {

            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

                JSONResponse jsonResponse = response.body();

                data = new ArrayList<>(Arrays.asList(jsonResponse.getPost()));
                adapter = new DataAdapter(data);
                recyclerView.setAdapter(adapter);
            }

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

            }
        });
    }
}

这些是我的课。请帮我解决这个问题。

【问题讨论】:

  • JSONResponse 是对象,你 api 返回的 JSONArray 不是 JSONObject
  • 您没有在布局管理器中指定它是垂直、水平、网格等
  • @JRamesh 请解释一下
  • @RageshDAntony 如果您想使用上面的代码解析响应,那么响应将是这样的 {[{},{}]}

标签: java android json android-recyclerview retrofit


【解决方案1】:

将您的 JSON 数据样本更改为 JSON 对象 像这样

{
[
  {
    "user_id": "59e4897140d1666c6e8b4567",
    "post_id": "59eeb10d40d16686168b4567",
    "post_url": "http://demo.cogzideltemplates.com/anan/posts/images/22f3fb0b974be4968118a410e0ad48f7.jpg",
    "post_type": "image",
    "caption": "vvnnk",
    "created": 1508815117,
    "time_diff": "1 hours ago",
    "first_name": null,
    "last_name": null,
    "user_name": null,
    "email": null,
    "profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
    "category": "New release"
  },
  {
    "user_id": "59e4897140d1666c6e8b4567",
    "post_id": "59ee306940d166697f8b4567",
    "post_url": "http://demo.cogzideltemplates.com/anan/posts/images/8f81bd77e60e596cf458d42a743897f8.jpg",
    "post_type": "image",
    "caption": "cutyy",
    "created": 1508782185,
    "time_diff": "10 hours ago",
    "first_name": null,
    "last_name": null,
    "user_name": null,
    "email": null,
    "profile_pic": "http://demo.cogzideltemplates.com/anan/images/users/no_avatar.jpg",
    "category": "Super Star"
  }
]}

并更改您的 JSONResponse.java

这样

public class JSONResponse {
private List<Post> post;

public List<Post> getPost() {
    return post;
}

}

Here is the tutorial for parsing JSON Array and JSON Object

【讨论】:

  • 感谢您的回答.. 但遗憾的是我无法更改 json 字符串,因为它是直接从互联网上获取的。请您在不更改 JSON 的情况下提供解决方案。 @Girish
  • 我解决了我的问题.. 我只是将所有出现的 更改为 > 并且它有效.. 谢谢大家
猜你喜欢
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 2018-03-06
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多