当我从数组中显示图像时,网格视图工作正常,但是当我试图从服务器显示图像时,它将无法工作并且给出一个空白屏幕。我有以下代码请告诉我我在哪里做错了。
1. Gridview的主要类
package com.grid_example;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
public class Grid_exampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
}
}
2.ImageAddpter类从服务器获取图像并在gridview中显示
package com.grid_example;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
String path;
Bitmap bmp;
// Bitmap[] bitmapArray = new Bitmap[20];
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(20);
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return bitmapArray.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(bitmapArray.get(position));
return imageView;
}
// references to our images
ImageAdapter() {
String xml = XMLfunctions_wallpaper.getXML();
Document doc = XMLfunctions_wallpaper.XMLfromString(xml);
// Document doc = XMLfunctions.XMLfromString(this.getResources().openRawResource(R.raw.music));
NodeList nodes = doc.getElementsByTagName("content");
for(int i=0;i<nodes.getLength();i++){
Element e=(Element)nodes.item(i);
try{
path=XMLfunctions_wallpaper.getValue(e,"previews");
System.out.println(path);
URL ulrn = new URL(path);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
// Bitmap bm = Bitmap.createBitmap(bmp);
bitmapArray.add(bmp); // Add a bitmap
}catch(Exception e1){}
}
}
}
3.XMLFunction_wallpaper类用于解析图像
package com.grid_example;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions_wallpaper {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* @param elem element (it is XML tag)
* @return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost("http://hellosunshine.in/keyss/music.xml");
HttpPost httpPost = new HttpPost("http://m.hellosunshine.in/content/wallpaper.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions_wallpaper.getElementValue(n.item(0));
}
}
4.我的gridview布局
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
感谢任何帮助。
答案 0 :(得分:2)
如果您从解析URL
获得的图像XML
是正确的,那么您可以首先创建一个Bitmap
数组,然后将其传递给您的适配器。将URL
转换为Bitmap
的代码如下:(如果您没有它。)
public static Bitmap getBitmapFromURL(String src) {
try {
Log.d("URL",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
编辑:以下是您需要使用的ArrayAdapter
课程,而非BaseAdapter
课程。
public class CustomAdapter extends ArrayAdapter<ImageView>{
Activity context;
int linearResource;
public CustomAdapter(Context context, int resources, List<ImageView> objects){
super(context, resources, objects);
this.context=(Activity) context;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView;
LayoutInflater mInflater = context.getLayoutInflater();
if (convertView == null){
row = getItem(position);
}
else{
imageView= (ImageView) mInflater.inflate(R.layout.images, null);
//or imageView=new imageView(context);
}
return imageView;
}
}
在GridView中设置适配器时,请使用以下代码。
gridView.setAdapter(new CustomAdapter(this, 0, imageData));//Where imageData is the ArraList<ImageView> type and where you've stored your ImageViews.