Fork me on GitHub
Android豆瓣图书查询Demo

Android豆瓣图书查询Demo

首先先看一下Demo预览效果吧,主要也就是两个Activity。涉及到的技术有zxing开源项目的使用,网络协议豆瓣API的调用,JSON数据的解析,多线程以及Handler的使用,还有Intent传递Object对象的方式。

   

看下项目的组织框架。MainActivity,BookView分别是两个界面的Activity,BookInfo是书籍信息的类,Util就是一些工具类,有解析JSON数据的方法,下载图书信息的方法之类的。下面google.zxing.integeration.android包中的内容是完全引入zxing开源项目的东西。

一.Zxing类库的使用。https://code.google.com/p/zxing/

1.首先安装Zxing的apk。

2.下载两个接口文件,IntentIntegrator.java,IntentResult.java 文件,当时在网上找了半天都下不下来。这里给大家共享了!https://files.cnblogs.com/itstudent/zxing.zip

3.Zxing的使用

开始调用:

IntentIntegrator integrator=new IntentIntegrator(MainActivity.this);
integrator.initiateScan();

然后复写onActivityResult这个方法:

public void onActivityResult(int requestCode,int resultCode,Intent data)
{
  IntentResult result=IntentIntegrator.parseActivityResult(requestCode,resultCode,data);

  //result即为扫描结果,result.getContents()  返回图书的ISBN码。

二.启用下载线程下载,解析图书信息

得到ISBN码后就可以获取图书的信息了,这里为了避免下载过程中导致UI主界面阻塞,所以我们新起一个下载线程来下载,获取图书资料信息。

 

private class DownloadThread extends Thread
{
    String url=null;
    public DownloadThread(String urlstr)
    {
        url=urlstr;
    }
    public void run()
    {
        String result=Util.Download(url);
        BookInfo book=new Util().parseBookInfo(result);
 
        //给主线程UI界面发消息,提醒下载信息,解析信息完毕
        Message msg=Message.obtain();
        msg.obj=book;
        hd.sendMessage(msg);
    }
}

 

在这里就提到了Util类中的两个主要方法: 

(1)public static String Download(String urlstr)   

 

public static String Download(String urlstr)
{
    String result="";
    try{
        URL url=new URL(urlstr);
        URLConnection connection =url.openConnection();
 
        String line;
        BufferedReader in = new BufferedReader(new         InputStreamReader(connection.getInputStream(),"UTF-8"));
        while ((line = in.readLine()) != null) {
            result += line;
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
    return  result;
}

 

(2)    public BookInfo parseBookInfo(String str)

豆瓣API链接地址:https://api.douban.com/v2/book/isbn/编号

因为豆瓣返回的JSON数据形式是这样的:

  “titile”:"",

  "image":"http:\/\/",

  "author":["",""],

  .....

仔细看下可以知道返回的数据形式除了image,author,其他的都是字符串类型,很容易拿到。

但是image返回的是图片链接的形式,所以需要     public Bitmap DownloadBitmap(String bmurl)方法获取Bitmap,

而author这个数据返回的是JSONArray类型,所以需要    public String parseJSONArraytoString (JSONArray arr)将字符串数组解析成字符串。

 

    public BookInfo parseBookInfo(String str)
    {
        BookInfo info=new BookInfo();
        try{
            JSONObject mess=new JSONObject(str);
            info.setTitle(mess.getString("title"));
            info.setBitmap(DownloadBitmap(mess.getString("image")));
            info.setAuthor(parseJSONArraytoString(mess.getJSONArray("author")));
            info.setPublisher(mess.getString("publisher"));
            info.setPublishDate(mess.getString("pubdate"));
            info.setISBN(mess.getString("isbn13"));
            info.setSummary(mess.getString("summary"));
 
        }catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }
 
     public Bitmap DownloadBitmap(String bmurl)
     {
         Bitmap bm=null;
         InputStream is =null;
         BufferedInputStream bis=null;
         try{
             URL  url=new URL(bmurl);
             URLConnection connection=url.openConnection();
             bis=new BufferedInputStream(connection.getInputStream());
             bm= BitmapFactory.decodeStream(bis);
         }catch (Exception e){
             e.printStackTrace();
         }
         finally {
             try {
                 if(bis!=null)
                     bis.close();
                 if (is!=null)
                     is.close();
             }catch (Exception e){
                 e.printStackTrace();
             }
         }
         return bm;
     }
    public String parseJSONArraytoString (JSONArray arr)
    {
        StringBuffer str =new StringBuffer();
        for(int i=0;i<arr.length();i++)
        {
            try{
                str=str.append(arr.getString(i)).append(" ");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return str.toString();
    }
}

 

  (3)从下载线程中得到返回的BookInfo数据之后,必须要通过Handler发送个UI主线程中。

UI主线程中:
  
       hd=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                BookInfo book= (BookInfo)msg.obj;
 
                //进度条消失
                mpd.dismiss();
 
                Intent intent=new Intent(MainActivity.this,BookView.class);
                intent.putExtra(BookInfo.class.getName(),book);
                startActivity(intent);
            }
        };
 
 
下载线程中(下载解析完毕后):
            Message msg=Message.obtain();
            msg.obj=book;
            hd.sendMessage(msg);


(4)Intent发送Object对象
在MainActivity中得到了Handler返回的BookInfo还需要通过Intent传递给BookView界面上显示出来。所以就涉及到Intent传递Object对象的问题。有两种方式:一是传递的对象需要实现Serializable接口,另一种是实现Parcelable接口。

这里采用的是方式二: 

实现Parcelable接口要实现他的三个方法。

public class BookInfo implements Parcelable   
 
 
 public static final Parcelable.Creator<BookInfo> CREATOR = new Creator<BookInfo>() {
    public BookInfo createFromParcel(Parcel source) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.mTitle = source.readString();
        bookInfo.mBitmap = source.readParcelable(Bitmap.class.getClassLoader());
        bookInfo.mAuthor = source.readString();
        bookInfo.mPublisher = source.readString();
        bookInfo.mPublishDate = source.readString();
        bookInfo.mISBN = source.readString();
        bookInfo.mSummary = source.readString();
        return bookInfo;
    }
    public BookInfo[] newArray(int size) {
        return new BookInfo[size];
    }
};
public int describeContents() {
    return 0;
}
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(mTitle);
    dest.writeParcelable(mBitmap, flags);
    dest.writeString(mAuthor);
    dest.writeString(mPublisher);
    dest.writeString(mPublishDate);
    dest.writeString(mISBN);
    dest.writeString(mSummary);
}

 

//然后直接使用Intent发送:
    Intent intent=new Intent(MainActivity.this,BookView.class);
    intent.putExtra(BookInfo.class.getName(),book);
    startActivity(intent);
 
 
//最后在BookView中这样得到这个BookInfo:
          intent=getIntent();
          BookInfo book=(BookInfo)intent.getParcelableExtra(BookInfo.class.getName());
 
 
分类: Android
posted on 2013-07-12 16:03  HackerVirus  阅读(376)  评论(0编辑  收藏  举报