android - 为什么在 Android 中使用 Retrofit 时不显示来自服务器的帖子

标签 android android-adapter retrofit2 android-json

我想使用 Retrofit 从服务器加载数据,我使用 DataModel 设置和获取数据。

这就是我想做的。当我点击一个类别时,我想在其他 Activity 中看到来自该类别的帖子。

为了显示类别帖子,我使用此链接:http://tellfa.com/tafrihgah/?json=get_category_posts

我使用 category id 进行过滤。

例如:http://tellfa.com/tafrihgah/?json=get_category_posts&id=1通过此链接,我看到了 Category1 中的所有帖子。

设置链接的Retrofit interface:(我在other class中设置了base_url)

public interface Retrofit_ApiInterface {

    // For Categories Response
    @GET("tafrihgah/?json=get_category_posts&")
    Call<R_CatModelResponse> getCatResponse(@Query("id") Integer id);
}

我通过此代码将类别 ID 发送到其他 Activity :

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

        private List<Retrofit_ColoniesModel> mDateSet;
        private Context mContext;
        private SparseBooleanArray expandState = new SparseBooleanArray();

        public ColoniesAdapter(Context context, List<Retrofit_ColoniesModel> dataSet) {
            this.mContext = context;
            this.mDateSet = dataSet;
            for (int i = 0; i < mDateSet.size(); i++) {
                expandState.append(i, false);
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {

            holder.colonies_title.setText(mDateSet.get(position).getTitle());
            holder.colonies_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    Retrofit_ColoniesModel model = mDateSet.get(pos);
                    mContext.startActivity(new Intent(v.getContext(), Category_page.class)
                            .putExtra("categoryTitle", model.getTitle())
                            .putExtra("categoryID", model.getId()));

                    Toast.makeText(mContext, " " + model.getId(), Toast.LENGTH_SHORT).show();
                }
            });

...

Category_page 代码:

public class Category_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private TextView toolbar_title;
    private ImageView toolbar_menuImage;
    private RelativeLayout root;
    private CategoryAdapter mAdapter;
    private RecyclerView cat_recyclerView;
    private LinearLayoutManager mLayoutManager;
    private RelativeLayout loadLayout;
    private String catTitle = "";
    private Integer catID;
    private Bundle bundle;
    private int pageCount = 1;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.category_page);
        //if (!EventBus.getDefault().isRegistered(this)) {
        //   EventBus.getDefault().register(this);
        //}

        // Hide StatusBar color
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        // Initializing
        context = Category_page.this;
        toolbar = (Toolbar) findViewById(R.id.category_toolbar);
        cat_recyclerView = (RecyclerView) findViewById(R.id.category_recycler);
        toolbar_title = (TextView) toolbar.findViewById(R.id.toolbar_pages_title);
        mLayoutManager = new LinearLayoutManager(this);
        root = (RelativeLayout) findViewById(R.id.category_root);
        loadLayout = (RelativeLayout) findViewById(R.id.category_empty_layout);
        // Toolbar
        setSupportActionBar(toolbar);
        if (toolbar != null) {
            getSupportActionBar().setTitle("");
        }

        // Receive Data
        bundle = getIntent().getExtras();
        catID = bundle.getInt("categoryID");
        if (bundle != null) {
            catTitle = bundle.getString("categoryTitle");
        }
        if (catTitle != null) {
            toolbar_title.setText(catTitle);
        }

        // Load data
        //LoadData(catID);
        // Menu
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        toolbar_menuImage = (ImageView) toolbar.findViewById(R.id.toolbar_pages_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), toolbar_menuImage)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView
        cat_recyclerView.setLayoutManager(mLayoutManager);
        cat_recyclerView.setHasFixedSize(true);

        // Retrofit //////////
        Retrofit_ApiInterface apiInterface = Retrofit_ApiClient.getClient().create(Retrofit_ApiInterface.class);
        Call<R_CatModelResponse> call = apiInterface.getCatResponse(catID);

        call.enqueue(new Callback<R_CatModelResponse>() {
            @Override
            public void onResponse(Call<R_CatModelResponse> call, Response<R_CatModelResponse> response) {
                List<R_CatModel> models = response.body().getCat_posts();

                mAdapter = new CategoryAdapter(context, cat_recyclerView, models);
                cat_recyclerView.setAdapter(mAdapter);

                Toast.makeText(Category_page.this, "Response", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<R_CatModelResponse> call, Throwable t) {

                Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();

            }
        });

我从一个适配器发送带有以下代码的 category_id :

mContext.startActivity(new Intent(v.getContext(), Category_page.class)
        .putExtra("categoryTitle", model.getTitle())
        .putExtra("categoryID", model.getId()));

并使用以下代码接收此数据:

// Receive Data
bundle = getIntent().getExtras();
catID = bundle.getInt("categoryID");

但是错误信息(Toast)而不是分类帖子!

显示来自

的错误 toast
@Override
public void onFailure(Call<R_CatModelResponse> call, Throwable t) {
    Toast.makeText(Category_page.this, "Error", Toast.LENGTH_SHORT).show();
}

更新:
这是我得到的错误:

E/CatResponseError: Error : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 48 path $.category

更新#2:
添加了我的 POJO 类:

public class R_CatModelResponse {

    @SerializedName("status")
    public String Cat_status;
    @SerializedName("count")
    public int Cat_count;
    @SerializedName("pages")
    public int Cat_pages;
    @SerializedName("category")
    public List<Retrofit_ColoniesModel> category;
    @SerializedName("posts")
    public List<R_CatModel> Cat_posts;

    public String getCat_status() {
        return Cat_status;
    }

    public void setCat_status(String cat_status) {
        Cat_status = cat_status;
    }

    public int getCat_count() {
        return Cat_count;
    }

    public void setCat_count(int cat_count) {
        Cat_count = cat_count;
    }

    public int getCat_pages() {
        return Cat_pages;
    }

    public void setCat_pages(int cat_pages) {
        Cat_pages = cat_pages;
    }

    public List<Retrofit_ColoniesModel> getCategory() {
        return category;
    }

    public void setCategory(List<Retrofit_ColoniesModel> category) {
        this.category = category;
    }

    public List<R_CatModel> getCat_posts() {
        return Cat_posts;
    }

    public void setCat_posts(List<R_CatModel> cat_posts) {
        Cat_posts = cat_posts;
    }
}

我该如何解决这个问题?

请帮帮我。提前致谢。

最佳答案

参见 this使您的生活更轻松的模式:D,基于使用以下结构:

您的数据模型应该是:

public class Model {

    String status;
    int count;
    int page;
    Category category;
    List<Post> posts;

    // implement rest of thing

    public class Category{

        int id;
        String slug;
        String title;
        String description;
        int parent;
        int post_count;
    }

    public class Post {
        int id;
        String type;
        String slug;
        //..rest of thing
    }

}

您的服务interface应该是:

public interface IService {

        @GET("/tafrihgah/?json=get_category_posts")
        Call<Model> getCategoryPost(
                @Query("id") String id

                //...other query if you need should added like below
               @Query("categorySlug") String categorySlug,
               @Query("tag") String tag,
        );
    }

还有你的ServiceHelper包含以下方法:

public Call<CategoryModel> getAllCategory() {
    return service.getCateogryPost();
}

而你的错误导致了你的POJO不适合服务器型号。仔细检查您的型号并确保 Object而不是 List/Array ;

在你的情况下而不是 List<Retrofit_ColoniesModel> category使用 Retrofit_ColoniesModel category ;

关于android - 为什么在 Android 中使用 Retrofit 时不显示来自服务器的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39291691/

相关文章:

c# - 如何在 Visual Studio 中为 Windows 计算机上的 Xamarin 应用程序设计用户界面?

android - 在 android 中为 ksoap2 中的 header 提供安全性

java - 改造 JSON 反序列化对象的 $ref 对其原始副本的引用

android - ImageView 在两次点击后更改图像

android - 如何从另一个 fragment 获取适配器

android - Retrofit2 和证书固定

java - 如何使用注解通过改造 2 在 android 中解析动态 json

android - 如何在警报对话框中扩充包含 ListView 的布局?

java - 为 Eclipse/Android 开发编译标志

android - Spinner 和 RecyclerView 的通用适配器