• 第二阶段:团队开发Fooks第七天


    实现了加入书架的功能

     

    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 AddBookshelfServlet 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 bookname =request.getParameter("bookName");
            String username =request.getParameter("username");
    
            Bookshelf bookshelf =new Bookshelf(bookname,username);
            dao dao =new dao();
            PrintWriter out = response.getWriter();
            JSONObject json=new JSONObject();
            if(dao.addshelf(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);
        }
    
    }
    AddBookshelfServlet.java
    package com.example.fooks.utils;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.example.fooks.R;
    import com.example.fooks.entity.Book;
    import com.example.fooks.entity.Bookshelf;
    
    import java.util.List;
    
    
    public class ShopsAdapter extends BaseAdapter {
        private List<Book> mList;
        private Context mContext;
        private LayoutInflater mLayoutInflater;
    
    
        public ShopsAdapter(List<Book> mList, Context mContext) {
            this.mList = mList;
            this.mContext = mContext;
            this.mLayoutInflater = LayoutInflater.from(mContext);
        }
    
        @Override
        public int getCount() {
            return mList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if(convertView==null)
            {
                viewHolder= new ViewHolder();
                convertView=mLayoutInflater.inflate(R.layout.booklist,null);
                viewHolder.mBook= convertView.findViewById(R.id.book_show);
                convertView.setTag(viewHolder);
            }else {
                viewHolder=(ViewHolder)convertView.getTag();
            }
    
            Book book=mList.get(position);
            viewHolder.mBook.setText(book.getBookName());
    
            return convertView;
        }
    }
    ShopsAdapter.java
    package com.example.fooks;
    
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    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.appcompat.app.AppCompatActivity;
    import androidx.recyclerview.widget.GridLayoutManager;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.OrientationHelper;
    import androidx.recyclerview.widget.RecyclerView;
    import androidx.recyclerview.widget.StaggeredGridLayoutManager;
    
    import com.example.fooks.entity.Book;
    import com.example.fooks.entity.Bookshelf;
    import com.example.fooks.utils.BooksAdapter;
    import com.example.fooks.utils.ShopsAdapter;
    import com.example.fooks.utils.ViewHolder;
    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.RequestParams;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    
    import cz.msebera.android.httpclient.Header;
    
    public class ListActivity extends AppCompatActivity {
        private String mUsername;
        private Button mHome;
        private Button mBook;
        private Button mPerson;
        private ListView mListView;
        private EditText editText;
        private EditText editText2;
        private ShopsAdapter mShopsAdapter;
        private List<Book> mShowBooks  =new ArrayList<>();
        private List <ViewHolder> mViewHolder;
        private static String TAG="ListActivity";
        //设置返回按钮:不应该退出程序---而是返回桌面
        //复写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 onPause() {
            overridePendingTransition(0,0);
            super.onPause();
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list);
    
            Intent intent = getIntent();
            mUsername = intent.getStringExtra("username");
            //
            mBook = (Button) this.findViewById(R.id.btn_book);
            mHome = (Button) this.findViewById(R.id.btn_home);
    
            mPerson = (Button) this.findViewById(R.id.btn_person);
    
            mListView=(ListView)this.findViewById(R.id.shop_booklist);
    
            //把输入框变成分割线 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);
    
            //
            mPerson.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ListActivity.this, UserActivity.class);
                    intent.putExtra("username", mUsername);
                    startActivity(intent);
                    ListActivity.this.overridePendingTransition(0, 0);
    
                }
            });
            mHome.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ListActivity.this, MainActivity.class);
                    intent.putExtra("username", mUsername);
                    startActivity(intent);
                    ListActivity.this.overridePendingTransition(0, 0);
    
                }
            });
            mBook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ListActivity.this, ReadActivity.class);
                    intent.putExtra("username", mUsername);
                    startActivity(intent);
                    ListActivity.this.overridePendingTransition(0, 0);
                }
            });
    
            //点击加入书架
           mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                   Book book = mShowBooks.get(position);
                   //定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框
                   AlertDialog.Builder builder = new AlertDialog.Builder(ListActivity.this);
                   builder.setMessage("确定将本书加入书架?");
                   builder.setTitle("提示");
    
                   //添加AlertDialog.Builder对象的setPositiveButton()方法
                   builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           Log.e(TAG, "书架信息:" + book);
                           AddtoBookshelf(book);
                       }
                   });
                   //添加AlertDialog.Builder对象的setNegativeButton()方法
                   builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
    
                       }
                   });
    
                   builder.create().show();
               }
           });
    
    
    
            initBook();
    
        }
    
        private void AddtoBookshelf(Book book) {
            AsyncHttpClient client =new AsyncHttpClient();
            String url = "http://47.94.229.72:8080/Fooks/AddBookshelfServlet";//url组成:ip:端口 + 服务端工程名 + servlet名
            RequestParams params = new RequestParams();
            params.put("username",mUsername);
            params.put("bookName",book.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(ListActivity.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();
                }
            });
        }
    
        private void initBook(){
    
            //获取数据
            AsyncHttpClient client =new AsyncHttpClient();
            String url = "http://47.94.229.72:8080/Fooks/BookListServlet";//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);
                                    Book book =new Book();
                                    book.setId(jsonObject.getInt("id"));
                                    book.setBookName(jsonObject.getString("bookName"));
                                    book.setBookPath(jsonObject.getString("bookPath"));
                                    book.setCreateUser(jsonObject.getString("createUser"));
                                    book.setCreateDate(jsonObject.getString("createDate"));
                                    mShowBooks.add(book);
                                }
                                mShopsAdapter=new ShopsAdapter(mShowBooks,ListActivity.this);
                                mListView.setAdapter(mShopsAdapter);
    
                            } 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();
                }
            });
        }
    }
    ListActivity.java
  • 相关阅读:
    Niagara技术文档汇总
    cPickle对python对象进行序列化,序列化到文件或内存
    html = data.decode('gbk').encode('utf-8')
    用200行Python代码“换脸”
    No module named cv2
    JAVA Calendar具体解释
    千万别用模板给的list.size()巨坑
    div仿checkbox表单样式美化及功能
    动态规划0—1背包问题
    拒绝乱码:做外贸系统,打印俄文快递单时,避免俄文乱码的方法
  • 原文地址:https://www.cnblogs.com/yeyueweiliang/p/13019860.html
Copyright © 2020-2023  润新知