第二阶段:团队开发Fooks第五天
从书架删除书籍的功能
点击长按该书籍
成功实现从书架删除书籍的功能
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.fooks; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.Nullable; import com.example.fooks.entity.Book; import com.example.fooks.entity.Bookshelf; import com.example.fooks.utils.BooksAdapter; import com.example.fooks.utils.ViewHolder; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.FileAsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; public class ReadActivity extends Activity { private String mUsername; private Button mHome; private Button mBook; private Button mList; private Button mPerson; private Button mUpload; private EditText editText; private EditText editText2; private ListView mListView; private List<Bookshelf> mShowBookShelfs =new ArrayList<>(); private List <ViewHolder> mViewHolder; private static final int FILE_SELECT_CODE = 0; private static String TAG="ReadActivity"; //设置返回按钮:不应该退出程序---而是返回桌面 //复写onKeyDown事件 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent home = new Intent(Intent.ACTION_MAIN); home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); home.addCategory(Intent.CATEGORY_HOME); startActivity(home); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_read); //把输入框变成分割线 by:scf editText=this.findViewById(R.id.editText); editText2=this.findViewById(R.id.editText2); editText.setFocusableInTouchMode(false);//不可编辑 editText.setKeyListener(null); editText2.setFocusableInTouchMode(false);//不可编辑 editText2.setKeyListener(null); Intent intent =getIntent(); mUsername =intent.getStringExtra("username"); mListView=(ListView) this.findViewById(R.id.book_list) ; //初始化控件 initView(); initListener(); initBook(); } private void initBook() { ListView ShowBookList=(ListView)findViewById(R.id.book_list); //获取数据 AsyncHttpClient client =new AsyncHttpClient(); String url = "http://47.94.229.72:8080/Fooks/BookshelfServlet";//url组成:ip:端口 + 服务端工程名 + servlet名 RequestParams params = new RequestParams(); params.put("username",mUsername); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { if(i == 200) { try { String result = new String(bytes,"utf-8"); Log.e(TAG,"返回结果"+result); try { JSONArray jsonArray = new JSONArray(result); for(int j=0;j<jsonArray.length();j++){ JSONObject jsonObject=jsonArray.getJSONObject(j); Bookshelf bookshelf =new Bookshelf(); bookshelf.setId(jsonObject.getInt("id")); bookshelf.setBookName(jsonObject.getString("bookName")); bookshelf.setUsername(jsonObject.getString("username")); mShowBookShelfs.add(bookshelf); } BooksAdapter booksAdapter=new BooksAdapter(mShowBookShelfs,ReadActivity.this); ShowBookList.setAdapter(booksAdapter); } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { Toast.makeText(getApplicationContext(),"请求失败,请检查网络",Toast.LENGTH_LONG).show(); } }); } private void initListener() { mUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { upLoad(); } }); mHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ReadActivity.this,MainActivity.class); intent.putExtra("username",mUsername); startActivity(intent); ReadActivity.this.overridePendingTransition(0, 0); } }); mList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ReadActivity.this,ListActivity.class); intent.putExtra("username",mUsername); startActivity(intent); ReadActivity.this.overridePendingTransition(0, 0); } }); mPerson.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ReadActivity.this,UserActivity.class); intent.putExtra("username",mUsername); startActivity(intent); ReadActivity.this.overridePendingTransition(0, 0); } }); //书籍列表的点击事件 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Bookshelf bookshelf=mShowBookShelfs.get(position); String path=Environment.getExternalStorageDirectory()+"/Fooks/Book/"+bookshelf.getBookName(); File file =new File(path); if(file.exists()){ Intent intent =new Intent(ReadActivity.this,BookActivity.class); intent.putExtra("username",mUsername); intent.putExtra("bookName",bookshelf.getBookName()); intent.putExtra("path",path); startActivity(intent); }else { Toast.makeText(getApplicationContext(),"开始下载,请耐心等待",Toast.LENGTH_LONG).show(); Log.e(TAG,"book:"+bookshelf); Log.e(TAG,"path:"+path); DownLoadBook(bookshelf,path); } } }); //书籍列表的长按删除 mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { //定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框 AlertDialog.Builder builder=new AlertDialog.Builder(ReadActivity.this); builder.setMessage("确定删除?"); builder.setTitle("提示"); Bookshelf bookshelf=mShowBookShelfs.get(position); //添加AlertDialog.Builder对象的setPositiveButton()方法 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.e(TAG,"书架信息:"+bookshelf); DeleteBookshelf(bookshelf); } }); //添加AlertDialog.Builder对象的setNegativeButton()方法 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return false; } }); } @Override protected void onPause() { overridePendingTransition(0,0); super.onPause(); } private void DownLoadBook(Bookshelf bookshelf,String path) { AsyncHttpClient client =new AsyncHttpClient(); String url = "http://47.94.229.72:8080/Fooks/Book/";//url组成:ip:端口 + 服务端工程名 + servlet名 try { String URL=URLEncoder.encode(bookshelf.getBookName(),"utf-8"); URL=URL.replaceAll("\\+", "%20"); Log.e(TAG,url+URL); client.post(url+URL, new FileAsyncHttpResponseHandler(new File(path)) { @Override public void onFailure(int i, Header[] headers, Throwable throwable, File file) { Toast.makeText(getApplicationContext(),"下载失败,请检查网络",Toast.LENGTH_LONG).show(); } @Override public void onSuccess(int i, Header[] headers, File file) { Toast.makeText(getApplicationContext(),"下载成功,点击打开",Toast.LENGTH_LONG).show(); } }); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } private void upLoad() { Intent intent = new Intent(ReadActivity.this,AddActivity.class); intent.putExtra("username",mUsername); startActivity(intent); } private void initView() { mBook=(Button) this.findViewById(R.id.btn_list); mHome=(Button) this.findViewById(R.id.btn_home); mList=(Button) this.findViewById(R.id.btn_list); mPerson=(Button) this.findViewById(R.id.btn_person); mUpload=(Button) this.findViewById(R.id.book_upload); } private void DeleteBookshelf(Bookshelf bookshelf) { AsyncHttpClient client =new AsyncHttpClient(); String url = "http://47.94.229.72:8080/Fooks/DeleteBookshelfServlet";//url组成:ip:端口 + 服务端工程名 + servlet名 RequestParams params = new RequestParams(); params.put("username",bookshelf.getUsername()); params.put("BookName",bookshelf.getBookName()); client.post(url, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { if(i == 200) { try { String result = new String(bytes, "utf-8"); try { JSONObject jsonObject = new JSONObject(result); int s = jsonObject.getInt("result"); switch (s) { case 0: Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_LONG).show(); break; case 1: Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getApplicationContext(), "未知错误", Toast.LENGTH_LONG).show(); break; } } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(ReadActivity.this, result, Toast.LENGTH_SHORT).show(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { Toast.makeText(getApplicationContext(),"请求失败,请检查网络",Toast.LENGTH_LONG).show(); } }); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package Servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.dao; import entity.Book; import entity.Bookshelf; import net.sf.json.JSONObject; public class DeleteBookshelfServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); String username=request.getParameter("username"); String bookname =request.getParameter("BookName"); Bookshelf bookshelf =new Bookshelf(bookname,username); dao dao =new dao(); PrintWriter out = response.getWriter(); JSONObject json=new JSONObject(); if(dao.deleteshelf(bookshelf)) { json.put("result", 1); out.print(json); }else { json.put("result", 0); out.print(json); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }