——my_tab_content.xml页面代码初步如下
//根据状态显示或隐藏“我的”页面中头部信息 public void changeStatus(){ //获取最新的登录状态,SharePreferences为永久存储,需要手动退出 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ Bitmap one; userName = sp.getString("name",""); signature = sp.getString("sign",""); headImg = sp.getString("headImg",""); //设置用户昵称、头像、心情 my_name.setText(userName); my_sign.setText(userName); //通过网络链接获取图片 try { one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png"); my_head_img.setImageBitmap(one); }catch(IOException e){ e.printStackTrace(); } //已经登录时设置用户相关信息为显示状态 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); un_login_top.setVisibility(View.GONE); }else{ //尚未登录,设置登录、注册按钮为显示状态 un_login_top.setVisibility(View.VISIBLE); login_top.setVisibility(View.GONE); } }
2.在myeclipse中创建项目iShareService为android应用搭建web后台服务
package org.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class JdbcUtils {
private static String url ="jdbc:mysql://127.0.0.1/ishare?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
private static String username="root";
private static String password="";
private static String driverName="com.mysql.jdbc.Driver";
// static静态代码块里面代码,会在类加载到内存的时候立刻执行
static {
//1.注册驱动
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
//2.获取连接
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection,PreparedStatement prepareStatement,ResultSet resultSet) {
//5.释放资源 connection prepareStatement resultSet
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(prepareStatement!=null) {
try {
prepareStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void statementClose(Connection connection,Statement statement,ResultSet resultSet) {
//5.释放资源 connection prepareStatement resultSet
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.utils.JdbcUtils;
public class Register extends HttpServlet{/**
* 注册
*/
private static final long serialVersionUID = 1L;
//处理中文字符串
public String handleString(String s) {
try {
byte bb[]=s.getBytes("ISO8859-1");
s=new String(bb,"UTF-8");
}catch(Exception e){}
return s;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String username = handleString(request.getParameter("username"));
String password = handleString(request.getParameter("password"));
String signature = handleString(request.getParameter("signature"));
String userlogimage = "userImg.png"; /* 默认头像*/
out.print(username+"--"+password+"--"+signature);
Connection connection = null;
PreparedStatement prepareStatement = null;
try {
connection = JdbcUtils.getConnection();
//3.获取statement
//String sql ="insert into user(name,phone,password,gender,province,city,create_time,update_time) value(?,?,?,?,?,?,?,?) ";
String sql ="INSERT INTO user VALUES(?,?,?,?)";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, username);
prepareStatement.setString(2, password);
prepareStatement.setString(3, signature);
prepareStatement.setString(4, userlogimage);
//4.执行sql
prepareStatement.execute();
out.print("register succeeded!");
} catch (Exception e) {
e.printStackTrace();
out.print("该用户名已被使用,请更换名字!"+e);
}finally {
//5.释放资源 connection prepareStatement
JdbcUtils.close(connection, prepareStatement, null);
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package myServlet.data;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;/**
* Servlet implementation class Login
*/
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
//处理中文字符串
public String handleString(String s) {
try {
byte bb[]=s.getBytes("ISO8859-1");
s=new String(bb,"UTF-8");
}catch(Exception e){}
return s;
}/**
* @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 username = request.getParameter("username").trim();
String password = request.getParameter("password").trim();
String signature = "在这里写下你的心情吧!";
username = handleString(username);
password = handleString(password);
if(username == null) {
username = "";
}
if(password == null) {
password = "";
}
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;
String backnews="";
boolean boo = false;
boo = username.length()>0&&password.length()>0;
try {
connection = JdbcUtils.getConnection();
//3.获取statement
//String sql ="insert into user(logname,password,phone,address,realname) value(?,?,?,?,?) ";
String sql ="select * from user where username=? and password=?";
prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, username);
prepareStatement.setString(2, password);
if(boo) {
//4.执行sql
boolean m =false;
rs = prepareStatement.executeQuery();
while(rs.next()) {
signature = rs.getString(4);
m = true;
}
if(m==true) {
//登录成功
success(request,response,username,signature,backnews);
/*RequestDispatcher dispatcher = request.getRequestDispatcher("/pages/login.jsp");
dispatcher.forward(request, response);*/
}else {
backnews="你输入的用户名或密码有误!";
fail(request,response,username,backnews);
}
}else {
backnews="请输入用户名和密码";
fail(request,response,username,backnews);
}
} catch (Exception e) {
backnews=""+e.toString();
e.printStackTrace();
fail(request,response,username,backnews);
}finally {
//5.释放资源 connection prepareStatement
JdbcUtils.close(connection, prepareStatement, rs);
}
out.flush();
out.close();
}/**
* @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 success(HttpServletRequest request, HttpServletResponse response,String logname,String signature,String backnews) {
try {
PrintWriter out = response.getWriter();
out.print("Login succeeded!");
out.print(backnews);
out.print(logname);
out.print(signature);
}catch(IOException e) {
e.printStackTrace();
}
}
public void fail(HttpServletRequest request, HttpServletResponse response,String logname,String backnews) {
response.setContentType("text/html;charset=utf-8");
try {
PrintWriter out = response.getWriter();
out.println(backnews);
}catch(IOException e) {
e.printStackTrace();
}
}}
3. 因为要通过网络获取到用户头像资源,所以需要创建LoadImgByNet.java文件,对网络图片资源进行处理,代码如下:
package com.example.discover; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class LoadImgByNet { public static Bitmap getBitmap(String path) throws IOException { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200){ InputStream inputStream = conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } return null; } }
4.在Android项目的MyTabFragment.java中给注册、登录按钮绑定事件
package com.example.discover; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyTabFragment extends Fragment{ TableRow account_set_bt; //第一个功能 View myLayout; //“我的”页面 Button pop_register,pop_login; //弹出对话框的按钮 ImageView my_head_img; //用户头像 TextView my_name,my_sign; //用户昵称和心情 /*Button go_login,go_register;*/ String userName,passWord,signature,headImg; //存放用户基本信息 RelativeLayout login,register; //注册、登录页面 LinearLayout login_top,un_login_top; //“我的”页面顶部两种状态下的布局 Activity mActivity; //存放当前的activity TextView test3; //用于返回测试信息 String baseUrl = "http://10.0.2.2:8080/iShareService/servlet/"; //web服务器的地址 String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images/"; //图片资源 boolean isLogin; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { myLayout = inflater.inflate(R.layout.my_tab_content, container, false); return myLayout; } //APP如果在主线程中请求网络操作,将会抛出异常,所以需要用线程来操作网络请求 void setVersion() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() //探测SQLite数据库操作 .penaltyLog() //打印logcat .penaltyDeath() .build()); } //绑定点击事件 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mActivity = this.getActivity(); // 设置线程策略 setVersion(); login_top = ( LinearLayout)getActivity().findViewById(R.id.login_top); //“我的”页面顶部登录后显示的用户信息 un_login_top = (LinearLayout)getActivity().findViewById(R.id.un_login_top); //“我的”页面未登录时显示的登录、注册按钮 my_head_img = ( ImageView) getActivity().findViewById(R.id.images_head); //我的头像 my_name = (TextView) getActivity().findViewById(R.id.t_name); //我的昵称 my_sign = (TextView) getActivity().findViewById(R.id.t_sign); //我的签名 account_set_bt =(TableRow)getActivity().findViewById(R.id.more_page_row1); //"我的"界面第一个功能 account_set_bt.setOnClickListener(new mClick()); pop_register = (Button)getActivity().findViewById(R.id.pop_register); //弹出注册对话框的按钮 pop_login = (Button)getActivity().findViewById(R.id.pop_login); //弹出登录对话框的按钮 test3 = (TextView) getActivity().findViewById(R.id.test3_info); //测试 //根据登录状态显示不同的UI ,用SharePreferences判断用户是否登录 changeStatus(); /* SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ //已经登录时设置用户相关信息为显示状态 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); }else{ //尚未登录,设置登录、注册按钮为显示状态 un_login_top.setVisibility(View.VISIBLE); // 设置线程策略 setVersion(); }*/ pop_register.setOnClickListener(new popClick()); //弹出注册登录对话框事件 pop_login.setOnClickListener(new popClick()); } //“我的”页面中相关点击事件 class mClick implements View.OnClickListener { public void onClick(View v) { if(isLogin) { if (v == account_set_bt) { //点击了账号管理 Intent account_manage_intent = new Intent(); account_manage_intent.setClass(mActivity, AccountManagement.class); //创建intent对象,并制定跳转页面 startActivity(account_manage_intent); //跳转到账号管理页面 /*TextView textView = (TextView) getActivity().findViewById(R.id.test_text_view); //用于放测试的提示信息 Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();*/ } }else{ Toast.makeText(getActivity(), "请先登录!", Toast.LENGTH_LONG).show(); } } } //登录、注册弹框 class popClick implements View.OnClickListener { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); public void onClick(View v) { if (v == pop_register) { register= (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_register, null); //从另外的布局关联组件 builder.setTitle("用户注册").setMessage("请输入用户名和密码").setView(login); builder.setTitle("i 分享").setView(register); builder.setNegativeButton("取消", new exitClick()); /*dialog.setPositiveButton("注册", new registerClick());*/ builder.setPositiveButton("注册", null); //不监听,防止被关闭 builder.setIcon(R.drawable.app_icon); final AlertDialog dialog = builder.create(); dialog.show(); //不会自动关闭对话框,可手动关闭 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show(); StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName,txtUserPass1,txtUserPass2,txtSignature; TextView test1; String passWord2; txtUserName = (EditText)register.findViewById(R.id.et_username); txtUserPass1 = (EditText)register.findViewById(R.id.et_password1); txtUserPass2 = (EditText)register.findViewById(R.id.et_password2); txtSignature= (EditText)register.findViewById(R.id.et_signature); test1 = (TextView)register.findViewById(R.id.test1_view_info); userName = txtUserName.getText().toString(); passWord = txtUserPass1.getText().toString(); passWord2 = txtUserPass2.getText().toString(); signature = txtSignature.getText().toString(); //从密码框中取值比较 if(!passWord.equals(passWord2)){ test1.setText("两次密码不一致!"); Toast.makeText(getActivity(), "两次密码不一致", Toast.LENGTH_LONG).show(); return; } try { String registerUrl = baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature; URL url = new URL(registerUrl); 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); } test1.setText(stringBuilder); dialog.dismiss(); //注册成功,手动关闭对话框 buffer.close(); }else{ test1.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test1.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test1.getText(), Toast.LENGTH_LONG).show(); test3.setText(userName+"——"+passWord+"——"+passWord2+"——"+signature+"——"+baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature+"_"+test1.getText()); } }); } else if (v == pop_login) { login = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_login, null); //从另外的布局关联组件 builder.setTitle("i 分享").setView(login); builder.setNegativeButton("取消", new exitClick()); builder.setPositiveButton("登录", null); builder.setIcon(R.drawable.app_icon); final AlertDialog dialog2 = builder.create(); dialog2.show(); //不会自动关闭对话框,可手动关闭 dialog2.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show(); StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName2,txtUserPass2; TextView test2; txtUserName2 = (EditText)login.findViewById(R.id.et_login_username); txtUserPass2 = (EditText)login.findViewById(R.id.et_login_password); test2 = (TextView)login.findViewById(R.id.test2_view_info); userName = txtUserName2.getText().toString(); passWord = txtUserPass2.getText().toString(); //从密码框中取值比较 if(userName.length()==0||passWord.length()==0){ test2.setText("用户名和密码不能为空!"); Toast.makeText(getActivity(), "用户名和密码不能为空!", Toast.LENGTH_LONG).show(); return; } try { String LoginUrl = baseUrl+"Login?username="+userName+"&password="+passWord; URL url = new URL(LoginUrl); 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); } test2.setText(stringBuilder); //获取到登录的用户昵称、签名和头像 signature = stringBuilder.toString(); headImg = stringBuilder.toString(); loginSuccess(userName,signature,headImg); dialog2.dismiss(); //登录成功,手动关闭对话框 buffer.close(); }else{ test2.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test2.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test2.getText(), Toast.LENGTH_LONG).show(); test3.setText(userName+"——"+passWord); //dialog2.dismiss() } }); } } } //登录成功后的界面以及状态更改 public void loginSuccess(String name,String sign,String headImg){ //登录成功后更改登录状态为已登录 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putBoolean("isLogin", true); editor.putString("name", name); editor.putString("sign", sign); editor.putString("img", headImg); editor.commit(); //UI更新 changeStatus(); } //根据状态显示或隐藏“我的”页面中头部信息 public void changeStatus(){ //获取最新的登录状态,SharePreferences为永久存储,需要手动退出 SharedPreferences sp = mActivity.getSharedPreferences("save", Context.MODE_PRIVATE); isLogin = sp.getBoolean("isLogin",false); if(isLogin){ Bitmap one; userName = sp.getString("name",""); signature = sp.getString("sign",""); headImg = sp.getString("headImg",""); //设置用户昵称、头像、心情 my_name.setText(userName); my_sign.setText(userName); //通过网络链接获取图片 try { one= LoadImgByNet.getBitmap(imgBaseUrl+"my_tab_list1.png"); my_head_img.setImageBitmap(one); }catch(IOException e){ e.printStackTrace(); } //已经登录时设置用户相关信息为显示状态 //username = this.getActivity().getSharedPreferences("config", Context.MODE_PRIVATE).getString("fname", ""); login_top.setVisibility(View.VISIBLE); un_login_top.setVisibility(View.GONE); }else{ //尚未登录,设置登录、注册按钮为显示状态 un_login_top.setVisibility(View.VISIBLE); login_top.setVisibility(View.GONE); } } //注册对话框的“注册”按钮 /*class registerClick implements DialogInterface.OnClickListener{ StringBuilder stringBuilder = new StringBuilder(); BufferedReader buffer = null; HttpURLConnection connGET = null; EditText txtUserName,txtUserPass1,txtUserPass2,txtSignature; TextView test1; String passWord2; public void onClick(DialogInterface dialog,int which){ txtUserName = (EditText)register.findViewById(R.id.et_username); txtUserPass1 = (EditText)register.findViewById(R.id.et_password1); txtUserPass2 = (EditText)register.findViewById(R.id.et_password2); txtSignature= (EditText)register.findViewById(R.id.et_signature); test1 = (TextView)register.findViewById(R.id.test1_view_info); userName = txtUserName.getText().toString(); passWord = txtUserPass1.getText().toString(); passWord2 = txtUserPass2.getText().toString(); signature = txtSignature.getText().toString(); //从密码框中取值比较 if(!passWord.equals(passWord2)){ test1.setText("两次密码不一致!"); Toast.makeText(getActivity(), "两次密码不一致", Toast.LENGTH_LONG).show(); return; } try { String registerUrl = baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signatstringbuilder用法ure; URL url = new URL(registerUrl); 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); } test1.setText(stringBuilder); buffer.close(); }else{ test1.setText("非200.."+connGET.getResponseCode() ); } } catch (Exception e) { e.printStackTrace(); test1.setText("get 提交 err.." + e.toString()); } Toast.makeText(getActivity(), test1.getText(), Toast.LENGTH_LONG).show(); //dialog.dismiss(); test3.setText(userName+"——"+passWord+"——"+passWord2+"——"+signature+"——"+baseUrl+"Register?username="+userName+"&password="+passWord+"&signature="+signature+"_"+test1.getText()); } }*/ //输入对话框的“退出”按钮事件 class exitClick implements DialogInterface.OnClickListener{ public void onClick(DialogInterface dialog,int which){ dialog.cancel(); //关闭对话框 /* try { Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); field.setAccessible(true); field.set(dialog, true); } catch (Exception e) { e.printStackTrace(); }*/ } } }