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) {
           
            }   
    }   
}

 

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