Struts服务器端+Android客户端+json数据(二)

上文Struts服务器端+Android客户端+json数据(一)主要展示了服务器端代码的编写,这里主要展示Android客户端的代码。

首先需要在AndroidManifest.xml配置访问网络的权限:
<uses-permission android:name="android.permission.INTERNET"/>

图书列表book_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:id="@+id/bookList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">        
    </ListView>
</LinearLayout>

book_item.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" >
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <TextView 
            android:id="@+id/bookIsbn"
            android:layout_width="30dip"
            android:layout_height="wrap_content"/>
        <TextView 
            android:id="@+id/bookTitle"
            android:layout_width="70dp"
            android:layout_height="wrap_content"/>
        <TextView 
            android:id="@+id/bookPrice"
            android:layout_width="30dip"
            android:layout_height="wrap_content"/>
        <ImageView
            android:id="@+id/bookImage"
            android:layout_width="90dp"
            android:layout_height="80dp"/>
        <Button 
            android:id="@+id/bookDelete"
            android:layout_width="50dip"
            android:layout_height="35dip"
            android:text="删除"
            android:textSize="12dip"
            android:textColor="#000000"/>
    </LinearLayout>
</LinearLayout>

BookMainActivity.java
适配器建议使用时单独放置在一个文件中,我这里直接写成了内部类的形式,可根据自己的要求独立出来。

public class BookMainActivity extends Activity {
    //getBooks.action中getBooks必须和服务器端struts.xml配置文件的action name一致,.action可写可不写
    private static String URL="http://10.0.2.2:8080/服务器端文件的工程名/getBooks.action";
    private static String IMAGEURL="http://10.0.2.2:8080/服务器端文件的工程名";
    private static String DELEURL="http://10.0.2.2:8080/服务器端文件的工程名/deleteBook.action?";
    //deleteBook.action?加问号是后面还需要加参数bookId
    ListView lv;
    Bitmap bitmap;
    Button delBt;
    BookManageMentUtil bm;
    boolean bl=false;
    List<HashMap<String,Object>> books;
    HashMap<String,Object> book;//存放一本书
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.book_main);
        init();
        getBooksFormServer(this.URL);
    }
    private void getBooksFormServer(String url2) {
        new AsyncTask<String,Void,List<HashMap<String,Object>>>(){

            @Override
            protected List<HashMap<String, Object>> doInBackground(String... params) {
                // 访问服务器
                books=bm.getBooksListFromServer(params[0]);
                return books;
            }
            protected void onPostExecute(List<HashMap<String,Object>> books) {
                MyAdapter ma=new MyAdapter();
                lv.setAdapter(ma);
            }
        }.execute(url2);

    }
    public class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return books.size();
        }

        @Override
        public Object getItem(int arg0) {
            return books.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LinearLayout ll=(LinearLayout)View.inflate(getApplicationContext(),
                    R.layout.book_item, null);
            TextView bookIsbn=(TextView)ll.findViewById(R.id.bookIsbn);
            bookIsbn.setText(books.get(position).get("isbn").toString());

            TextView bookTitle=(TextView)ll.findViewById(R.id.bookTitle);
            bookTitle.setText(books.get(position).get("title").toString());

            TextView bookPrice=(TextView)ll.findViewById(R.id.bookPrice);
            bookPrice.setText(books.get(position).get("price").toString());

            ImageView bookImage=(ImageView)ll.findViewById(R.id.bookImage);
            //重新new一个线程下载图片
            bitmap=bm.getBookImage(IMAGEURL+books.get(position).get("bookImage"));
            bookImage.setImageBitmap(bitmap);

            final int bookId=((Integer)books.get(position).get("bookId")).intValue();
            delBt=(Button)ll.findViewById(R.id.bookDelete);
            delBt.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    /*
                     * 创建对话框,是否删除记录
                     */
                    AlertDialog.Builder bd=new Builder(BookMainActivity.this);
                    bd.setTitle("对话框");
                    bd.setMessage("骚年,确定删除吗");
                    bd.setNegativeButton("取消", null);
                    bd.setPositiveButton("确定",new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {    
                            delBookFromServer(DELEURL,bookId);
                        }
                    }); 
                    bd.create().show();
                }
            });
            return ll;
        }   
    }

    public void delBookFromServer(String dELEURL, int bookId
            ) {
        new AsyncTask<String, Void,String>() {
            @Override
            protected String doInBackground(
                    String... params) {
                String delResult="";
                try {
                    HttpClient hc=new DefaultHttpClient();
                    HttpPost request=new HttpPost(params[0]);
                    HttpResponse response=null;
                    response=hc.execute(request);
                    if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity entity=response.getEntity();
                        String strJson=EntityUtils.toString(entity,"utf-8");
                        if(strJson!=null){
                            JSONObject jsonObject=new JSONObject(strJson);
                            delResult=jsonObject.get("message").toString();
                        }
                    }else{
                        delResult="没有网络或服务器连接不上!";
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
                return delResult;
            }

            public void onPostExecute(String result){
                System.out.println("the result="+result);
                if(result.equals("删除成功")){                  
                    Intent it=new Intent();
                    it.setClass(getApplicationContext(), BookMainActivity.class);
                    startActivity(it);
                    BookMainActivity.this.finish();
                }
            }
        }.execute(dELEURL+"bookId="+bookId);    
    }

    private void init() {
        // TODO Auto-generated method stub
        lv=(ListView)this.findViewById(R.id.bookList);
    }
}

图书管理的工具类:BookManageMentUtil.java
主方法中调用的方法都应写在这里,使主activity更清爽。但是删除操作,传参出了点问题,所以未分离出来。

public class BookManageMentUtil {
    static Bitmap bitmap;
    public static List<HashMap<String, Object>> getBooksListFromServer(String url){
        HashMap<String, Object> book=null;
        List<HashMap<String, Object>> books=null;
        try {

            HttpClient hc=new DefaultHttpClient();
            HttpPost request=new HttpPost(url);
            HttpResponse response=null;
            response=hc.execute(request);
            if(response.getStatusLine().getStatusCode()==200) {

                HttpEntity entity=response.getEntity();
                String strJson=EntityUtils.toString(entity,"utf-8");
                if(strJson!=null) {
                    JSONArray jsonArray=new JSONArray(strJson);
                    books=new ArrayList<HashMap<String, Object>>();
                    for(int i=0;i<jsonArray.length();i++) {
                        JSONObject jsonObject=(JSONObject)jsonArray.get(i);
                        book=new HashMap<String, Object>();
                        book.put("bookId",jsonObject.get("bookId"));
                        book.put("isbn", jsonObject.get("isbn"));
                        book.put("title", jsonObject.get("title"));
                        book.put("price", jsonObject.get("price"));
                        book.put("bookImage", jsonObject.get("bookImage"));
                        books.add(book);
                    }
                }
            }else {
                System.out.println("BookManageMenyUtil....code......"+response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return books;

    }
    public static Bitmap getBookImage(final String url) {
        new Thread(){
            public void run(){
                URL imageUrl;
                try {
                    imageUrl = new URL(url);
                    //System.out.println("BookManageMentUtil getBookImage... url..."+url);
                    HttpURLConnection con=(HttpURLConnection)imageUrl.openConnection();
                    con.setRequestMethod("GET");
                    con.setRequestProperty("connection","keep-alive");
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    con.setReadTimeout(5000);
                    //System.out.println("code..."+con.getResponseCode());
                    if(con.getResponseCode()==200){
                        InputStream is=con.getInputStream();
                        bitmap=BitmapFactory.decodeStream(is);
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }.start();
        return bitmap;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值