新手学习,用的方法可能不太恰当,代码很粗糙。
根据网址返回信息获取需要的信息并显示出来,由于我自己用的网址返回信息是键值对的字符串形式,因此其中代码可能不适用与其他地方。从返回值中截取的3个信息名为imageUrlWeb,discountDescription,countentSortType。其中imageUrlWeb为图片url.
main.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/MyListView">
</ListView>
</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_width="80dp"
android:layout_height="80dp"
android:padding="10dp"
/>
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/image"
android:layout_margin="10dp"
android:textStyle="bold"
>
</TextView>
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/image"
android:layout_below="@+id/textview"
android:layout_marginLeft="10dp"
>
</TextView>
</RelativeLayout>
main.java
package com.example.a;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CopyOfweiActivity extends Activity {
private ListView listView;
Bitmap myImage = null;
ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weixin);
listView = (ListView) findViewById(R.id.MyListView);
// 进来调用网络获取数据
myTask m = new myTask();
m.execute("获取信息的网址,键值对");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class myTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpClient c = new DefaultHttpClient();
HttpGet g = new HttpGet(arg0[0]);
HttpResponse r = c.execute(g);
if (r.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = r.getEntity();
InputStream is = entity.getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = -1;
while ((length = is.read(buf)) != -1) {
baos.write(buf, 0, length);
}
return new String(baos.toByteArray(), "utf-8");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// publishProgress(50);
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// imageUrlWeb,discountDescription,countentSortType,
try {
JSONObject j = new JSONObject(result);
JSONArray jsonArray = new JSONArray(j.getString("items"));
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i = 0; i < jsonArray.length(); i++) {
Map<String, String> map = new HashMap<String, String>();
JSONObject item = jsonArray.getJSONObject(i);
String imageUrlWeb = item.getString("imageUrlWeb");
String discountDescription = item
.getString("discountDescription");
String countentSortType = item
.getString("countentSortType");
map.put("img", imageUrlWeb);
map.put("title", discountDescription);
map.put("content", countentSortType);
list.add(map);
}
// 装载输入填充adapter适配器
myAdapter madapter = new myAdapter(CopyOfweiActivity.this, list);
listView.setAdapter(madapter);
madapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class myAdapter extends BaseAdapter {
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
Context context;
LayoutInflater layoutInflater;
public myAdapter(Context c, ArrayList<Map<String, String>> list2) {
// TODO Auto-generated constructor stub
context = c;
list = list2;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
ConvertView convertView = null;
if (convertView == null) {
view = LayoutInflater.from(CopyOfweiActivity.this).inflate(
R.layout.listitem, null);
convertView = new ConvertView();
convertView.t1 = (TextView) view
.findViewById(R.id.textview);
convertView.t2 = (TextView) view
.findViewById(R.id.textview2);
convertView.i = (ImageView) view.findViewById(R.id.image);
view.setTag(convertView); // 缓存
}
convertView.t1.setText(list.get(position).get("title")
.toString());
convertView.t2.setText(list.get(position).get("content")
.toString());
// 获取网络图片
// convertView.i.setImageBitmap((Bitmap)list.get(position).get("img"));
new BitMapAsy(convertView.i).execute(list.get(position).get(
"img"));
return view;
}
}
class ConvertView {
public TextView t1;
public TextView t2;
public ImageView i;
}
class BitMapAsy extends AsyncTask<String, Integer, Bitmap> {
private ImageView img;
public BitMapAsy(ImageView img) {
this.img = img;
}
@Override
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub
URL myFileURL = null;
Bitmap bitmap = null;
try {
myFileURL = new URL(arg0[0]);
HttpURLConnection conn = (HttpURLConnection) myFileURL
.openConnection();
conn.setConnectTimeout(6000);
conn.setDoInput(true);
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
img.setImageBitmap(result);
}
}
}
}
到此以上为完整代码。
编写之时原本是将图片资源获取到之后和其他两个字符串一起放入到map中,发现会报OOM错误,经查找得知可使用LinkedHashMap <String,SoftReference<Bitmap> >来代替map。
SoftReference,软引用,在内存空间不足时会回收这种对象的内存。
新建软引用对象:SoftReference<Bitmap> s = new SoftReference<Bitmap>(myImage); myImage为Bitmap对象
从软引用对象获取:s.get(); 返回原来的类型
package com.example.a;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class weiActivity extends Activity {
private ListView listView;
Bitmap myImage = null;
// private List<String> data= new ArrayList<String>();HashMap <String,Bitmap> mSoftCache
ArrayList<LinkedHashMap <String,SoftReference<Bitmap> >> mylist = new ArrayList<LinkedHashMap <String,SoftReference<Bitmap>>>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weixin);
listView = (ListView) findViewById(R.id.MyListView);
//进来调用网络获取数据
myTask m = new myTask();
m.execute("http://tepin.e9448.com/mserver1/getActivityPlanningByType.bdo?channelType=wap");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class myTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpClient c = new DefaultHttpClient();
HttpGet g = new HttpGet(arg0[0]);
HttpResponse r = c.execute(g);
if (r.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = r.getEntity();
InputStream is = entity.getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = -1;
while ((length = is.read(buf)) != -1) {
baos.write(buf, 0, length);
}
return new String(baos.toByteArray(), "utf-8");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// publishProgress(50);
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// imageUrlWeb,discountDescription,countentSortType,
try {
JSONObject j = new JSONObject(result);
JSONArray jsonArray = new JSONArray(j.getString("items"));
ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i = 0; i < jsonArray.length(); i++) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
JSONObject item = jsonArray.getJSONObject(i);
String imageUrlWeb = item.getString("imageUrlWeb");
String discountDescription = item.getString("discountDescription");
String countentSortType = item.getString("countentSortType");
Runnableupdate r = new Runnableupdate(handler, imageUrlWeb,discountDescription,countentSortType);
new Thread(r).start();
}
//装载输入填充adapter适配器
myAdapter madapter = new myAdapter(weiActivity.this, mylist);
listView.setAdapter(madapter);
madapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class Runnableupdate implements Runnable {
private Handler handler;
String uri;
String discountDescription;
String countentSortType;
public Runnableupdate(Handler handler, String uri, String d, String c) {
super();
this.handler = handler;
this.uri = uri;discountDescription=d;countentSortType=c;
}
public void run() {
URL myFileURL = null;
Bitmap bitmap = null;
try {
myFileURL = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
conn.setConnectTimeout(6000);
conn.setDoInput(true);
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
Message msg = new Message();
Bundle b = new Bundle();
b.putParcelable("image", bitmap);b.putString("discountDescription", discountDescription);b.putString("countentSortType", countentSortType);
msg.setData(b);
msg.what = 1;
handler.sendMessage(msg);
}
}
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
myImage = (Bitmap) msg.getData().get("image");
LinkedHashMap<String, SoftReference<Bitmap>> map = new LinkedHashMap<String, SoftReference<Bitmap>>(); // 存放到MAP里面
SoftReference<Bitmap> s = new SoftReference<Bitmap>(myImage);
map.put("image", s);
mylist.add(map);
}
}
};
class myAdapter extends BaseAdapter {
//HashMap <String,Bitmap>
ArrayList<LinkedHashMap <String,SoftReference<Bitmap>>> list = new ArrayList<LinkedHashMap <String,SoftReference<Bitmap>>>();
Context context;
LayoutInflater layoutInflater;
public myAdapter(Context c, ArrayList<LinkedHashMap <String,SoftReference<Bitmap>>> list2) {
// TODO Auto-generated constructor stub
context = c;
list = list2;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
ConvertView convertView = null;
if (convertView == null) {
view = LayoutInflater.from(weiActivity.this).inflate(R.layout.listitem, null);
convertView = new ConvertView();
convertView.i = (ImageView) view.findViewById(R.id.image);
view.setTag(convertView); // 缓存
}
//获取网络图片
convertView.i.setImageBitmap(list.get(position).get("image").get());
return view;
}
}
class ConvertView {
public ImageView i;
}
}
转载请注明出处