Retrofit解析网页Json数据简单实例

本文介绍了一个结合Butterknife和Retrofit实现的新闻应用案例。通过具体代码展示了如何进行库配置、创建实体类、定义适配器及实现网络请求等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单使用了Butterknife+Retrofit

这里写图片描述


库配置
Project级的build.gradle

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

App级的build.gradle

apply plugin: 'com.android.application'
apply plugin:'android-apt'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.android.retrofitdemo"
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
}


布局文件

<?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="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/news_listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>


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

    <ImageView
        android:id="@+id/news_imageView"
        android:layout_width="70dp"
        android:layout_height="70dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/news_title_textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/news_description_textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>


</LinearLayout>


实体类

package com.android.retrofitdemo;


import com.google.gson.annotations.SerializedName;


/**
 * 新闻数据
 */


public class News {

    @SerializedName("id")
    private int id;
    @SerializedName("name")
    private String name;//名称
    @SerializedName("food")
    private String  food;//食物
    @SerializedName("img")
    private String img;//图片
    @SerializedName("images")
    private String images;//图片,
    @SerializedName("description")
    private String description;//描述
    @SerializedName("keywords")
    private String keywords;//关键字
    @SerializedName("message")
    private String message;//资讯内容
    @SerializedName("count")
    private int count ;//访问次数
    @SerializedName("fcount")
    private int fcount;//收藏数
    @SerializedName("rcount")
    private int rcount;//评论读数

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getFcount() {
        return fcount;
    }

    public void setFcount(int fcount) {
        this.fcount = fcount;
    }

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }

    public int getId() {
        return id;
    }

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

    public String getImages() {
        return images;
    }

    public void setImages(String images) {
        this.images = images;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRcount() {
        return rcount;
    }

    public void setRcount(int rcount) {
        this.rcount = rcount;
    }
}
package com.android.retrofitdemo;


import com.google.gson.annotations.SerializedName;

import java.util.List;

public class Tngou {
    @SerializedName("status")
    private boolean status;
    @SerializedName("total")
    private long total;
    @SerializedName("tngou")
    private List<News> newsList;

    public List<News> getNewsList() {
        return newsList;
    }

    public void setNewsList(List<News> newsList) {
        this.newsList = newsList;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }
}


数据适配器

package com.android.retrofitdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.Collection;
import java.util.List;

/**
 * 新闻列表适配器
 */
public class NewsAdapter extends BaseAdapter{

    private Context mContext;
    private List<News> mNewsList;

    public NewsAdapter(Context context, List<News> newsList){
        mContext = context;
        mNewsList = newsList;
    }

    @Override
    public int getCount() {
        return mNewsList.size();
    }

    @Override
    public Object getItem(int position) {
        return mNewsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.news_item,null);
            viewHolder = new ViewHolder();
            viewHolder.newsImageView = (ImageView) convertView.findViewById(R.id.news_imageView);
            viewHolder.newsTitleTextView = (TextView) convertView.findViewById(R.id.news_title_textView);
            viewHolder.newsDescriptionTextView = (TextView) convertView.findViewById(R.id.news_description_textView);
            convertView.setTag(viewHolder);
        }

        viewHolder = (ViewHolder) convertView.getTag();
        Picasso.with(mContext).load("http://tnfs.tngou.net/image"+mNewsList.get(position).getImg()).into(viewHolder.newsImageView);
        viewHolder.newsTitleTextView.setText(mNewsList.get(position).getName());
        viewHolder.newsDescriptionTextView.setText(mNewsList.get(position).getDescription());
        return convertView;
    }

    public final class ViewHolder{
        public ImageView newsImageView;
        public TextView newsTitleTextView;
        public TextView newsDescriptionTextView;
    }

    public void addAll(Collection<? extends News> collection){
        mNewsList.addAll(collection);
        notifyDataSetChanged();
    }

}


网络请求接口

package com.android.retrofitdemo;

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

/**
 * 获取新闻列表
 */
public interface NewsService {

    @GET("/api/cook/list" )
    Call<Tngou> getNews(@Query("id") int id, @Query("page") int page, @Query("rows") int rows);
}
package com.android.retrofitdemo;

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

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends AppCompatActivity implements Callback<Tngou> {


    @BindView(R.id.news_listView)
    ListView newsListView;

    private NewsAdapter adapter;

    private List<News> newsList;

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



        Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.tngou.net")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

        NewsService newsService = retrofit.create(NewsService.class);
        Call<Tngou> call = newsService.getNews(0,1,20);
        call.enqueue(this);

        ListView newsListView = (ListView) findViewById(R.id.news_listView);
        adapter = new NewsAdapter(this, new ArrayList<News>());
        newsListView.setAdapter(adapter);
    }


    @Override
    public void onResponse(Call<Tngou> call, Response<Tngou> response) {
        newsList = response.body().getNewsList();
        adapter.addAll(newsList);
    }

    @Override
    public void onFailure(Call<Tngou> call, Throwable t) {
        t.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值