一、认领任务
经过团队讨论,我认领到的工作是:利用数据库的数据实现益食物页面的布局,以二级目录显示食物列表
二、任务完成时间估算
页面布局 | 2h |
从数据库提取 | 5h |
益食物页面
展示如下:
可以从数据库提取数据。在这里感谢团队的闫起材体同学爬取的数据
主要用的是Tomcat+mysql搭建后台。
主要的实现代码:
foods(Activity)
package com.example.myapplication5; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.widget.ExpandableListView; import android.widget.ImageButton; import android.widget.SearchView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import com.alibaba.fastjson.JSON; import com.example.myapplication5.Shiwu; public class foods extends AppCompatActivity { // 定义扩展ExpandableListView 所需要变量 private ExpandableListView expandablelistview; private MyExpandAdapter myExpandAdapter; private ImageButton imageButton; // 一级名称 private String[] groupName = new String[]{"谷薯芋、杂豆、主食", "蛋类、肉类及制品", "奶类及制品","蔬果和菌藻","坚果、大豆及制品","饮料","食用油、油脂及制品","调味品","零食、点心、冷饮","其它","菜肴" }; private int[] groupPic = new int[]{R.drawable.one, R.drawable.two, R.drawable.three,R.drawable.four,R.drawable.five,R.drawable.six,R.drawable.seven,R.drawable.eight,R.drawable.nine,R.drawable.ten,R.drawable.eleven}; // 二级名称 private String[][] childName = new String[11][100]; //二级热量 private String[][] childReliang = new String[11][100]; //把二级图片去掉了 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); setContentView(R.layout.tab01_5); imageButton = findViewById(R.id.imageButton21); imageButton.setImageResource(R.drawable.back); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { foods.this.finish(); } }); SearchView searchView = findViewById(R.id.sv); //设置该SearchView默认是否自动缩小为图标 searchView.setIconifiedByDefault(false); //设置该SearchView显示搜索按钮 searchView.setSubmitButtonEnabled(true); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { //单机搜索按钮时激发该方法 @Override public boolean onQueryTextSubmit(String query) { if (query.equals("")) { Toast.makeText(foods.this, "您输入的内容为空", Toast.LENGTH_SHORT).show(); } else { //Toast//实际应用中应该在该方法内执行实际查询,此处仅使用Toast显示用户输入的查询内容 Toast.makeText(foods.this, "你的选择是:" + query, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(foods.this, SActivity.class); intent.putExtra("key1", query); startActivity(intent); } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); expandablelistview = findViewById(R.id.elv); class postTask extends AsyncTask { @Override protected Object doInBackground(Object[] params) { String path=params[0].toString(); try { //获取网络上get方式提交的整个路径 URL url=new URL(path); //打开网络连接 HttpURLConnection conn= (HttpURLConnection) url.openConnection(); //设置提交方式 conn.setRequestMethod("POST"); //设置网络超时时间 conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//键和值是固定的 //设置允许对外输出数据 conn.setDoOutput(true); //把界面上的所有数据写出去 if(conn.getResponseCode()==200){ //用io流与web后台进行数据交互 InputStream is=conn.getInputStream(); //字节流转字符流 BufferedReader br=new BufferedReader(new InputStreamReader(is)); //读出每一行的数据 String str=br.readLine(); //返回读出的每一行的数据 return str; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); //获取Android studio与web后台数据交互获得的值 String s= (String) o; List<Shiwu> shopInfos = JSON.parseArray(s, Shiwu.class); int i=0,j=0,k=0,l=0,m=0,n=0,p=0,q=0,r=0,t=0,u=0; for (Shiwu shiwu : shopInfos) { System.out.println(shiwu.getClasses()); System.out.println(shiwu.getName()); System.out.println(shiwu.getCalory()); if(shiwu.getClasses().equals("谷薯芋、杂豆、主食 " + " ")) { childName[0][i]=shiwu.getName(); childReliang[0][i]=shiwu.getCalory(); i++; }else if(shiwu.getClasses().equals("蛋类、肉类及制品 " + " ")){ childName[1][j]=shiwu.getName(); childReliang[1][j]=shiwu.getCalory(); j++; }else if(shiwu.getClasses().equals("奶类及制品 " + " ")){ childName[2][k]=shiwu.getName(); childReliang[2][k]=shiwu.getCalory(); k++; }else if(shiwu.getClasses().equals("蔬果和菌藻 " + " ")){ childName[3][l]=shiwu.getName(); childReliang[3][l]=shiwu.getCalory(); l++; }else if(shiwu.getClasses().equals("坚果、大豆及制品 " + " ")){ childName[4][m]=shiwu.getName(); childReliang[4][m]=shiwu.getCalory(); m++; }else if(shiwu.getClasses().equals("饮料 " + " ")){ childName[5][n]=shiwu.getName(); childReliang[5][n]=shiwu.getCalory(); n++; }else if(shiwu.getClasses().equals("食用油、油脂及制品 " + " ")){ childName[6][p]=shiwu.getName(); childReliang[6][p]=shiwu.getCalory(); p++; }else if(shiwu.getClasses().equals("调味品 " + " ")){ childName[7][q]=shiwu.getName(); childReliang[7][q]=shiwu.getCalory(); q++; }else if(shiwu.getClasses().equals("零食、点心、冷饮 " + " ")){ childName[8][r]=shiwu.getName(); childReliang[8][r]=shiwu.getCalory(); r++; }else if(shiwu.getClasses().equals("其它 " + " ")){ childName[9][t]=shiwu.getName(); childReliang[9][t]=shiwu.getCalory(); t++; }else if(shiwu.getClasses().equals("菜肴 " + " ")){ childName[10][u]=shiwu.getName(); childReliang[10][u]=shiwu.getCalory(); u++; } } // Toast.makeText(LoginActivity.this, sourceStrArray[0]+sourceStrArray[1], Toast.LENGTH_SHORT).show(); dosome(); } } String path="http://10.0.2.2:8080/testhttp/Show.Servlet";//这里是本地web的地址,先运行httptest的Servlet再启动,才不会闪退。而http://120.79.40.20/testhttp/ //调用postTask,把获取到的数据与路径放入方法中,这里没有放数据。 new postTask().execute(path); } public void dosome(){ //传递参数 myExpandAdapter = new MyExpandAdapter(this, groupName, childName, childReliang, groupPic); expandablelistview.setAdapter(myExpandAdapter); //点击Toast expandablelistview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Toast.makeText(getApplicationContext(), groupName[groupPosition] + ":" + childName[groupPosition][childPosition] + ":" + childReliang[groupPosition][childPosition], Toast.LENGTH_SHORT).show(); return false; } }); } }
相应的适配器:
MyExpandAdapter
package com.example.myapplication5; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.TextView; public class MyExpandAdapter extends BaseExpandableListAdapter { private String[] groupName; private String[][] childName; private String[][] childReliang; private int[] groupPic; private int[][] childPic; LayoutInflater inflater; public MyExpandAdapter(Context context, String[] groupName, String[][] childName,String[][] childReliang, int[] groupPic) { this.inflater = LayoutInflater.from(context); this.groupName = groupName; this.childName = childName; this.childReliang = childReliang; this.groupPic = groupPic; } @Override public int getGroupCount() { return groupName.length; } @Override public int getChildrenCount(int groupPosition) { return childName[groupPosition].length; } @Override public Object getGroup(int groupPosition) { return groupName[groupPosition]; } @Override public Object getChild(int groupPosition, int childPosition) { return childName[groupPosition][childPosition]; } public Object getChildReliang(int groupPosition, int childPosition) { return childReliang[groupPosition][childPosition]; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return true; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.group_item, null); TextView textView = convertView.findViewById(R.id.textView_g); textView.setText(getGroup(groupPosition).toString()); ImageView imageView = convertView.findViewById(R.id.imageView_g); imageView.setImageResource(groupPic[groupPosition]); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.child_item, null); TextView nickTextView = convertView.findViewById(R.id.textView_c2); TextView ReliangTextView = convertView.findViewById(R.id.textView_c3); nickTextView.setText(getChild(groupPosition, childPosition).toString()); ReliangTextView.setText(getChildReliang(groupPosition, childPosition).toString()); // ImageView imageView = convertView.findViewById(R.id.imageView2); // imageView.setImageResource(childPic[groupPosition][childPosition]); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/healthbg3"> <!--定义自动完成的ListView--> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="61dp"> <ImageButton android:id="@+id/imageButton21" android:layout_width="52dp" android:layout_height="52dp" android:layout_gravity="center_horizontal" android:background="@android:color/background_light" android:clickable="false" android:contentDescription="@string/setting" android:scaleType="fitCenter" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.069" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.617" app:srcCompat="@drawable/back" /> <TextView android:id="@+id/textView01_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="益食物" android:textColor="@android:color/background_dark" android:textSize="36sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="1.0" /> </androidx.constraintlayout.widget.ConstraintLayout> <ExpandableListView android:id="@+id/elv" android:layout_width="match_parent" android:layout_height="354dp" android:layout_alignParentTop="true" android:layout_centerVertical="true" android:layout_marginTop="181dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> <SearchView android:id="@+id/sv" android:layout_width="358dp" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerHorizontal="true" android:layout_marginTop="83dp" android:layout_marginEnd="27dp" android:layout_marginRight="27dp" /> </RelativeLayout>
下面是后台的实现:
bean层:
public class Shiwu { private String classes; private String name; private String calory; public String getClasses() { return classes; } public void setClasses(String classes) { this.classes = classes; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCalory() { return calory; } public void setCalory(String calory) { this.calory = calory; } }
dao层:
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.test.bean.Shiwu; import com.test.util.DBUtil; public class ShowDao { public List<Shiwu> select(){ Connection conn = DBUtil.getConn(); //连接数据库 List<Shiwu> list = new ArrayList<Shiwu>(); try { String sql="select * from reliang"; Statement pstmt = (Statement) conn.createStatement(); ResultSet rs = (ResultSet) pstmt.executeQuery(sql); while(rs.next()) { Shiwu Shiwu=new Shiwu(); Shiwu.setClasses(rs.getString("classes")); Shiwu.setName(rs.getString("name")); Shiwu.setCalory(rs.getString("calory")); list.add(Shiwu); } rs.close(); pstmt.close(); conn.close(); }catch(SQLException e) { e.printStackTrace(); } return list; } public List<Shiwu> select1(String name){ Connection conn = DBUtil.getConn(); //连接数据库 List<Shiwu> list1 = new ArrayList<Shiwu>(); try { String sql="select * from reliang where name like '%"+name+"%' "; Statement pstmt = (Statement) conn.createStatement(); ResultSet rs = (ResultSet) pstmt.executeQuery(sql); while(rs.next()) { Shiwu Shiwu=new Shiwu(); Shiwu.setClasses(rs.getString("classes")); Shiwu.setName(rs.getString("name")); Shiwu.setCalory(rs.getString("calory")); list1.add(Shiwu); } rs.close(); pstmt.close(); conn.close(); System.out.println("ShowDaoselect1"); }catch(SQLException e) { e.printStackTrace(); } return list1; } }
servlet层:
import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.bean.Shiwu; import com.test.dao.ShowDao; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; /** * Servlet implementation class ShowServlet */ @WebServlet("/ShowServlet") public class ShowServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ShowServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); ShowDao sd = new ShowDao(); List<Shiwu> list = sd.select(); String json = JSON.toJSONString(list); System.out.println(json); PrintWriter pw=response.getWriter(); pw.write(json); pw.close(); // request.setAttribute("list", list); // request.getRequestDispatcher("show.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
连接数据库的util层就不贴了,比较简单。
这样子展示功能就能实现了。
期间遇到的困难有:
as端与后端数据的数据传递问题,转换json格式进行传值可以解决这个问题。之前对List操作的学习不是很深入,经过这次尝试算是对List有了很多的了解。
而传递到前端的json数据进行处理花费了我大量的时间,说起来真是折腾呀。
仔细分析数据表,然后对数据该怎样处理是值得深思的,这样可以更快的解决问题。