将图像从xml文件加载到imageview中

时间:2013-12-27 12:10:38

标签: android xml xml-parsing

这个问题在stackoverflow中被多次询问,但我仍然没有得到答案,因此我发布了这个问题。

使用xml文件的解析器概念正在读取android中的xml文件。在那个xml文件中我声明了图像和文本。很清楚从xml文件显示文本,但我尝试将图像URL从xml文件显示到imageview。我提到了stackoverflow,但我仍然不知道如何从我的xml文件中显示图像。

这是我的xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<test>
<Category Type="entertainment">
<channel_name>sunmusic</channel_name>
<image_url>http://xxxx/xxxx/Images/news1.png</image_url>
</Category>
<Category Type="sports">
<channel_name>neosports</channel_name>
<image_url>http://xxxx/xxxx/Images/news2.png</image_url>
</Category>
</test>

我在服务器中加载了所有图片,链接工作正常。请帮我解决这个问题。

Customlistview.java

public class CustomListViewAdapter extends ArrayAdapter<TV> {
    Activity context;
    List<tv> tvlist;

    public CustomListViewAdapter(Activity context, List<TV> tvlist) {
        super(context, R.layout.list_item, tvlist);
        this.context = context;
        this.tvlist = tvlist;
    }

    /*private view holder class*/
    private class ViewHolder 
    {
        ImageView imageView;
        TextView txtCname;
            }

    public TV getItem(int position) 
    {
        return tvlist.get(position);
    }

    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ViewHolder holder;
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) 
        {
            convertView = inflater.inflate(R.layout.list_item, null);
            holder = new ViewHolder();
            holder.txtCname = (TextView) convertView.findViewById(R.id.channel_name);
            holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
            convertView.setTag(holder);
        } 
        else 
        {
            holder = (ViewHolder) convertView.getTag();
        }

        TV laptop = (TV) getItem(position); 
        holder.txtCname.setText(laptop.getChannelName());       
        holder.imageView.setImageBitmap(laptop.getImageBitmap());


        return convertView;
    }
}

tv.java

public class TV 
{   
        private String channel_name;               
        private String imageURL;
        private Bitmap imageBitmap;
        private String type;

        public String getChannelName() 
        {
            return channel_name;
        }
        public void setChannelName(String type) 
        {
            this.type = type;
        }   
        public String getType() 
        {
            return type;
        }
        public void setType(String channel_name) 
        {
            this.channel_name = channel_name;
        }   
        public String getImageURL() 
        {
            return imageURL;
        }
        public void setImageURL(String imageURL) 
        {
            this.imageURL = imageURL;
        }
        public Bitmap getImageBitmap() 
        {
            return imageBitmap;
        }
        public void setImageBitmap(Bitmap imageBitmap) 
        {
            this.imageBitmap = imageBitmap;
        }
    }

mainactivity.java

public class MainActivity extends Activity implements OnClickListener, OnItemClickListener 
{
    Button button;
    ListView listView;
    List<TV> tvlist;
    CustomListViewAdapter listViewAdapter;
    static final String URL = "http://xxxx/xxxx/Images/channeltest.xml";


    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewsById();
        button.setOnClickListener(this);
        listView.setOnItemClickListener(this);
    }

    private void findViewsById() 
    {
        button = (Button) findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.laptopList);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
    {

    }

    @Override
    public void onClick(View view) 
    {
        GetXMLTask task = new GetXMLTask(this);
        task.execute(new String[] { URL });
    }


    private class GetXMLTask extends AsyncTask<String, Void, List<TV>> 
    {
        private Activity context;
        public GetXMLTask(Activity context) 
        {
            this.context = context;
        }

        @Override
        protected void onPostExecute(List<TV> tvlist) 
        {
            listViewAdapter = new CustomListViewAdapter(context, tvlist);
            listView.setAdapter(listViewAdapter);
        }


        private String getXmlFromUrl(String urlString) 
        {
            StringBuffer output = new StringBuffer("");
            try 
            {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) 
                {
                    stream = httpConnection.getInputStream();
                    BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
                    String s = "";
                    while ((s = buffer.readLine()) != null)
                        output.append(s);
                }

            } 
            catch (Exception ex) 
            {
                ex.printStackTrace();
            }
            return output.toString();

        }  

        @Override
        protected List<TV> doInBackground(String... urls) 
        {
            List<TV> tvlist = null;
            String xml = null;
            for (String url : urls) 
            {
                xml = getXmlFromUrl(url);
                InputStream stream = new ByteArrayInputStream(xml.getBytes());
                tvlist = MsenseParsar.parse(stream);

                for (TV tv : tvlist) 
                {
                    String imageURL = tv.getImageURL();
                    Bitmap bitmap = null;
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    bmOptions.inSampleSize = 1;

                    try 
                    {
                        bitmap = BitmapFactory.decodeStream(new URL(imageURL).openStream(), null, bmOptions);
                    } 
                    catch (MalformedURLException e) 
                    {
                        e.printStackTrace();
                    } 
                    catch (IOException e) 
                    {
                        e.printStackTrace();
                    }
                    tv.setImageBitmap(bitmap);
                }
            }
        return tvlist;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你拥有的是xml。您需要先解析标记。获取网址,然后将下载的图片设置为ImageView

解析使用XmlPullParser。考试@

http://developer.android.com/training/basics/network-ops/xml.html

解析后

How to load an ImageView by URL in Android?

示例:

 public class MainActivity extends Activity {

    ImageView i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        i = (ImageView)findViewById(R.id.imageView1);
        new TheTask().execute();

    }

class TheTask extends AsyncTask<Void,Bitmap,Bitmap>
{

    @Override
    protected Bitmap doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
         Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png").getContent());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        i.setImageBitmap(result);

    }

}

}

编辑:

 tv.setImageBitmap(bitmap);

无法从非ui线程更新ui。在后台线程上调用doInbackground

EDIT2:

相应地修改以下内容

我正在从assests文件夹中解析xml。

 InputStream is = MainActivity.this.getResources()
      .getAssets().open("newxml.xml");

使用虚拟图像解析XML

<?xml version="1.0" encoding="UTF-8"?>
<test>
<Category Type="entertainment">
<channel_name>sunmusic</channel_name>
<image_url>http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png</image_url>
</Category>
<Category Type="sports">
<channel_name>neosports</channel_name>
<image_url>http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png</image_url>
</Category>
</test>

确保使用asynctask从url获取xml。下载UIL并将jar添加到libs文件夹。

public class MainActivity extends ListActivity {

    ImageView i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        try
        {
           InputStream is = MainActivity.this.getResources()
      .getAssets().open("newxml.xml");
        ParseXml pxml = new ParseXml();
        ArrayList<Entry> all=pxml.getList(is);
        LazyAdapter adapter = new LazyAdapter(this,all);
        setListAdapter(adapter);
        }catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

ParseXml

public class ParseXml {


    private static final String ns = null;
    InputStream is;
    ArrayList<Entry> all;
    public ArrayList<Entry> getList(InputStream is) {
        // TODO Auto-generated constructor stub
        this.is= is;
        try
        {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(is, null);
        parser.nextTag();
         all=readFeed(parser);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return  all;
    }
    private ArrayList<Entry> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
        ArrayList<Entry> entries = new ArrayList<Entry>();

        parser.require(XmlPullParser.START_TAG, ns, "test");
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            // Starts by looking for the entry tag
            if (name.equals("Category")) {
                entries.add(readEntry(parser));
            } else {
                skip(parser);
            }
        }  
        return entries;
    }
    private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
        parser.require(XmlPullParser.START_TAG, ns, "Category");
        String summary = null;
        String link = null;
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
           if (name.equals("channel_name")) {
                summary = readChannel(parser);
            } else if (name.equals("image_url")) {
                link = readUrl(parser);
            } else {
                skip(parser);
            }
        }
        return new Entry(summary, link);
    }
    private String readChannel(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "channel_name");
        String title = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "channel_name");
        Log.i("...........",title);
        return title;
    }
    private String readUrl(XmlPullParser parser) throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "image_url");
        String title = readText(parser);
        parser.require(XmlPullParser.END_TAG, ns, "image_url");
        Log.i("...........",title);
        return title;
    }
    // For the tags title and summary, extracts their text values.
    private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";
        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }
    private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }
}

LazyAdapter

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<Entry> data;
private LayoutInflater inflater=null;
public ImageLoader imageLoader; 
DisplayImageOptions options;

public LazyAdapter(Activity a, ArrayList<Entry> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    File cacheDir = StorageUtils.getOwnCacheDirectory(a, "MyFolderCache");


 // Get singletone instance of ImageLoader
   imageLoader = ImageLoader.getInstance();
 // Create configuration for ImageLoader (all options are optional)
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
              // You can pass your own memory cache implementation
             .discCacheExtraOptions(1024, 1024, CompressFormat.PNG, 100)
             .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
             .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
             .enableLogging()
             .build();
 // Initialize ImageLoader with created configuration. Do it once.
 imageLoader.init(config);
    //imageLoader.init(ImageLoaderConfiguration.createDefault(a));
   // imageLoader=new ImageLoader(activity.getApplicationContext());
    options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.ic_launcher)
    .cacheInMemory()
    .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(20))
    .build();
}



public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    ViewHolder vh = new ViewHolder();;
    if(convertView==null)
    {

    vi = inflater.inflate(R.layout.row, null);   
    vh.iv=(ImageView)vi.findViewById(R.id.imageView1); 
    vh.pb= (ProgressBar)vi.findViewById(R.id.pb); 
    vh.tv = (TextView) vi.findViewById(R.id.textView1);
    vh.tv1= (TextView) vi.findViewById(R.id.textView2);

    }
    Entry entry = data.get(position);
    vh.tv.setText(entry.channel);
    vh.tv1.setText(""+position);
    display(vh.iv,entry.url , vh.pb);
    //imageLoader.displayImage(data.get(position).toString(), image,options);

    return vi;
}

public void display(ImageView img, String url, final ProgressBar spinner)
{
    imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
         spinner.setVisibility(View.VISIBLE);
        }
        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
         spinner.setVisibility(View.GONE);


        }
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
         spinner.setVisibility(View.GONE);
        }
        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }

});
}
 public static class ViewHolder
 {
  ImageView iv;
  TextView tv,tv1;
  ProgressBar pb;

 }
}

row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/ic_launcher" />
 <ProgressBar 
    android:id="@+id/pb"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

 <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_above="@+id/textView2"
     android:layout_alignParentLeft="true"
     android:layout_marginBottom="21dp"
     android:layout_marginLeft="31dp"
     android:text="TextView" />

 <TextView
     android:id="@+id/textView2"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/textView1"
     android:layout_alignParentBottom="true"
     android:text="TextView" />

  </RelativeLayout>

对齐

enter image description here