android获取接口展示到ListView上(带效果图)

时间:2024-04-09 21:24:52

首先写权限

  <!-- 网络权限 -->
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

引入包

  implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

MainActivity布局代码

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

        <ListView
            android:id="@+id/Mlist"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></ListView>

    </LinearLayout>

Http请求网络(GET)

public class Http {

    String str = "http://apis.juhe.cn/cook/query?key=81d31315d7cb8a6e2aa7add264afb729&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10";

    public static String requestHttpGet(String strUrl){
        try {
            //创建ur
            URL url = new URL(strUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置为get请求
            connection.setRequestMethod("GET");
            //超时,时间,获取数据时间
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            //获取请求码
            int code = connection.getResponseCode();
            //判断是否成功
            if (code == HttpURLConnection.HTTP_OK){
                //获取数据
                InputStream stream = connection.getInputStream();
                BufferedReader reader =  new BufferedReader(new InputStreamReader(stream,"utf-8"));
                //拼接字符串
                StringBuilder builder = new StringBuilder();
                //把数据读取成字符串
                String str = "";
                while ((str = reader.readLine())!= null){
                    //把数据拼接成一行数据
                    builder.append(str);
                }
                //返回拼接后的数据
                return builder.toString();
            }
                //关闭连接
                connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

AsyncTask请求数据

public class MyAsyncTask extends AsyncTask<String,Integer,String> {

    @Override
    protected String doInBackground(String... strings) {
        //5,利用子线程请求数据
        return Http.requestHttpGet(strings[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //5,主线程  调用
        callbacks.getData(s);
    }

    //1,创建接口
    public interface Callbacks{
        //2,抽象方法
        void  getData(String str);
    }
    //3,属性
    private Callbacks callbacks;
    //4,set方法
    public void setCallbacks(Callbacks callbacks) {
        this.callbacks = callbacks;
    }

}

App获取图片

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                //加载时显示的站位图
                .showImageOnLoading(R.mipmap.zhan)
                //url为空时显示的站位图
                .showImageForEmptyUri(R.mipmap.zhaobudao)
                //加载失败是显示的占位图
                .showImageOnFail(R.mipmap.shibai)
                //
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .build();

        //构建
        ImageLoaderConfiguration loaderConfiguration = new ImageLoaderConfiguration.Builder(this)
            //吧设置添加到构建中
            .defaultDisplayImageOptions(options)
            .build();
        //获得实例
        ImageLoader imageLoader = ImageLoader.getInstance();

        //初始化
        imageLoader.init(loaderConfiguration);
    }
}

写完了App在重新添加权限

   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:name=".app.App"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
    

MainActivity主页面代码

public class MainActivity extends AppCompatActivity implements MyAsyncTask.Callbacks {

    private ListView listview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件id
        listview = findViewById(R.id.Mlist);
        //创建对象
        MyAsyncTask task = new MyAsyncTask();
        //注册接口
        task.setCallbacks(MainActivity.this);
        //请求数据
        task.execute("http://apis.juhe.cn/cook/query?key=81d31315d7cb8a6e2aa7add264afb729&menu=西红柿&rn=10");
    }

    @Override
    public void getData(String str) {
        //解析
        Gson gson = new Gson();
        JsonBean jsonBean = gson.fromJson(str, JsonBean.class);
        //获取集合
//        List<JsonBean.ResultBean.DataBean> data = jsonBean.getResult().getData();
        List<JsonBean.ResultBean.DataBean> data = jsonBean.getResult().getData();
        //设置适配器
        listview.setAdapter(new MyListAdapter(data,MainActivity.this));
    }
}

Listview优化布局

 <ImageView
        android:id="@+id/Limg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/Lte"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="阿萨德撒的"/>

Listview优化代码

public class MyListAdapter extends BaseAdapter {

    private List<JsonBean.ResultBean.DataBean>list;
    private Context context;
    private ImageView image;

    public MyListAdapter(List<JsonBean.ResultBean.DataBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

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

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null){
            view = View.inflate(context,R.layout.list_adapter,null);
            holder = new ViewHolder();
            holder.textView = view.findViewById(R.id.Lte);
            holder.imageView = view.findViewById(R.id.Limg);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        JsonBean.ResultBean.DataBean dataBean = list.get(i);
            holder.textView.setText(dataBean.getSteps().get(0).getImg().toString());
            ImageLoader.getInstance().displayImage(dataBean.getSteps().get(0).getImg(),holder.imageView);

        return view;
    }

    class ViewHolder{
        TextView textView;
        ImageView imageView;
    }
}

效果展示
android获取接口展示到ListView上(带效果图)