Struts服务器端+Android客户端+json数据(二)
程序员文章站
2024-03-23 11:18:46
...
上文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;
}
}
推荐阅读
-
Struts服务器端+Android客户端+json数据(二)
-
android客户端与javaweb服务器端数据通信-异步Get
-
android客户端与javaweb服务器端数据通信-Post-键值对
-
Android构建JSON数据(构建篇二:HashMap构建)
-
Android入门——数据解析之使用GSON解析JSON字符串(二)
-
dragon boat festival php实现post接口 接收android客户端json数据 存储数据库 并返回json
-
Android开发使用json实现服务器与客户端数据的交互功能示例
-
android客户端从服务器端获取json数据并解析的实现代码
-
Android开发使用json实现服务器与客户端数据的交互功能示例
-
android客户端从服务器端获取json数据并解析的实现代码