Android——“i 分享”APP開發Day03

通過前兩天的開發,已經實現了應用的註冊登錄功能,考慮到後面主功能的測試需要,所以今天優先處理一下退出登錄的功能

  1. 創建賬號管理的頁面——activity_account_manage.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"
    android:background="#eeeeee">
    <LinearLayout
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/account_images_head"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:scaleType="fitCenter"
            android:src="@drawable/tab_icon_one"/>

        <LinearLayout
            android:id="@+id/account_login_top"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical"
            android:weightSum="1"
            >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:layout_weight="0.3"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/account_textView8"
                    android:layout_width="70dp"
                    android:layout_height="wrap_content"
                    android:text="暱稱:"
                    android:textSize="18sp"/>

                <TextView
                    android:id="@+id/account_t_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="丫an梅"
                    android:textSize="18sp"
                    android:textStyle="bold"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.3"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/account_textView9"
                    android:layout_width="70dp"
                    android:layout_height="wrap_content"
                    android:text="狀態:"
                    android:textSize="18sp"/>

                <TextView
                    android:id="@+id/account_t_status"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.44"
                    android:text="已登錄"
                    android:textSize="18sp"
                    android:textStyle="bold"/>
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/account_bt_out_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="100dp"
            android:layout_marginRight="100dp"
            android:background="@drawable/selector_loginactivity_button"
            android:text="退出登錄"
            android:textColor="#fff"
            android:gravity="center"
            />
    </LinearLayout>

</LinearLayout>

     2. 創建AccountManagement.java,處理賬號管理頁面的邏輯

  • 獲取到當前登錄用戶的頭像和暱稱信息——數據爲測試數據尚未和數據庫同步
  • 處理退出登錄按鈕的事件,更改用戶的登錄狀態並更新“我的”頁面中的UI
  • 登錄成功之後返回發現頁
package com.example.discover;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

public class AccountManagement extends Activity {
    ImageView my_head_img;   //用戶頭像
    TextView my_name,status;   //用戶暱稱和心情
    Button out_login;   //退出登錄

    String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images/";  //圖片資源
    String userName,headImg;   //存放用戶基本信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_manage);

        my_head_img = (ImageView)findViewById(R.id.account_images_head);   //我的頭像
        my_name = (TextView)findViewById(R.id.account_t_name); //我的暱稱
        status = (TextView)findViewById(R.id.account_t_status); //登錄狀態
        out_login = (Button)findViewById(R.id.account_bt_out_login) ;//退出登錄的按鈕

        setBaseInfo();
        out_login.setOnClickListener(new onClick());
    }
    class onClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            exitSuccess();
            Toast.makeText(AccountManagement.this, "退出成功!", Toast.LENGTH_LONG).show();

            //通過handler設置延時兩秒後執行r任務,跳轉到首頁
            new Handler().postDelayed(new AccountManagement.LoadMainTask(),1000);
        }
    }

    //啓動線程,加載主頁
    private class LoadMainTask implements Runnable{
        @Override
        public void run() {
            Intent intent = new Intent(AccountManagement.this,MainActivity.class);
            startActivity(intent);  //打開主頁
            finish();   //關閉起始頁
        }
    }

    //退出登錄後進行用戶登錄狀態修改
    public void exitSuccess(){
        //退出登錄後更改登錄狀態
        SharedPreferences sp = AccountManagement.this.getSharedPreferences("save", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("isLogin", false);
        editor.putString("name", "");
        editor.putString("sign", "");
        editor.putString("img", "");
        editor.commit();
    }

    //設置賬號管理頁面用戶相關信息
    public void setBaseInfo(){
        //獲取最新的登錄狀態,SharePreferences爲永久存儲,需要手動退出
        SharedPreferences sp = AccountManagement.this.getSharedPreferences("save", Context.MODE_PRIVATE);
        //boolean isLogin = sp.getBoolean("isLogin",false);    //第一版本不做登錄判斷,在跳轉前要求登錄狀態才能夠跳轉到這個頁面
        status.setText("已登錄");

        Bitmap one;     //用於獲取網絡圖片
        userName = sp.getString("name","");
        headImg = sp.getString("headImg","");

        //設置用戶暱稱、頭像
        my_name.setText(userName);

        //通過網絡鏈接獲取圖片
        try {
            one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png");
            my_head_img.setImageBitmap(one);   //設置用戶頭像
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

 

     3. 在數據庫ishare中創建分享的內容表info

  • 字段包括info_id(自增的內容ID)、info_title(內容標題)、info_descibe(內容簡述)、info_detail(內容詳情)、info_type(內容類型,0表示日記,1表示趣事)、info_support(點贊數)、username(作者)

     4.在myeclipse的myServlet.data包下創建QueryDiscover.java文件,用於查詢info表中的數據

  • 爲了將返回的rowSet數據打包爲Json格式,需要在lib中引入json-lib-2.4-jdk15.jar以及相關聯的jar包ezmorph-1.0.4、commons-logging-1.1.1、commons-lang-2.4、commons-collections-3.2、commons-beanutils-1.8.0
  • 在org.utils包下創建JsonUtils.java,代碼如下

package org.utils;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.List;
import java.util.Map;

public class JsonUtils {
    public static JSONArray formatRsToJsonArray(List<Map<String,Object>> data){
        JSONArray jsonArray = new JSONArray();//存放返回的jsonOjbect數組
        for(Map<String,Object> rowItem:data) {
            JSONObject json = new JSONObject();
                for(Map.Entry<String, Object> entry:rowItem.entrySet()) {
                    json.put(entry.getKey(), entry.getValue());
                }
            jsonArray.add(json);
        }
        return jsonArray;
    }
}

  • QueryDiscover.java文件執行查詢Info表的操作,並將查詢的結果封裝爲Json格式返回

package myServlet.data;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
/*import java.sql.ResultSetMetaData;*/
import java.sql.Statement;

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;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;


/**
 * Servlet implementation class QueryDiscover
 */
@WebServlet("/QueryDiscover")
public class QueryDiscover extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    CachedRowSetImpl rowSet = null;    //存儲表中全部記錄的行集對象
    int pageSize; //每頁加載數量
    int pageNum;   //第幾頁
    int totalRecord;  //總記錄數
    int totalPage;   //總頁數
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryDiscover() {
        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 page = request.getParameter("page");    
        String count = request.getParameter("count");
        
        if(page == null||page == "") {
            page = "1";
        }
        
        if(count == null|count == "") {
            count = "10";
        }
        
        try {
            pageNum = Integer.parseInt(page);    //第幾頁
            pageSize = Integer.parseInt(count);    //每頁加載幾條
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        
        String condition = "select * from info";
    
        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);
            
            /*用於測試
             * while(rs.next()) {
                String infoId = rs.getString(1);    //內容ID                        
                String infoTitle = rs.getString(2);   //內容標題                    
                String infoDescribe = rs.getString(3);   //內容簡述
                String infoDetail = rs.getString("info_detail");   //內容詳情
                
                String type = rs.getString(5);    //類型:0表示日記,1表示趣事
                String support = rs.getString(6);   //點贊數

                
                String infoAuthor = rs.getString(7);  //作者    

                out.println(infoId+"--"+infoTitle+"--"+infoDescribe+"--"+infoDetail+"--"+type+"--"+support+"--"+infoAuthor);  
                out.println("__________________________________________");  
            }*/
            
            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數組
            
            //將rowSet的數據提取到Map
            List<Map<String,Object>> data = 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++){    
                        /*Object infoId =  rowSet.getObject(1);
                        Object infoTitle =  rowSet.getObject(2);*/
                        String infoId = rowSet.getString(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);
                        
                        /*Map<String,Object> map = new HashMap<String,Object>();
                        for(int j = 1;j<columnCount;j++) {
                            map.put(metaData.getColumnClassName(j), rowSet.getObject(j));
                        }*/
                        data.add(map);
                        boo = rowSet.next();
                    }
                    jsonArray = JsonUtils.formatRsToJsonArray(data);
                    out.println(jsonArray.toString());  //返回json
                    
                }catch(Exception e) {
                    
                }
                
            }catch(IOException e) {
           
            }   
    }   
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章