文章标题 listview网络请求数据展示

布局
res/layout/activty_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
   <ListView
       android:id="@+id/list_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent"></ListView>
</RelativeLayout>

item_lista.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="200dp"
        android:layout_height="150dp" />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity

package image.bwie.com.dongliiang20170915;

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

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import image.bwie.com.dongliiang20170915.adapter.MyBaseAdapter;
import image.bwie.com.dongliiang20170915.bean.JsonBean;

public class MainActivity extends AppCompatActivity {

    private ListView list_view;
    private List<JsonBean.NewslistBean> list=new ArrayList<>();
    private MyBaseAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list_view = (ListView) findViewById(R.id.list_view);
        //获取网络数据
        getDataNet();
    }

    private void getDataNet() {
        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>(){

            @Override
            protected String doInBackground(Void... voids) {
                String path="https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10";
                try {
                    URL url = new URL(path);
                    HttpURLConnection conection= (HttpURLConnection) url.openConnection();
                    conection.setRequestMethod("GET");
                    conection.setConnectTimeout(5000);
                    conection.setReadTimeout(5000);
                    int responseCode = conection.getResponseCode();
                    if (responseCode==200){
                        InputStream inputStream = conection.getInputStream();
                        //字节转成字符串
                       String json=getStreamToString(inputStream,"utf-8");
                        return json;

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String json) {
                Gson gson = new Gson();
                JsonBean jsonBean = gson.fromJson(json, JsonBean.class);

                list.addAll(jsonBean.getNewslist());

                Log.i("list===========",list.toString());
                //设置适配器
                getAdapter();


            }
        };
        asyncTask.execute();
    }

    private void getAdapter() {
        if (adapter==null){
            adapter = new MyBaseAdapter(MainActivity.this,list);
            list_view.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }

    }

    private String getStreamToString(InputStream inputStream, String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String string=null;
            while ((string=bufferedReader.readLine())!=null){
                stringBuilder.append(string);

            }
            bufferedReader.close();
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }
}

Utils工具类ImageLoaderUtil

package image.bwie.com.dongliiang20170915.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;

import image.bwie.com.dongliiang20170915.R;

/**
 * 此类的作用:
 *
 * @author: forever
 * @date: 2017/9/15 10:38
 */
public class ImageLoaderUtil {
    public static void initConfig(Context context) {
        File cacheDir = new File(Environment.getExternalStorageDirectory(),"/image");  //缓存文件夹路径

        if (!cacheDir.exists()){
            cacheDir.mkdirs();
        }

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径
                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
                .diskCacheFileCount(100)  // 可以缓存的文件数量
                // default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .imageDownloader(new BaseImageDownloader(context)) // default
                .imageDecoder(new BaseImageDecoder(true)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs() // 打印debug log
                .build(); //开始构建

        ImageLoader.getInstance().init(config);
    }
    public static DisplayImageOptions getOption() {

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(1000)  // 下载前的延迟时间
                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
                .build();

        return options;
    }
}
适配器
ImageApplcation
package image.bwie.com.dongliiang20170915.adapter;

import android.app.Application;

import image.bwie.com.dongliiang20170915.utils.ImageLoaderUtil;
/**
 * 此类的作用:
 *
 * @author: forever
 * @date: 2017/9/15 9:49
 */
public class ImageApplcation extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderUtil.initConfig(this);
    }
}
MyBaseAdpter

package image.bwie.com.dongliiang20170915.adapter;

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

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.util.List;

import image.bwie.com.dongliiang20170915.R;
import image.bwie.com.dongliiang20170915.bean.JsonBean;
import image.bwie.com.dongliiang20170915.utils.ImageLoaderUtil;

/**
 * 此类的作用:
 *
 * @author: forever
 * @date: 2017/9/15 8:58
 */
public class MyBaseAdapter extends BaseAdapter {
    Context context;
    List<JsonBean.NewslistBean> list;

    public MyBaseAdapter(Context context, List<JsonBean.NewslistBean> list) {
        this.context = context;
        this.list = list;
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
    }

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Viewhodler hodler;
        if (view == null) {
            view = View.inflate(context, R.layout.item_lista, null);
            hodler = new Viewhodler();
            hodler.image_view = view.findViewById(R.id.image_view);
            hodler.text_view = view.findViewById(R.id.text_view);
            view.setTag(hodler);

        } else {
            hodler = (Viewhodler) view.getTag();
        }
        ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(), hodler.image_view, ImageLoaderUtil.getOption());
       hodler.text_view.setText(list.get(i).getTitle());
        return view;
    }

    class Viewhodler{
        ImageView image_view;
        TextView text_view;
    }

}

清单文件配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="image.bwie.com.dongliiang20170915">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:name=".adapter.ImageApplcation"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值