网络请求图片,文字,展现在ListView上

来源:互联网 发布:超图软件 福州软件园 编辑:程序博客网 时间:2024/06/04 23:29
一,在  manifests  写权限

<uses-permission android:name="android.permission.INTERNET"/>
在 <application  写
android:name=".MApp"
写依赖
compile 'com.google.code.gson:gson:2.8.2'compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
二,在main布局写
<ListView    android:id="@+id/lv"    android:layout_width="wrap_content"    android:layout_height="wrap_content"></ListView>
在item布局里写
<?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/iv"        android:layout_width="150dp"        android:layout_height="100dp" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <TextView            android:id="@+id/tv_title"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="16sp" />        <TextView            android:id="@+id/tv_content"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="24sp" />    </LinearLayout></LinearLayout>
三,在 MainActivity 里写
public class MainActivity extends AppCompatActivity {    private String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";    private List<TouNews> list;    private List<News.DataBean> list1;    private ListView lv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        lv = (ListView) findViewById(R.id.lv);        new MyAsyncTask().execute(urlString);    }    class MAsyncTask extends AsyncTask<String,Void,String>{        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            Type type = new TypeToken<List<TouNews>>() {}.getType();            Gson gson = new Gson();            list = gson.fromJson(s,type);        }        @Override        protected void onProgressUpdate(Void... values) {            super.onProgressUpdate(values);        }        @Override        protected String doInBackground(String... params) {            return NetWordUtils.getNetjson(params[0]);        }    }    class PageAdapter extends PagerAdapter{        @Override        public int getCount() {            return list.size();        }        @Override        public boolean isViewFromObject(View view, Object object) {            return view == object;        }        @Override        public Object instantiateItem(ViewGroup container, int position) {            TextView textView = new TextView(MainActivity.this);            textView.setText(list.get(position).getString());            container.addView(textView);            return textView;        }        @Override        public void destroyItem(ViewGroup container, int position, Object object) {            container.removeView((View) object);        }    }    class MyAsyncTask extends AsyncTask<String,Void,String>{        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            Gson gson = new Gson();            News news = gson.fromJson(s, News.class);           list1 =  news.getData();            lv.setAdapter(new MyAdapter());        }        @Override        protected void onProgressUpdate(Void... values) {            super.onProgressUpdate(values);        }        @Override        protected String doInBackground(String... params) {            return NetWordUtils.getNetjson(params[0]);        }    }    class MyAdapter extends BaseAdapter{        @Override        public int getCount() {            return list1.size();        }        @Override        public Object getItem(int position) {            return list1.get(position);        }        @Override        public long getItemId(int position) {            return position;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            ViewHolder holder = null;            if (convertView == null) {                holder = new ViewHolder();                convertView = View.inflate(MainActivity.this, R.layout.item, null);                holder.imageView = convertView.findViewById(R.id.iv);                holder.textView01 = convertView.findViewById(R.id.tv_title);                holder.textView02 = convertView.findViewById(R.id.tv_content);                convertView.setTag(holder);            } else {                holder = (ViewHolder) convertView.getTag();            }            holder.textView01.setText(list1.get(position).getNews_summary());            holder.textView02.setText(list1.get(position).getNews_title());            ImageLoader.getInstance().displayImage(list1.get(position).getPic_url(),holder.imageView);            return convertView;        }    }    class ViewHolder {        ImageView imageView;        TextView textView01;        TextView textView02;    }    class MyAsync extends  AsyncTask<String, Void, Bitmap>{        ImageView imageView;        //有参构造        public MyAsync(ImageView imageView) {            this.imageView = imageView;        }        //图片Imageview赋值        @Override        protected void onPostExecute(Bitmap bitmap) {            super.onPostExecute(bitmap);            imageView.setImageBitmap(bitmap);        }        //解析图片        @Override        protected Bitmap doInBackground(String... strings) {            return NetWordUtils.getNetBitmap(strings[0]);        }    }}
四,在创建个  NetWordUtils 类里写
private static String  tag = "NetWordUtils";/** * 获取网络json * * @param urlString * @return */public static String getNetjson(String urlString) {    try {        URL url = new URL(urlString);        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();        urlConnection.setRequestMethod("GET");//若果是get请求可以不用配置; 其他请求必须配置        urlConnection.setConnectTimeout(8000);//设置链接超时间        InputStream inputStream = urlConnection.getInputStream();//获取网络返回的输入流;        //可拼接的字符串        StringBuilder stringBuilder = new StringBuilder();        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));        String temp = "";        while ((temp = bufferedReader.readLine()) != null) {            stringBuilder.append(temp);            temp = "";        }        //这个是网络获取的数据        String data = stringBuilder.toString();        Log.e(tag, "getData: " + data);        return data;    } catch (MalformedURLException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    return "";}/** * 获取网络图片的工具类 * * @param urlString * @return */public static Bitmap getNetBitmap(String urlString) {    try {        //用URL封装链接地址;        URL url = new URL(urlString);        //用url打开链接        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();        //联网的状态码        int responseCode = urlConnection.getResponseCode();        if(responseCode ==200){            //链接上获取输入流            InputStream inputStream = urlConnection.getInputStream();            //把流直接转换成bitmap(系统提供的BitmapFactory)            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//BitmapFactory是个工具类,系统提供的            return bitmap;        }else {            Log.e(tag, "网络状态码:: "+responseCode );        }    } catch (MalformedURLException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }    return null;}
五,在创建个 MApp 类,继承  Application 里写
public void onCreate() {    super.onCreate();    ImageLoaderConfiguration imageLoaderConfiguration=new ImageLoaderConfiguration.Builder(this).build();    ImageLoader.getInstance().init(imageLoaderConfiguration);}
六,在创建个 TouNews 类里写
private String string;public TouNews(String string) {    this.string = string;}public String getString() {    return string;}public void setString(String string) {    this.string = string;}
七,在创建个 News 这个类,里面写要解析的东西
原创粉丝点击