Android - "i share" APP development Day03

Through the development of the first two days, the registration and login function of the application has been realized. Considering the testing needs of the main function later, the function of logout is given priority today

  1. Create an account management page - 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="Nickname?"
                    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="Ya an Plum blossom"
                    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="Status:"
                    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="Already logged in"
                    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="Logout"
            android:textColor="#fff"
            android:gravity="center"
            />
    </LinearLayout>

</LinearLayout>

2. Create AccountManagement.java to process the logic of account management page

  • Get the picture and nickname information of the current login user -- the data is the test data has not been synchronized with the database
  • Handles the event to exit the login button, changes the user's login status and updates the UI in the my page
  • Return to discovery page after successful login
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;   //User head
    TextView my_name,status;   //User nickname and mood
    Button out_login;   //Logout

    String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images / "; / / image resources
    String userName,headImg;   //Store basic user information

    @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 head
        my_name = (TextView)findViewById(R.id.account_t_name); //My nickname
        status = (TextView)findViewById(R.id.account_t_status); //Logon status
        out_login = (Button)findViewById(R.id.account_bt_out_login) ;//Exit login button

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

            //Set a delay of two seconds through the handler, then execute the r task and jump to the home page
            new Handler().postDelayed(new AccountManagement.LoadMainTask(),1000);
        }
    }

    //Start thread, load home page
    private class LoadMainTask implements Runnable{
        @Override
        public void run() {
            Intent intent = new Intent(AccountManagement.this,MainActivity.class);
            startActivity(intent);  //Open home page
            finish();   //Close start page
        }
    }

    //Modify the user's login status after logging out
    public void exitSuccess(){
        //Change login status after logging out
        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();
    }

    //Set account management page user related information
    public void setBaseInfo(){
        //Get the latest login status. SharePreferences is permanent storage. You need to exit manually
        SharedPreferences sp = AccountManagement.this.getSharedPreferences("save", Context.MODE_PRIVATE);
        //boolean isLogin = sp.getBoolean("isLogin",false); / / the first version does not make a login judgment, and requires the login status to jump to this page before jumping
        status.setText("Already logged in");

        Bitmap one;     //For getting network pictures
        userName = sp.getString("name","");
        headImg = sp.getString("headImg","");

        //Set user nickname and Avatar
        my_name.setText(userName);

        //Get pictures through Internet links
        try {
            one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png");
            my_head_img.setImageBitmap(one);   //Set user image
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

 

3. Create shared content table info in database ishare

  • The fields include info? ID, info? Title, info? Description, info? Detail, info? Type (0 for journal, 1 for fun), info? Support, username (author)

4. Create QueryDiscover.java file under myServlet.data package of myeclipse to query data in info table

  • In order to package the returned rowSet data into Json format, we need to introduce json-lib-2.4-jdk15.jar and related jar packages ezmorph-1.0.4, commons-logging-1.1.1, commons-lang-2.4, commons-collections-3.2, commons-beanautils-1.8.0 into lib
  • Create JsonUtils.java under the org.utils package. The code is as follows

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();//Store the returned jsonOjbect array
        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;
    }
}

  • The querydiscovery.java file performs the operation of querying the Info table and encapsulates the results of the query as Json format

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;    //Rowset object that stores all records in the table
    int pageSize; //Load quantity per page
    int pageNum;   //How many pages
    int totalRecord;  //Total number of records
    int totalPage;   //PageCount
    
    /**
     * @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);    //How many pages
            pageSize = Integer.parseInt(count);    //Load several pieces per page
        } 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);
            
            /*For testing
             * while(rs.next()) {
                String infoId = rs.getString(1);    //Content ID
                String infoTitle = rs.getString(2);   //Content title
                String infoDescribe = rs.getString(3);   //Content brief
                String infoDetail = rs.getString("info_detail");   //Content details
                
                String type = rs.getString(5);    //Type: 0 for diary, 1 for fun
                String support = rs.getString(6);   //Praise points

                
                String infoAuthor = rs.getString(7);  //Author

                out.println(infoId+"--"+infoTitle+"--"+infoDescribe+"--"+infoDetail+"--"+type+"--"+support+"--"+infoAuthor);  
                out.println("__________________________________________");  
            }*/
            
            rowSet = new CachedRowSetImpl();  //Create rowset object
            rowSet.populate(rs);
            
            
            //Return results by query pages
            returnByPage(request,response,rowSet);
        } catch (Exception e) {    
            out.println(condition+"Exception:"+e.toString());
            e.printStackTrace();
        }finally {
            //5. Release resource 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();//Store the returned jsonOjbect array
            
            //Extract data from rowSet to 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(); / / returns the total number of columns
                    
                    rowSet.last();    //Move to next line
                    totalRecord = rowSet.getRow();
                    
                    /*out.println("All records "+ totalRecord); / / all records*/                    
                    if(totalRecord%pageSize==0){
                        totalPage = totalRecord/pageSize;  //PageCount
                    }else{
                        totalPage = totalRecord/pageSize+1; 
                    }
                    
                    int index = (pageNum-1)*pageSize+1;
                    rowSet.absolute(index);   //Query location moves to the starting record location of the query page
                    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);    //Content ID
                        String infoTitle = rowSet.getString(2);   //Content title
                        String infoDescribe = rowSet.getString(3);   //Content brief
                        String infoDetail = rowSet.getString("info_detail");   //Content details
                        
                        String type = rowSet.getString(5);    //Type: 0 for diary, 1 for fun
                        String support = rowSet.getString(6);   //Praise points
    
                        
                        String infoAuthor = rowSet.getString(7);  //Author
                        
                        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());  //Return to json
                    
                }catch(Exception e) {
                    
                }
                
            }catch(IOException e) {
           
            }   
    }   
}

 

Tags: Android Java JSON SQL

Posted on Wed, 06 Nov 2019 13:36:35 -0800 by carolin