在上一篇已經完成了發現頁的分頁加載功能,接下來就開始實現查找頁的功能,在這個模塊會分成找人和找文兩個查找方向,初步設計是通過查找相關用戶暱稱的關鍵字以及文章標題和簡述的關鍵字進行查找;另外在進入該查找頁時希望會展示前十的熱門文章,其中熱門的判定標準是點贊數
- 在myEclipse的myServlet.data包下創建查詢熱門文章的servlet——QueryHotInfo.java,該文件主要就是查詢點贊數前十的文章內容並返回所有相關信息,和上一篇發現頁的查詢類似,具體代碼如下:
- 注:爲方便後期擴展,雖然不做分頁但仍然將返回的總記錄數封裝到返回的Json
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.ServletConfig;
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 org.utils.JdbcUtils;
import org.utils.JsonUtils;import com.sun.rowset.CachedRowSetImpl;
import net.sf.json.JSONArray;
/**
* Servlet implementation class QueryHotInfo
*/
@WebServlet("/QueryHotInfo")
public class QueryHotInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
CachedRowSetImpl rowSet = null; //存儲表中全部記錄的行集對象
int pageSize=10; //每頁加載數量
int pageNum=1; //第幾頁
int totalRecord; //總記錄數
int totalPage; //總頁數
/**
* @see HttpServlet#HttpServlet()
*/
public QueryHotInfo() {
super();
// TODO Auto-generated constructor stub
}/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
//將傳過來的字符串轉爲Boolean
/*public Boolean stringToBoolean(String str)
{
switch(str.toLowerCase())
{
case "true":case "1": return true;
case "false":case "0": return false;
default: return false;
}
}*/
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String condition = "select * from info order by info_support desc"; //按點贊數降序,查詢熱門
Connection connection = null;
Statement sql = null;
ResultSet rs = null;try {
connection = JdbcUtils.getConnection();
sql = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = sql.executeQuery(condition);
rowSet = new CachedRowSetImpl(); //創建行集對象
rowSet.populate(rs);
//按查詢頁數返回結果
returnByPage(request,response,rowSet);
} catch (Exception e) {
out.println(condition+"異常:"+e.toString());
e.printStackTrace();
}finally {
//5.釋放資源 connection prepareStatement
JdbcUtils.statementClose(connection, sql, rs);
}
}/**
* @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);
}
public void returnByPage(HttpServletRequest request, HttpServletResponse response,CachedRowSetImpl rowSet)throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect數組
JSONArray TotaljsonArray = new JSONArray();//存放返回的jsonOjbect數組
//將rowSet的數據提取到Map
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
//將rowSet的數據提取到Map
List<Map<String,Object>> Totaldata = new ArrayList<Map<String,Object>>();
try {
PrintWriter out = response.getWriter();
try {
//ResultSetMetaData metaData = rowSet.getMetaData();
//int columnCount = metaData.getColumnCount(); //返回總列數
rowSet.last(); //移到隨後一行
totalRecord = rowSet.getRow();
/*out.println("全部記錄數"+totalRecord); //全部的記錄數*/
if(totalRecord%pageSize==0){
totalPage = totalRecord/pageSize; //總頁數
}else{
totalPage = totalRecord/pageSize+1;
}
int index = (pageNum-1)*pageSize+1;
rowSet.absolute(index); //查詢位置移動到查詢頁的起始記錄位置
boolean boo = true;
for(int i=1; i<=pageSize&&boo;i++){
int infoId = rowSet.getInt(1); //內容ID
String infoTitle = rowSet.getString(2); //內容標題
String infoDescribe = rowSet.getString(3); //內容簡述
String infoDetail = rowSet.getString("info_detail"); //內容詳情
String type = rowSet.getString(5); //類型:0表示日記,1表示趣事
String support = rowSet.getString(6); //點贊數
String infoAuthor = rowSet.getString(7); //作者
Map<String,Object> map = new HashMap<String,Object>();
map.put("infoId", infoId);
map.put("infoTitle", infoTitle);
map.put("infoDescribe", infoDescribe);
map.put("infoDetail", infoDetail);
map.put("infoType", type);
map.put("infoSupport", support);
map.put("infoAuthor", infoAuthor);
data.add(map);
boo = rowSet.next();
}
jsonArray = JsonUtils.formatRsToJsonArray(data);
Map<String,Object> map = new HashMap<String,Object>();
map.put("totalRecord", totalRecord);
map.put("RecordDetail", jsonArray);
Totaldata.add(map);
TotaljsonArray = JsonUtils.formatRsToJsonArray(Totaldata);
out.println(TotaljsonArray.toString()); //返回json
}catch(Exception e) {
}
}catch(IOException e) {
}
}
}
2.接下來在同一個包下面創建按關鍵字查找文章的servlet——QueryInfoByKey.java
- 其實這部分的代碼與上面都是大同小異,不過是這次返回的相關內容是一次性返回所有的記錄,具體代碼如下:
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.ServletConfig;
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 org.utils.JdbcUtils;
import org.utils.JsonUtils;import com.sun.rowset.CachedRowSetImpl;
import net.sf.json.JSONArray;
/**
* Servlet implementation class QueryInfoByKey
*/
@WebServlet("/QueryInfoByKey")
public class QueryInfoByKey extends HttpServlet {
private static final long serialVersionUID = 1L;
CachedRowSetImpl rowSet = null; //存儲表中全部記錄的行集對象
int pageSize=10; //每頁加載數量
int pageNum=1; //第幾頁
int totalRecord; //總記錄數
int totalPage; //總頁數
/**
* @see HttpServlet#HttpServlet()
*/
public QueryInfoByKey() {
super();
// TODO Auto-generated constructor stub
}/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String keyWord = request.getParameter("key");
if(keyWord == null||keyWord.length()==0) {
return;
}
String condition ="select * from info where info_title like '%"+keyWord+"%' or info_describe like '%"+keyWord+"%'" ; //按關鍵詞查找
Connection connection = null;
Statement sql = null;
ResultSet rs = null;try {
connection = JdbcUtils.getConnection();
sql = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = sql.executeQuery(condition);
rowSet = new CachedRowSetImpl(); //創建行集對象
rowSet.populate(rs);
//按查詢頁數返回結果
returnByPage(request,response,rowSet);
} catch (Exception e) {
out.println(condition+"異常:"+e.toString());
e.printStackTrace();
}finally {
//5.釋放資源 connection prepareStatement
JdbcUtils.statementClose(connection, sql, rs);
}
}/**
* @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);
}
public void returnByPage(HttpServletRequest request, HttpServletResponse response,CachedRowSetImpl rowSet)throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect數組
JSONArray TotaljsonArray = new JSONArray();//存放返回的jsonOjbect數組
//將rowSet的數據提取到Map
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
//將rowSet的數據提取到Map
List<Map<String,Object>> Totaldata = new ArrayList<Map<String,Object>>();
try {
PrintWriter out = response.getWriter();
try {
//ResultSetMetaData metaData = rowSet.getMetaData();
//int columnCount = metaData.getColumnCount(); //返回總列數
rowSet.last(); //移到隨後一行
totalRecord = rowSet.getRow();
/*out.println("全部記錄數"+totalRecord); //全部的記錄數*/
if(totalRecord%pageSize==0){
totalPage = totalRecord/pageSize; //總頁數
}else{
totalPage = totalRecord/pageSize+1;
}
int index = (pageNum-1)*pageSize+1;
rowSet.absolute(index); //查詢位置移動到查詢頁的起始記錄位置
boolean boo = true;
for(int i=1; i<=totalRecord&&boo;i++){
int infoId = rowSet.getInt(1); //內容ID
String infoTitle = rowSet.getString(2); //內容標題
String infoDescribe = rowSet.getString(3); //內容簡述
String infoDetail = rowSet.getString("info_detail"); //內容詳情
String type = rowSet.getString(5); //類型:0表示日記,1表示趣事
String support = rowSet.getString(6); //點贊數
String infoAuthor = rowSet.getString(7); //作者
Map<String,Object> map = new HashMap<String,Object>();
map.put("infoId", infoId);
map.put("infoTitle", infoTitle);
map.put("infoDescribe", infoDescribe);
map.put("infoDetail", infoDetail);
map.put("infoType", type);
map.put("infoSupport", support);
map.put("infoAuthor", infoAuthor);
data.add(map);
boo = rowSet.next();
}
jsonArray = JsonUtils.formatRsToJsonArray(data);
Map<String,Object> map = new HashMap<String,Object>();
map.put("totalRecord", totalRecord);
map.put("RecordDetail", jsonArray);
Totaldata.add(map);
TotaljsonArray = JsonUtils.formatRsToJsonArray(Totaldata);
out.println(TotaljsonArray.toString()); //返回json
}catch(Exception e) {
}
}catch(IOException e) {
}
}}
3.然後就是處理按關鍵字查找用戶,同樣的在同一包下面創建一個servlet——QueryPeopleByKey.java
- 這邊的處理也不用多講了,就和按關鍵字查找文章的處理一樣,只是sql和Json的封裝有點差別,直接上代碼:
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.ServletConfig;
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 org.utils.JdbcUtils;
import org.utils.JsonUtils;import com.sun.rowset.CachedRowSetImpl;
import net.sf.json.JSONArray;
/**
* Servlet implementation class QueryPeopleInfo
*/
@WebServlet("/QueryPeopleInfoByKey")
public class QueryPeopleInfoByKey extends HttpServlet {
private static final long serialVersionUID = 1L;
CachedRowSetImpl rowSet = null; //存儲表中全部記錄的行集對象
int pageSize=10; //每頁加載數量
int pageNum=1; //第幾頁
int totalRecord; //總記錄數
int totalPage; //總頁數
/**
* @see HttpServlet#HttpServlet()
*/
public QueryPeopleInfoByKey() {
super();
// TODO Auto-generated constructor stub
}/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String keyWord = request.getParameter("nameKey");
if(keyWord == null||keyWord.length()==0) {
return;
}
String condition ="select * from user where username like '%"+keyWord+"%'" ; //按關鍵詞查找
Connection connection = null;
Statement sql = null;
ResultSet rs = null;try {
connection = JdbcUtils.getConnection();
sql = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = sql.executeQuery(condition);
rowSet = new CachedRowSetImpl(); //創建行集對象
rowSet.populate(rs);
//按查詢頁數返回結果
returnByPage(request,response,rowSet);
} catch (Exception e) {
out.println(condition+"異常:"+e.toString());
e.printStackTrace();
}finally {
//5.釋放資源 connection prepareStatement
JdbcUtils.statementClose(connection, sql, rs);
}
}/**
* @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);
}
public void returnByPage(HttpServletRequest request, HttpServletResponse response,CachedRowSetImpl rowSet)throws ServletException, IOException{
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect數組
JSONArray TotaljsonArray = new JSONArray();//存放返回的jsonOjbect數組
//將rowSet的數據提取到Map
List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
//將rowSet的數據提取到Map
List<Map<String,Object>> Totaldata = new ArrayList<Map<String,Object>>();
try {
PrintWriter out = response.getWriter();
try {
rowSet.last(); //移到隨後一行
totalRecord = rowSet.getRow();
if(totalRecord%pageSize==0){
totalPage = totalRecord/pageSize; //總頁數
}else{
totalPage = totalRecord/pageSize+1;
}
int index = (pageNum-1)*pageSize+1;
rowSet.absolute(index); //查詢位置移動到查詢頁的起始記錄位置
boolean boo = true;
for(int i=1; i<=totalRecord&&boo;i++){
String userName = rowSet.getString(1); //用戶暱稱
//String passWord = rowSet.getString(2); //用戶密碼
String signature = rowSet.getString(3); //用戶簽名
String userLogImage = rowSet.getString(4); //用戶頭像
Map<String,Object> map = new HashMap<String,Object>();
map.put("userName", userName);
/*map.put("passWord", passWord);*/
map.put("signature", signature);
map.put("userLogImage", userLogImage);
data.add(map);
boo = rowSet.next();
}
jsonArray = JsonUtils.formatRsToJsonArray(data);
Map<String,Object> map = new HashMap<String,Object>();
map.put("totalRecord", totalRecord);
map.put("RecordDetail", jsonArray);
Totaldata.add(map);
TotaljsonArray = JsonUtils.formatRsToJsonArray(Totaldata);
out.println(TotaljsonArray.toString()); //返回json
}catch(Exception e) {
}
}catch(IOException e) {
}
}}
4.有了上述三個接口,我們就可以快樂地寫Android端查找頁的代碼了
- 首先當然是要有查找頁的頁面佈局,準備是在頂部放一個搜索框和兩個搜索按鈕以及一個清除文本框輸入內容的清除按鈕,而熱門內容列表和查詢結果列表就套用之前發現頁中的做法,使用listView
- 去圖標網站下載搜索和刪除的小圖標,命名就按下面代碼文件中所示,將圖標放到drawable中
——在layout下 修改原來的find_tab_content.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <LinearLayout android:gravity="center_vertical" android:orientation="horizontal" android:id="@+id/title_bar" android:background="@drawable/title_bg_night" android:layout_width="fill_parent" android:layout_height="35.0dip"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/app_icon" /> <LinearLayout android:gravity="center_vertical" android:layout_width="0.0dip" android:layout_height="wrap_content" android:layout_weight="1.0"> <TextView android:textSize="16.0sp" android:textColor="@color/titleTextColor" android:singleLine="true" android:id="@+id/myTitle" android:layout_width="fill_parent" android:ellipsize="end" android:layout_height="wrap_content" android:layout_marginLeft="2.0dip" android:text="@string/app_name" /> </LinearLayout> <ImageButton android:id="@+id/back_button" android:layout_gravity="center" android:background="@color/transparent" android:layout_width="60.0dip" android:layout_height="29.0dip" android:layout_marginRight="5.0dip" android:src="@drawable/exit" /> </LinearLayout> <!--搜索框--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/find_search_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#CCFFFF" android:paddingBottom="30dp" android:orientation="vertical" android:gravity="center" android:layout_below="@+id/title_bar"> <LinearLayout android:layout_width="fill_parent" android:layout_height="50dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="5dp" android:background="@drawable/small_bc" android:orientation="horizontal"> <Button android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="right|center_vertical" android:layout_margin="30dp" android:background="@drawable/search" /> <!-- 輸入的搜索信息 --> <EditText android:id="@+id/et_seek_search" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="4" android:background="@null" android:gravity="center_vertical" android:hint="輸入想要搜索的關鍵字" android:imeOptions="actionSearch" android:singleLine="true" android:textColor="#0e0e0e" android:textColorHint="#b0c6ce" android:textSize="17sp" /> //清除查詢 <Button android:id="@+id/seek_bt_clear" android:layout_width="25dp" android:layout_height="25dp" android:layout_gravity="right|center_vertical" android:layout_margin="30dp" android:background="@drawable/delete" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/find_search_by_name" android:layout_width="70dp" android:layout_height="30dp" android:background="@drawable/button_radius" android:text="找人" android:gravity="center" /> <Button android:id="@+id/find_search_by_keyWord" android:layout_width="70dp" android:layout_height="30dp" android:layout_marginLeft="10dp" android:background="@drawable/button_radius" android:text="找文" android:gravity="center" /> </LinearLayout> </LinearLayout> <!-- <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/tab_icon_three" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:padding="10dp" android:text="這是查找界面" android:textSize="20sp" /> </LinearLayout>--> <LinearLayout android:layout_below="@+id/title_bar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" android:paddingTop="140dp"> <TextView android:id="@+id/seek_list_hint_info" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="6.0dip" android:gravity="center_vertical" android:paddingLeft="10.0dip" android:text="大家都在看:" android:textColor="#DF3154" android:textSize="16.0sp" /> <ListView android:id="@+id/find_listView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:dividerHeight="0dp" /> </LinearLayout> </RelativeLayout>
5.除了上面的佈局設計,我們還需要一個放查詢結果的列表項佈局文件
- 在layout下創建文件activity_seek_list_item.xml,具體代碼如下:
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableLayout android:id="@+id/seek_list_tableLayout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="1.0dip" android:shrinkColumns="0" android:stretchColumns="0" android:background="#ebebeb"> <TableRow android:id="@+id/seek_list_tableRow" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/small_bc" android:paddingBottom="12.0dip" android:paddingTop="12.0dip" > <TextView android:id="@+id/seek_list_textView" android:layout_width="wrap_content" android:layout_height="fill_parent" android:drawableLeft="@drawable/hot_key" android:drawablePadding="16.0dip" android:gravity="center_vertical" android:includeFontPadding="false" android:text="熱門標題" android:textColor="#ff333333" android:textSize="16.0sp" android:paddingLeft="20dp"/> <TextView android:id="@+id/seek_list_textView2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center_vertical" android:includeFontPadding="false" android:text="12345" android:textColor="#424202" android:textSize="16.0sp" android:paddingRight="20dp"/> <!--android:adjustViewBounds="true"圖片自適應--> <ImageView android:adjustViewBounds="true" android:id="@+id/seek_list_imgView" android:layout_width="wrap_content" android:layout_height="40dp" android:layout_gravity="right" android:gravity="center_vertical" android:src="@drawable/next_right" android:paddingRight="30dp"/> </TableRow> </TableLayout> </LinearLayout> </LinearLayout> </LinearLayout>
6.有了頁面佈局就可以開始做數據處理了,在原來創建好的FindTabFragment.java文件中進行修改
- 首先是關聯頁面組件
- 因爲打開頁面就可以顯示熱門內容的Top10,所以要先從後臺獲取數據
/** * 查詢數據庫中的數據 */ private JSONArray loadDataFromDataBase(String QueryInfoUrl){ //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show(); StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; try { URL url = new URL(QueryInfoUrl); connGET = (HttpURLConnection) url.openConnection(); connGET.setConnectTimeout(5000); connGET.setRequestMethod("GET"); if (connGET.getResponseCode() == 200) { buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream())); for (String s = buffer.readLine(); s != null; s = buffer.readLine()) { stringBuilder.append(s); } //返回測試信息 JSONArray jsonArray = new JSONArray(stringBuilder.toString()); /* testTxt.setText(baseUrl+"QueryDiscover?page="+page+"&count="+count);*/ //獲取到的數據,對Json進行解析 page = page+1; //一次成功請求後更新請求頁面 buffer.close(); return jsonArray; }else{ Toast.makeText(getActivity(),"非200", Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getActivity(), "get 提交 err.." + e.toString(), Toast.LENGTH_LONG).show(); } return null; }
- 然後和發現頁的處理一樣將數據存到bean中 以及初始化listView適配器
//初始化將詳情設置到FindInfo bean中 public List<FindInfo> initSetDataToBean(String detail){ List<FindInfo> findInfo = new ArrayList<FindInfo>(); try { JSONArray detailJsonArray = new JSONArray(detail); for (int i = 0; i < detailJsonArray.length(); i++) { FindInfo items = new FindInfo(); JSONObject temp = (JSONObject) detailJsonArray.get(i); Integer infoId = temp.getInt("infoId"); //內容ID String infoTitle = temp.getString("infoTitle"); //內容標題 String infoDescribe = temp.getString("infoDescribe"); //內容簡述 String infoDetail = temp.getString("infoDetail"); //內容詳情 Integer type = temp.getInt("infoType"); //類型:0表示日記,1表示趣事 Integer support = temp.getInt("infoSupport"); //點贊數 String infoAuthor = temp.getString("infoAuthor"); //作者 items.setInfoId(infoId); items.setInfoTitle(infoTitle); items.setInfoDescribe(infoDescribe); items.setInfoDetail(infoDetail); items.setType(type); items.setSupport(support); items.setInfoAuthor(infoAuthor); findInfo.add(items); } return findInfo; }catch (JSONException e){ Toast.makeText(getActivity(), "initSetDataToBean異常 err.." + e.toString(), Toast.LENGTH_LONG).show(); return null; } }
/** * 初始化ListView的適配器,即打開頁面展示的數據 */ private void initializeAdapter(){ // 設置線程策略 setVersion(); String QueryHotInfoUrl = baseUrl+"QueryHotInfo"; JSONArray jsonArray = loadDataFromDataBase(QueryHotInfoUrl); try { JSONObject totalObject = (JSONObject)jsonArray.get(0); dataSize = totalObject.getInt("totalRecord"); //總記錄數 String detail= totalObject.getString("RecordDetail"); //詳情 if(initSetDataToBean(detail)!=null) { adapter = new PaginationAdapter(initSetDataToBean(detail)); //將詳情設置到bean中 } }catch (JSONException e){ Toast.makeText(getActivity(), "initializeAdapter異常 err.." + e.toString(), Toast.LENGTH_LONG).show(); } }
——今天比較事多,就到這先吧,這部分文件的所有代碼在下一篇會提供