一、系统架构:
设计采用C/S架构,前端使用JAVA开发app的客户端,服务器采用多线程+套接字架构开发一个数据后台用来传送数据。
二、效果图:
1.主页:
2.榜单页:
3.预告片页:
4.动态评论页:
5.登录页:
三、数据库设计:
四、详细设计:
1.主页:
2.榜单页:
3.预告页:
4.动态页:
5.登录页:
五、代码:
(一)数据后台:
1.DBUtil.java:
package com.bn.databaseutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.bn.util.Constant;
/**
* 数据库层,与数据库交互进行增删查改
* @author 15518
*
*/
public class DBUtil {
/**
* 连接数据库
* @return connection连接
*/
public static Connection getConnection() {
Connection con = null;//声明连接
try {
Class.forName("org.gjt.mm.mysql.Driver");//声明驱动
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "moviebse?useUnicode=true&characterEncoding=UTF-8",
"Cailinhao", "CAIlinhao11014359");//获得连接
} catch (Exception e) {e.printStackTrace();}
return con;//返回连接
}
/**
* 登录验证
* @param uses 用户名
* @return 该用户在表中的具体信息
*/
public static String loginValid(String username) {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from users where usname=" + username;
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer message = new StringBuffer();//将查询到的信息进行字符串拼接
while (rs.next()) {
//进行字符串拼接
for (int i = 1; i <= 3; i++) {
message.append(rs.getString(i) + "<#>");//usname<#>pwd<#>uid<#>
}
//如果查找到信息,就返回拼接后的字符串
if (message.length() > 0) {
return message.substring(0, message.length() - 3)
.toString();//usname<#>pwd<#>uid
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 按名称查找电影
* @param cid 电影编号
* @return
*/
public static String getMovieByName(String cname) {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from movies where cname='" + cname + "'";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer message = new StringBuffer();//将查询到的信息进行字符串拼接
while (rs.next()) {
//进行字符串拼接
for (int i = 1; i <= 10; i++) {
message.append(rs.getString(i) + "<#>");//cid<#>cimg<#>cname<#>.....<#>
}
//如果查找到信息,就返回拼接后的字符串
if (message.length() > 0) {
return message.substring(0, message.length() - 3)
.toString();//cid<#>cimg<#>cname<#>.....
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 插入评论
* @param username 用户名
* @param detail 评论内容
*/
public static void insertEvaluate(String username,String detail) {
Connection con = getConnection();
Statement st = null;
try {
st = con.createStatement();
String sql = "insert into evaluate(username,detail) values('"+username+"','"+detail+"')";
System.out.println("sql " + sql);
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
}
/**
* 获取电影列表
* @return 电影列表拼接后的字符串
*/
public static String getMovieList() {
Connection con = getConnection();
Statement st = null;
ResultSet prs = null;
try {
st = con.createStatement();
String sql = "select * from movies";
System.out.println("sql " + sql);
prs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
while (prs.next()) {
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
String cimg = prs.getString(1);
String cname = prs.getString(2);
String clevel = prs.getString(3);
String cgrade = prs.getString(4);
String cact = prs.getString(5);
String cstate = prs.getString(6);
String csort = prs.getString(7);
String ctime = prs.getString(8);
String cintro = prs.getString(9);
sb.append(cname + "<#>" + clevel + "<#>"
+ cgrade + "<#>" + cact + "<#>" + cstate
+ "<#>" + csort + "<#>" + ctime + "<#>" + cintro
+ "<%>");//cname<#>...<#>cintro<#><%>cname<#>...<#>cintro<#><%>cname<#>...<#>cintro<#><%>
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);//cname<#>...<#>cintro<#><%>cname<#>...<#>cintro<#><%>cname<#>...<#>cintro<#>
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {prs.close();} catch (SQLException e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 获取评论列表
* @return 评论拼接后的字符串
*/
public static String getEvaluateList() {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from evaluate";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
while (rs.next()) {
int id = rs.getInt(1);
String username = rs.getString(2);
String datail = rs.getString(3);
sb.append(id + "<#>" + username + "<#>" + datail
+ "<%>");//id<#>...<#>datail<#><%>id<#>...<#>datail<#><%>id<#>...<#>datail<#><%>
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);//id<#>...<#>datail<#><%>id<#>...<#>datail<#><%>id<#>...<#>datail<#>
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 获取视频列表
* @return 视频列表拼接后的字符串
*/
public static String getVideoList() {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select vid,vname,vimg,vurl from videos";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
while (rs.next()) {
int vid = rs.getInt(1);
String vname = rs.getString(2);
String vimg = rs.getString(3);
String vurl = rs.getString(4);
sb.append(vid + "<#>" + vname + "<#>" + vimg + "<#>" + vurl + "<#>" + "<%>");//vid<#>...<#>vurl<#><%>vid<#>...<#>vurl<#><%>vid<#>...<#>vurl<#><%>
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);//vid<#>...<#>vurl<#><%>vid<#>...<#>vurl<#><%>vid<#>...<#>vurl<#>
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 获取轮播图
* @return 轮播图表拼接后的字符串
*/
public static String getSwipers() {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from swipers";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
while (rs.next()) {
String sid = rs.getString(1);
String simg = rs.getString(2);
sb.append(sid + "<#>" + simg + "<#>" + "<%>");//sid<#>...<#>simg<#><%>sid<#>...<#>simg<#><%>sid<#>...<#>simg<#><%>
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);//sid<#>...<#>simg<#><%>sid<#>...<#>simg<#><%>sid<#>...<#>simg<#>
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 获取主页的口碑榜
* @return 拼接的字符串
*/
public static String getRanking1() {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from ranking1_homepage";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
while (rs.next()) {
String rid = rs.getString(1);
String rname = rs.getString(2);
sb.append(rid + "<#>" + rname + "<#>" + "<%>");
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
/**
* 获取主页的热映榜
* @return 拼接的字符串
*/
public static String getRanking2() {
Connection con = getConnection();
Statement st = null;
ResultSet rs = null;
try {
st = con.createStatement();
String sql = "select * from ranking2_homepage";
System.out.println("sql " + sql);
rs = st.executeQuery(sql);
StringBuffer sb = new StringBuffer();//将查询到的信息进行字符串拼接
//循环读取每一条记录,并将每条记录按指定格式拼接在一起。
while (rs.next()) {
String rid = rs.getString(1);
String rname = rs.getString(2);
sb.append(rid + "<#>" + rname + "<#>" + "<%>");
}
//如果查找到信息,就返回拼接后的字符串
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 3);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {rs.close();} catch (Exception e) {e.printStackTrace();}
try {st.close();} catch (SQLException e) {e.printStackTrace();}
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
//未查找到信息返回NO_MESSAGE
return Constant.NO_MESSAGE;
}
}
2.ServerAgentThread.java:
package com.bn.server;
import java.io.*;
import java.net.*;
import com.bn.databaseutil.*;
import com.bn.util.*;
/**
* 多线程+套接字,根据Constant类中规定的字符串用来获取安卓端发送的请求,并根据不同的请求类型(字符串不同)来执行数据后端不同的函数操作数据库
*/
public class ServerAgentThread extends Thread {
Socket sc;
DataInputStream din;
DataOutputStream dout;
FileInputStream fis;
String picPath;
File file;
byte[] bb;
Boolean flag;
String thumbnailpath;
public ServerAgentThread(Socket sc) {
this.sc = sc;
}
public void run() {
try {
din = new DataInputStream(sc.getInputStream());//创建数据输入流
dout = new DataOutputStream(sc.getOutputStream());//创建数据输出流
String msg = din.readUTF();//将数据放入字符串
System.out.println("msg "+msg);
//按名称获取图片。图片名跟在“GET_IMAGE”后面,形式为:Constant.GET_IMAGE picName
if (msg.startsWith(Constant.GET_IMAGE)) {
//根据后端发来的字符串序列截取图片名称
String remsg = msg.substring(Constant.GET_IMAGE.length(),msg.length());
File fileResource = new File("resource");//创建文件流
picPath = fileResource.getAbsolutePath() + "\\IMAGE\\";//文件路径
file = new File(picPath + remsg);
System.out.println("file "+file.getAbsolutePath());
fis = new FileInputStream(file);
byte[] bb = new byte[fis.available()];
fis.read(bb);
dout.writeInt(bb.length);
dout.write(bb);
fis.close();
}
//获取电影列表
else if (msg.startsWith(Constant.GET_MOVIE_LIST)) {
String rem = DBUtil.getMovieList();
dout.writeUTF(rem);
}
//获取视频列表
else if (msg.startsWith(Constant.GET_VIDEO_LIST)) {
String rem = DBUtil.getVideoList();
dout.writeUTF(rem);
}
//按名称查找电影,电影名跟在“SEAECH_CERTAIN_MOVIE”后面,形式为:Constant.SEAECH_CERTAIN_MOVIE cname
else if (msg.startsWith(Constant.SEAECH_CERTAIN_MOVIE)) {
String cname = msg.substring(
//根据后端发来的字符串序列截取电影名
Constant.SEAECH_CERTAIN_MOVIE.length(), msg.length());
String remsg = DBUtil.getMovieByName(cname);
dout.writeUTF(remsg);
}
//按用户名查找用户信息,用户名跟在“LOGIN_VALID”后面,形式为:Constant.LOGIN_VALID username
else if (msg.startsWith(Constant.LOGIN_VALID)) {
//根据后端发来的字符串序列截取用户名
String username = msg.substring(Constant.LOGIN_VALID.length(), msg.length());
String remsg = DBUtil.loginValid(username);
dout.writeUTF(remsg);
}
//获取轮播图
else if (msg.startsWith(Constant.GET_SWIPERS)) {
String rem = DBUtil.getSwipers();
dout.writeUTF(rem);
}
//获取主页口碑榜
else if (msg.startsWith(Constant.GET_RANKING1)) {
String rem = DBUtil.getRanking2();
dout.writeUTF(rem);
}
//获取主页热映榜
else if (msg.startsWith(Constant.GET_RANKING2)) {
String rem = DBUtil.getRanking1();
dout.writeUTF(rem);
}
//获取评论
else if (msg.startsWith(Constant.GET_EVALUATE)) {
String rem = DBUtil.getEvaluateList();
dout.writeUTF(rem);
}
//插入评论,评论人和评论内容跟在“INSERT_EVALUATE”后面,形式为:Constant.INSERT_EVALUATE username#detail
else if (msg.startsWith(Constant.INSERT_EVALUATE)) {
String message=msg.substring(Constant.INSERT_EVALUATE.length(),msg.length());
//根据后端发来的字符串序列截取评论信息
String username=message.substring(0, message.indexOf("#"));
String detail=message.substring(message.indexOf("#")+1);
DBUtil.insertEvaluate(username, detail);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
din.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
dout.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.ServerThread.java:
package com.bn.server;
import java.net.*;
/**
* 线程类,使用线程来持续接收请求,并暴露一个端口号,统一网络下的主机通过该端口号来向本数据端发送请求
*/
public class ServerThread extends Thread{
ServerSocket ss;//定义一个ServerSocket对象
int technique;//定一个义端口号
public ServerThread (int technique) {
this.technique=technique;
}
@Override
public void run(){//重写run方法
try{
ss=new ServerSocket(technique);//创建一个ServerSocket对象
System.out.println("start on "+technique);
while(true){
Socket sk=ss.accept();
new ServerAgentThread(sk).start();//创建并开启一个代理线程
}}
catch(Exception e){e.printStackTrace();}
}
public static void main(String args[]){
new ServerThread(8888).start();
}
}
4.Constant.java:
package com.bn.util;
/**
* Android端和数据后台统一字符串序列
* @author 15518
*
*/
public class Constant {
//查询内容为空或条件没有限制
public static String NO_MESSAGE = "No Message";
//按图片名称获取图片
public static String GET_IMAGE = "<#GET_IMAGE#>";
//获取电影列表
public static String GET_MOVIE_LIST="<#GET_MOVIE_LIST#>";
//获取视频列表
public static String GET_VIDEO_LIST="<#GET_VIDEO_LIST#>";
//按名称获取电影详情
public static String SEAECH_CERTAIN_MOVIE = "<#SEAECH_CERTAIN_MOVIE#>";
//登录验证
public static String LOGIN_VALID = "<#LOGIN_VALID#>";
//获取轮播图
public static String GET_SWIPERS = "<#GET_SWIPERS#>";
//获取主页口碑榜
public static String GET_RANKING1 = "<#GET_RANKING1#>";
//获取主页热映榜
public static String GET_RANKING2 = "<#GET_RANKING2#>";
//获取评论动态
public static String GET_EVALUATE = "<#GET_EVALUATE#>";
//插入评论动态
public static String INSERT_EVALUATE = "<#INSERT_EVALUATE#>";
}
(二)Android端:
—布局文件:
1AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.activity"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 用于读取手机当前的状态 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 访问网络,网络定位需要上网 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- SD卡读取权限,用户写入离线定位数据 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 大内存 -->
<application
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="仿豆瓣评分"
android:largeHeap="true"
android:hardwareAccelerated="false"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- 电影详请 -->
<activity android:name="com.example.a15518.movies_connectdatabase.activity.DetailsFileActivity" />
<!-- 首页 -->
<activity android:name="com.example.a15518.movies_connectdatabase.activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--登录页面-->
<activity android:name="com.example.a15518.movies_connectdatabase.activity.LoginActivity" />
</application>
</manifest>
2.left_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="2000"
android:fromXDelta="-100%p"
android:toXDelta="0" />
</set>
3.left_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="2000"
android:fromXDelta="-100%p"
android:toXDelta="0" />
</set>
4.shape_corner.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--圆角矩形-->
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners
android:topLeftRadius="300dp"
android:topRightRadius="300dp"
android:bottomLeftRadius="300dp"
android:bottomRightRadius="300dp"/>
<solid android:color="@color/red"/>
</shape>
5.shape_corner_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"/>
<solid android:color="@color/honeydew"/>
</shape>
<!--
android:radius 全部的圆角半径,为角的弧度,值越大角越圆
android:topLeftRadius 左上角的圆角半径
android:topRightRadius 右上角的圆角半径
android:bottomLeftRadius 左下角的圆角半径
android:bottomRightRadius 右下角的圆角半径
solid:设置填充色
-->
6.activity_login.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@drawable/backgroundimg">
<LinearLayout
android:layout_width="340dp"
android:layout_height="300dp"
android:layout_gravity="center_horizontal"
android:background="@drawable/shape_corner_login"
android:layout_marginTop="50dp"
android:orientation="vertical">
<!--图片加账号密码-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--图片-->
<ImageView
android:layout_width="100dp"
android:layout_height="120dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="15dp"
android:background="@drawable/logo" />
<!--账号密码框-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_marginLeft="8dp"
android:background="@drawable/shape_corner"
android:backgroundTint="@color/white"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5dp"
android:layout_gravity="center"
android:text="账号"
android:textSize="20sp"/>
<EditText
android:id="@+id/usname"
android:layout_width="170dp"
android:layout_height="50dp"
android:hint="输入账号"
android:textColor="@color/gray"
android:paddingLeft="5dp"
android:background="@null"/>
</LinearLayout>
<LinearLayout
android:layout_marginLeft="8dp"
android:background="@drawable/shape_corner"
android:backgroundTint="@color/white"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginRight="5dp"
android:layout_gravity="center"
android:text="密码"
android:textSize="20sp"/>
<EditText
android:id="@+id/pwd"
android:layout_width="170dp"
android:layout_height="50dp"
android:textColor="@color/gray"
android:hint="输入密码"
android:paddingLeft="5dp"
android:background="@null"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"
android:textSize="18sp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:checked="true"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自动登录"
android:textSize="18sp"
android:layout_marginLeft="105dp"
android:layout_marginTop="15dp"
android:checked="true"/>
</LinearLayout>
<!--登录按钮-->
<Button
android:id="@+id/btnlogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:backgroundTint="@color/darkslateblue"
android:gravity="center"
android:paddingLeft="80dp"
android:paddingTop="20dp"
android:paddingRight="80dp"
android:paddingBottom="20dp"
android:text="登录"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
<!--复选框:隐身登录+开启震动-->
<LinearLayout
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:orientation="horizontal">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐身登录"
android:textSize="18sp"
android:textColor="@color/dimgrey"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开启震动"
android:textSize="18sp"
android:textColor="@color/dimgrey"
android:layout_marginLeft="115dp"
android:layout_marginTop="15dp"/>
</LinearLayout>
</LinearLayout>
7.activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Fragment容器-->
<LinearLayout
android:id="@+id/fragment_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp">
</LinearLayout>
<!--底部五个按钮-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<Button
android:id="@+id/btnone"
android:layout_width="0dp"
android:layout_weight="1"
android:drawableTop="@drawable/btn_one"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_height="match_parent"
android:text="首页"
android:textSize="8sp"
android:textColor="@color/gray"
android:background="#FFFFFF"
android:gravity="center"/>
<Button
android:id="@+id/btntwo"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_height="match_parent"
android:text="电影"
android:textSize="7sp"
android:textColor="@color/gray"
android:background="#FFFFFF"
android:drawableTop="@drawable/btn_two"
android:gravity="center"/>
<Button
android:id="@+id/btnthree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="预告"
android:textSize="8sp"
android:textColor="@color/gray"
android:background="#FFFFFF"
android:drawableTop="@drawable/btn_three"/>
<Button
android:id="@+id/btnfour"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="影迷动态"
android:textSize="8sp"
android:textColor="@color/gray"
android:background="#FFFFFF"
android:drawableTop="@drawable/btn_four"/>
<Button
android:id="@+id/btnfive"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="我的"
android:textSize="8sp"
android:textColor="@color/gray"
android:background="#FFFFFF"
android:drawableTop="@drawable/btn_five"/>
</LinearLayout>
</LinearLayout>
8.evaluate_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--评价Fragment-->
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<!--顶部标题-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="讨论区"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
<!--评价列表-->
<GridView
android:id="@+id/evaluatelist"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:numColumns="1" />
<!--评论-->
<LinearLayout
android:orientation="horizontal"
android:layout_height="50dp"
android:layout_width="match_parent">
<EditText
android:id="@+id/mydetail"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@color/white"
android:gravity="center_vertical"
android:hint="我也说两句..."
android:textSize="20sp" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
android:textColor="@color/gray"
android:background="@color/paleturquoise"/>
</LinearLayout>
</LinearLayout>
9.evaluate_item.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="horizontal"
android:background="@color/white"
android:layout_marginBottom="10dp">
<ImageView
android:id="@+id/img"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="15dp"
android:src="@drawable/head"/>
<LinearLayout
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:textSize="15sp"
android:textColor="@color/dimgrey"
android:text="用户名"/>
<TextView
android:id="@+id/detail"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="5dp"
android:text="评论内容"/>
</LinearLayout>
</LinearLayout>
10.homepage_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--主页Fragment-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--轮播图-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<ViewFlipper
android:id="@+id/flipper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<ImageView
android:id="@+id/swiper1"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/swiper2"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/swiper3"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/swiper4"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ViewFlipper>
</LinearLayout>
<!--热门片单标题-->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="热门片单"
android:gravity="center"
android:textSize="30dp"
android:textColor="@color/dodgerblue"/>
<!--两个榜单列表-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginRight="2dp"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="一周口碑榜"
android:textSize="20dp"
android:textColor="@color/black"
android:layout_marginBottom="5dp"/>
<!--口碑榜列表-->
<GridView
android:id="@+id/ranking1"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:numColumns="1"
android:verticalSpacing = "5dp"
android:background="@color/aliceblue"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="2dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="正在热映"
android:textSize="20dp"
android:textColor="@color/black"
android:layout_marginBottom="5dp"/>
<!--热映榜列表-->
<GridView
android:layout_gravity="center"
android:id="@+id/ranking2"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:numColumns="1"
android:verticalSpacing = "5dp"
android:background="@color/aliceblue"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
11.movie_detail.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:paddingBottom="2dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:background="@drawable/backgroundimg">
<!--自定义页面顶部-->
<Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp">
<TextView
android:id="@+id/ret"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回"
android:textColor="@color/gray"
android:textSize="10sp"
android:gravity="left"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="电影"
android:textSize="15sp"
android:textColor="@color/gray"
android:layout_gravity="center"
android:gravity="center"/>
</Toolbar>
<!--电影介绍-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="15dp">
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_marginRight="10dp"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:text="你好,李焕英"/>
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent"
android:textSize="12dp"
android:text="猫眼评分 9.3"
android:paddingTop="5dp"/>
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/gray"
android:text="主演:贾玲"
android:paddingTop="20dp"/>
<TextView
android:id="@+id/text6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/gray"
android:text="上映类型"/>
<TextView
android:id="@+id/text7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/gray"
android:text="上映时间"
android:ellipsize="end"
android:lines="1"/>
</LinearLayout>
</LinearLayout>
<!--简介标题+收起按钮-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="简介"
android:textColor="#FFFFFF"
android:textSize="20sp"/>
<TextView
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="收起^"
android:textSize="10dp"
android:layout_gravity="center"
android:textColor="@color/gray"/>
</LinearLayout>
<!--具体简介-->
<TextView
android:id="@+id/text8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#FFFFFF"/>
</LinearLayout>
12.movie_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<!-- 电影页Fragment-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="10dp">
<!--顶部标题+搜索框-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<!--标题-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="榜单页面"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
<!--搜索框-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@color/gray">
<EditText
android:id="@+id/srearch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="@color/white"
android:drawableLeft="@drawable/ic_baseline_search_24"
android:gravity="center_vertical"
android:hint="搜索"
android:textSize="20sp" />
</FrameLayout>
</LinearLayout>
<!--电影列表-->
<GridView
android:id="@+id/movielist"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="0dp"
android:numColumns="1" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
13.movie_item.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="horizontal"
android:gravity="center"
android:paddingBottom="1dp"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="@+id/img1"
android:layout_width="100dp"
android:layout_height="150dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:text="你好,李焕英"/>
<TextView
android:id="@+id/text2"
android:text="影院"
android:textSize="12sp"
android:gravity="center"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@color/gray"/>
</LinearLayout>
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorPrimary"
android:textSize="16dp"
android:text="猫眼评分 9.3" />
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/gray"
android:text="主演:贾玲"/>
<TextView
android:id="@+id/text5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/gray"
android:text="今天63家电影院放映491场"/>
</LinearLayout>
<Button
android:id="@+id/btn"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top1"
android:background="@drawable/shape_corner"
android:clickable="false"/>
</LinearLayout>
14.ranking_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--主页中排行榜单条数据项的布局文件-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/skyblue"
android:gravity="center"
android:text="测试"/>
<TextView
android:id="@+id/txt2"
android:layout_marginLeft="3dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/skyblue"
android:gravity="center"
android:text="测试"/>
</LinearLayout>
15.video_fragment.xml:
文章来源:https://www.toymoban.com/news/detail-493679.html
<?xml version="1.0" encoding="utf-8"?>
<!--视频页Fragment-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--顶部标题-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="电影预告"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
<!--电影播放器-->
<VideoView
android:id="@+id/video"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<!--视频列表-->
<GridView
android:id="@+id/videolist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2"
android:layout_marginTop="10dp"
android:stretchMode="columnWidth"
android:verticalSpacing = "10dp">
</GridView>
</LinearLayout>
16.video_item.xml:
文章来源地址https://www.toymoban.com/news/detail-493679.html
<?xml version="1.0" encoding="utf-8"?>
<!--视频页面中单个视频项的布局文件-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--图片-->
<ImageView
android:id="@+id/img"
android:layout_width="150dp"
android:layout_height="100dp"
android:scaleType="centerCrop"
android:layout_gravity="center"/>
<!--视频名-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/title"
android:layout_gravity="center"
android:text="标题"/>
</LinearLayout>
—功能:
1.DetailsFileActivity.java:
package com.example.a15518.movies_connectdatabase.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.a15518.movies_connectdatabase.downLoader.ImageDownLoader;
import com.example.a15518.movies_connectdatabase.util.Constant;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
/*
* 电影详细信息界面
*/
public class DetailsFileActivity extends Activity {
String cname;//电影cname
Handler mHandler;//子线程代理
ImageDownLoader imageDownLoader;//图片下载器
boolean flag = true; //简介是否可见
private TextView btn1;//“收起”按钮
private TextView ret;//返回按钮
private TextView textView1;
private TextView textView3;
private TextView textView4;
private TextView textView6;
private TextView textView7;
private TextView textView8;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
//获取用户点击的电影名称,由上一个Activity传来
Bundle bundle = this.getIntent().getExtras();
cname = bundle.getString("cid", null);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String[] str = bundle.getStringArray("str");
if ( str != null) {
if (!str.equals(Constant.NO_MESSAGE)) {
//加载电影详细信息
loadReady(str);
}
}
}
};
new Thread() {
@Override
public void run() {
try {
String[] str = null; // 信息数组
//向服务器请求并返回电影详情信息
String mmsg = NetInfoUtil.getCRETAIN_MOVIE(cname);
//分解数据后端发来的字符串序列
str = mmsg.split("<#>");
Bundle bundle = new Bundle();
bundle.putStringArray("str", str);
Message msg = new Message();
msg.setData(bundle);
//向handler发送消息
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 加载电影详情信息
* @param str 电影详细信息数组
*/
private void loadReady(String[] str) {
imageDownLoader = new ImageDownLoader();
String cimg = str[1];
String cname = str[2];
String cgrade = str[4];
String cact = str[5];
String csort = str[7];
String ctime = str[8];
String cintro = str[9];
textView1=(TextView)this.findViewById(R.id.text1);
textView1.setText(cname);
textView3=(TextView)this.findViewById(R.id.text3);
textView3.setText(cgrade);
textView4=(TextView)this.findViewById(R.id.text4);
textView4.setText(cact);
textView6=(TextView)this.findViewById(R.id.text6);
textView6.setText(csort);
textView7=(TextView)this.findViewById(R.id.text7);
textView7.setText(ctime);
textView8=(TextView)this.findViewById(R.id.text8);
textView8.setText(cintro);
ImageView imgView=(ImageView)this.findViewById(R.id.img);
//从缓存或SD卡或服务器获取图片并设置到图片控件imgView上
new ImageDownLoader().imgExcute(imgView, cimg);
//收起按钮
btn1 = (TextView) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flag == true){
flag = false;
btn1.setText("展开v");
textView8.setVisibility(View.INVISIBLE);
}else{
flag = true;
textView8.setVisibility(View.VISIBLE);
btn1.setText("收起^");
}
}
});
//返回按钮
ret = (TextView) findViewById(R.id.ret);
ret.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(DetailsFileActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
imageDownLoader.cancelTaskNow();
}
}
2.LoginActivity.java:
package com.example.a15518.movies_connectdatabase.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a15518.movies_connectdatabase.util.Constant;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
public class LoginActivity extends Activity {
Handler mHandler;//子线程代理对象(向数据服务端发送的请求不能位于主线程)
Button loginbtn;//登录按钮
TextView usname;//用户名控件
TextView pwd;//密码控件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//初始化UI控件
initUI();
//登录点击事件
loginbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String[] str = bundle.getStringArray("str");
if ( str != null) {
if (!str.equals(Constant.NO_MESSAGE)) {
//加载电影详细信息
checkLoginValid(str);
}
}
}
};
new Thread() {
@Override
public void run() {
try {
String[] str = null;//信息数组
//向服务器请求并返回用户信息
String mmsg = NetInfoUtil.getLogInfo(usname.getText()+"");
//后台返回的数据以<#>分成若干段保存在数组中
str = mmsg.split("<#>");
Bundle bundle = new Bundle();
bundle.putStringArray("str", str);
Message msg = new Message();
msg.setData(bundle);
//向handler发送消息
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
}
/**
* 检查登录是否成功
* @param str 数据服务端查询数据库获取到的该用户信息
*/
private void checkLoginValid(String[] str) {
if(str.length<2) {//登陆失败
Toast error = Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT);
error.show();
usname.setText("");
pwd.setText("");
return;
}
String username = str[0];
String password = str[1];
String uid = str[2];
if (usname.getText().toString().equals(username)&&pwd.getText().toString().equals(password)){//登录成功
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("uid",uid);
startActivity(intent);
Toast message = Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT);
message.show();
}
}
//初始化UI控件函数
public void initUI(){
loginbtn = findViewById(R.id.btnlogin);
usname = findViewById(R.id.usname);
pwd = findViewById(R.id.pwd);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
3.MainActivity.java:
package com.example.a15518.movies_connectdatabase.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import com.example.a15518.movies_connectdatabase.tabFragment.Evaluate_Fragment;
import com.example.a15518.movies_connectdatabase.tabFragment.HomePage_Fragement;
import com.example.a15518.movies_connectdatabase.tabFragment.Movie_Fragement;
import com.example.a15518.movies_connectdatabase.tabFragment.Video_Fragment;
import com.example.activity.R;
/**
* 主界面Activity
*/
public class MainActivity extends FragmentActivity {
//主页底部按钮
Button btnone;
Button btntwo;
Button btnthree;
Button btnfour;
Button btnfive;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//解决线程问题
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//初始化UI控件
initUI();
//首页按钮点击事件,Fragment转换
btnone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//第一步:创建Fragment的实例对象
HomePage_Fragement fragment = new HomePage_Fragement();
//第二步:调用activity的getSupportFragmentManager()获取FragmentManager对象
FragmentManager fragmentManager = getSupportFragmentManager();
//第三步:获取FragmentTrasction对象
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//第四步:FragmentTrasction对象调用需要执行的方法add()、replace()、remove()
fragmentTransaction.replace(R.id.fragment_layout,fragment);
//第五步:FragmentTrasction对象调用commit()方法提交事务到Activity
fragmentTransaction.commit();
}
});
//电影按钮点击事件,Fragment转换
btntwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//第一步:创建Fragment的实例对象
Movie_Fragement fragment = new Movie_Fragement();
//第二步:调用activity的getSupportFragmentManager()获取FragmentManager对象
FragmentManager fragmentManager = getSupportFragmentManager();
//第三步:获取FragmentTrasction对象
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//第四步:FragmentTrasction对象调用需要执行的方法add()、replace()、remove()
fragmentTransaction.replace(R.id.fragment_layout,fragment);
//第五步:FragmentTrasction对象调用commit()方法提交事务到Activity
fragmentTransaction.commit();
}
});
//预告按钮点击事件,Fragment转换
btnthree.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//第一步:创建Fragment的实例对象
Video_Fragment fragment = new Video_Fragment();
//第二步:调用activity的getSupportFragmentManager()获取FragmentManager对象
FragmentManager fragmentManager = getSupportFragmentManager();
//第三步:获取FragmentTrasction对象
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//第四步:FragmentTrasction对象调用需要执行的方法add()、replace()、remove()
fragmentTransaction.replace(R.id.fragment_layout,fragment);
//第五步:FragmentTrasction对象调用commit()方法提交事务到Activity
fragmentTransaction.commit();
}
});
//影迷动态按钮点击事件,Fragment转换
btnfour.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//第一步:创建Fragment的实例对象
Evaluate_Fragment fragment = new Evaluate_Fragment();
//第二步:调用activity的getSupportFragmentManager()获取FragmentManager对象
FragmentManager fragmentManager = getSupportFragmentManager();
//第三步:获取FragmentTrasction对象
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//第四步:FragmentTrasction对象调用需要执行的方法add()、replace()、remove()
fragmentTransaction.replace(R.id.fragment_layout,fragment);
//第五步:FragmentTrasction对象调用commit()方法提交事务到Activity
fragmentTransaction.commit();
}
});
//登录按钮点击事件,Activity跳转
btnfive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
//初始化UI控件函数
public void initUI(){
btnone = (Button) findViewById(R.id.btnone);
btntwo = (Button) findViewById(R.id.btntwo);
btnthree = (Button) findViewById(R.id.btnthree);
btnfour = (Button) findViewById(R.id.btnfour);
btnfive = (Button) findViewById(R.id.btnfive);
}
}
4.ImageDownLoader.java:
package com.example.a15518.movies_connectdatabase.downLoader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;
import com.example.a15518.movies_connectdatabase.util.BitmapCache;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 用来根据图片名请求后端获取位于后端IMAGE文件夹下的相应图片
*/
public class ImageDownLoader {
static Handler mHandler;
//ExecutorService:线程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
static int a=0;
public ImageDownLoader() {
if (mHandler == null) {
mHandler = new Handler();
}
}
// 获取IMAGE文件夹下的图片
public void imgExcute(final ImageView view, final String picName) {
if (view == null || picName == null) {
return;
}
final Bitmap bm = BitmapCache.showCacheBitmap(picName);
if (bm != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
view.setImageBitmap(bm);
}
});
return;
}
if (singleThreadExecutor == null || singleThreadExecutor.isShutdown()) {
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
byte[] bb = NetInfoUtil.getCachePicture(picName);
final Bitmap bitmap = BitmapFactory.decodeByteArray(bb, 0,
bb.length);
if (bitmap != null) {
BitmapCache.addBitmapToMemoryCache(picName, bitmap);
mHandler.post(new Runnable() {
@Override
public void run() {
String target=view.getTag()+"";
if(target==null||target.startsWith(target))
{
view.setImageBitmap(bitmap);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void cancelTask() {
if (singleThreadExecutor != null) {
singleThreadExecutor.shutdown();
singleThreadExecutor = null;
}
}
public void cancelTaskNow() {
if (singleThreadExecutor != null) {
singleThreadExecutor.shutdownNow();
singleThreadExecutor = null;
}
}
}
5.Evaluate_Fragment.java:
package com.example.a15518.movies_connectdatabase.tabFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
import java.util.List;
public class Evaluate_Fragment extends Fragment implements View.OnClickListener {
List<String[]> evaluatelist; //评论信息
EditText detail;//输入评论控件
Button sendbtn;//发送评论按钮
private GridView evaluateGridView;//评论列表控件
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View movie_fragment=inflater.inflate(R.layout.evaluate_fragment,null);
initUI(movie_fragment);
evaluatelist = NetInfoUtil.getEvaluateList();//从数据库中获取所有评论
//加载评论信息到evaluateGridView
initEvaluateList();
//发送评论按钮点击事件
sendbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String username="山东建筑大学";
String detailevaluate = String.valueOf(detail.getText());
//向数据后端请求插入评论到数据库
NetInfoUtil.insertEvaluate(username,detailevaluate);
detail.setText("");
//重新加载更新后的评论
try {
//避免子线程加载慢,更新数据库慢,所以主线程睡眠2000ms
Thread.currentThread().sleep(2000);
evaluatelist = NetInfoUtil.getEvaluateList();
initEvaluateList();
Toast message = Toast.makeText(getActivity(),"评论成功",Toast.LENGTH_SHORT);
message.show();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
return movie_fragment;
}
//在界面上加载评论信息
private void initEvaluateList() {
BaseAdapter ba=new BaseAdapter() {
@Override
public int getCount() {
return evaluatelist.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//单条评论信息
String[] strs=evaluatelist.get(position);
String username=strs[1];
String datail=strs[2];
LinearLayout menu_item=(LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.evaluate_item, null);
TextView cname=(TextView) menu_item.findViewById(R.id.username);
cname.setText(username);
TextView clevel=(TextView) menu_item.findViewById(R.id.detail);
clevel.setText(datail);
return menu_item;
}
};
evaluateGridView.setAdapter(ba);
}
//初始化UI控件
private void initUI(View movie_fragment) {
evaluateGridView = movie_fragment.findViewById(R.id.evaluatelist);
sendbtn = movie_fragment.findViewById(R.id.btn);
detail = movie_fragment.findViewById(R.id.mydetail);
}
@Override
public void onClick(View v) {
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
6.HomePage_Fragement.java:
package com.example.a15518.movies_connectdatabase.tabFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.example.a15518.movies_connectdatabase.activity.DetailsFileActivity;
import com.example.a15518.movies_connectdatabase.downLoader.ImageDownLoader;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
import java.util.List;
public class HomePage_Fragement extends Fragment implements OnClickListener{
ImageDownLoader imageLoader;
List<String[]> swiperList;//轮播图列表
List<String[]> ranking1List;//口碑榜列表
List<String[]> ranking2List;//热映榜列表
private GridView ranking1GridView;//口碑榜列表控件
private GridView ranking2GridView;//热映榜列表控件
ImageView swiper1;
ImageView swiper2;
ImageView swiper3;
ImageView swiper4;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.homepage_fragment,null);
initUI(view);
//向数据后端发送请求获取轮播图
swiperList = NetInfoUtil.getSwipers();
imageLoader = new ImageDownLoader();
//从服务器获取图片并设置到图片控件上
imageLoader.imgExcute(swiper1, swiperList.get(0)[1]);
imageLoader.imgExcute(swiper2, swiperList.get(1)[1]);
imageLoader.imgExcute(swiper3, swiperList.get(2)[1]);
imageLoader.imgExcute(swiper4, swiperList.get(3)[1]);
//开启轮播图
ViewFlipper flipper = view.findViewById(R.id.flipper);
flipper.startFlipping();
//向数据后端发送请求获取两个榜单
ranking1List = NetInfoUtil.getRanking1();
ranking2List = NetInfoUtil.getRanking2();
//加载榜单到ranking1GridView、ranking2GridView
initRanking1List();
initRanking2List();
return view;
}
//在界面上加载口碑榜信息
private void initRanking1List() {
BaseAdapter ba=new BaseAdapter() {
@Override
public int getCount() {
return ranking1List.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] strs=ranking1List.get(position);
//电影序号
String txt_1=strs[0];
//电影名称
String txt_2=strs[1];
LinearLayout ranking_item=(LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.ranking_item, null);
TextView txt1=(TextView) ranking_item.findViewById(R.id.txt1);
txt1.setText(txt_1);
TextView txt2=(TextView) ranking_item.findViewById(R.id.txt2);
txt2.setText(txt_2);
return ranking_item;
}
};
ranking1GridView.setAdapter(ba);
}
//在界面上加载热映榜信息
private void initRanking2List() {
BaseAdapter ba=new BaseAdapter() {
@Override
public int getCount() {
return ranking2List.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] strs=ranking2List.get(position);
//电影序号
String txt_1=strs[0];
//电影名称
String txt_2=strs[1];
LinearLayout ranking_item=(LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.ranking_item, null);
TextView txt1=(TextView) ranking_item.findViewById(R.id.txt1);
txt1.setText(txt_1);
TextView txt2=(TextView) ranking_item.findViewById(R.id.txt2);
txt2.setText(txt_2);
return ranking_item;
}
};
ranking2GridView.setAdapter(ba);
}
//初始化UI控件
private void initUI(View view) {
ranking1GridView = view.findViewById(R.id.ranking1);
ranking2GridView = view.findViewById(R.id.ranking2);
swiper1 = view.findViewById(R.id.swiper1);
swiper2 = view.findViewById(R.id.swiper2);
swiper3 = view.findViewById(R.id.swiper3);
swiper4 = view.findViewById(R.id.swiper4);
}
@Override
public void onClick(View v) {
}
@Override
public void onDestroy() {
super.onDestroy();
imageLoader.cancelTask();
}
}
7.Movie_Fragement.java:
package com.example.a15518.movies_connectdatabase.tabFragment;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.a15518.movies_connectdatabase.activity.DetailsFileActivity;
import com.example.a15518.movies_connectdatabase.downLoader.ImageDownLoader;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
import java.util.List;
public class Movie_Fragement extends Fragment implements OnClickListener{
List<String[]> movielist; // 电影列表
ImageDownLoader imageLoader;//图片加载器
private GridView movieGridView;//电影列表控件
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View movie_fragment=inflater.inflate(R.layout.movie_fragment,null);
imageLoader = new ImageDownLoader();
movieGridView = movie_fragment.findViewById(R.id.movielist);
//向数据后端发送请求获取电影列表
movielist = NetInfoUtil.getMovieList();
//加载电影信息到movieGridView
initMovieList();
return movie_fragment;
}
//在界面上加载电影列表
private void initMovieList() {
BaseAdapter ba=new BaseAdapter() {
@Override
public int getCount() {
return movielist.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] strs=movielist.get(position);
//电影图片名
String primaryPic=strs[0];
//电影名称
String name=strs[1];
//电影画质
String level=strs[2];
//电影评分
String grade=strs[3];
//演员
String act=strs[4];
//放映量
String state=strs[5];
LinearLayout menu_item=(LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.movie_item, null);
ImageView iv=(ImageView) menu_item.findViewById(R.id.img1);
//从服务器获取图片并设置到图片控件iv上
imageLoader.imgExcute(iv, primaryPic);
TextView cname=(TextView) menu_item.findViewById(R.id.text1);
cname.setText(name);
TextView clevel=(TextView) menu_item.findViewById(R.id.text2);
clevel.setText(level);
TextView cgrade=(TextView) menu_item.findViewById(R.id.text3);
cgrade.setText(grade);
TextView cact=(TextView) menu_item.findViewById(R.id.text4);
cact.setText(act);
TextView cstate=(TextView) menu_item.findViewById(R.id.text5);
cstate.setText(state);
Button btn=(Button) menu_item.findViewById(R.id.btn);
int rank = position + 1;
btn.setText("TOP"+rank);
return menu_item;
}
};
movieGridView.setAdapter(ba);
movieGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
movieGridView.setOnItemClickListener(
new OnItemClickListener()
{ @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//点击的电影id号
String[] strs=movielist.get(arg2);
String cid=strs[1];
Intent intent = new Intent(getActivity(),DetailsFileActivity.class);
intent.putExtra("cid", cid);
startActivity(intent);
}
});
}
@Override
public void onClick(View v) {
}
@Override
public void onDestroy() {
super.onDestroy();
imageLoader.cancelTask();
}
}
8.Video_Fragment.java:
package com.example.a15518.movies_connectdatabase.tabFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;
import com.example.a15518.movies_connectdatabase.downLoader.ImageDownLoader;
import com.example.a15518.movies_connectdatabase.util.NetInfoUtil;
import com.example.activity.R;
import java.util.List;
public class Video_Fragment extends Fragment implements OnClickListener{
List<String[]> videolist; // 电影列表信息
ImageDownLoader imageLoader;//图片下载器
private VideoView video;//视频播放器
private GridView videoGridView;//视频列表控件
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View video_fragment=inflater.inflate(R.layout.video_fragment,null);
initUI(video_fragment);
//从数据库中获取电影列表
videolist = NetInfoUtil.getVideoList();
//加载视频信息到videoGridView
initVideoList();
return video_fragment;
}
//在界面上加载视频列表
private void initVideoList()
{
BaseAdapter ba=new BaseAdapter()
{
@Override
public int getCount() {
// TODO Auto-generated method stub
return videolist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String[] strs=videolist.get(position);
String vname=strs[1];
String vimg=strs[2];
LinearLayout menu_item=(LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.video_item, null);
ImageView iv=(ImageView) menu_item.findViewById(R.id.img);
//从服务器获取图片并设置到图片控件iv上
imageLoader.imgExcute(iv, vimg);
TextView name=(TextView) menu_item.findViewById(R.id.title);
name.setText(vname);
return menu_item;
}
};
videoGridView.setAdapter(ba);
videoGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
videoGridView.setOnItemClickListener(
new OnItemClickListener()
{ @Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
String[] strs=videolist.get(arg2);
String vurl = strs[3];
video.setVideoPath(vurl);
video.requestFocus();
video.start();
}});
}
//初始化UI控件
private void initUI(View video_fragment) {
imageLoader = new ImageDownLoader();
video = (VideoView) video_fragment.findViewById(R.id.video);
videoGridView = video_fragment.findViewById(R.id.videolist);
}
@Override
public void onClick(View v) {
}
@Override
public void onDestroy() {
super.onDestroy();
imageLoader.cancelTask();
}
}
9.BitmapCache.java:
package com.example.a15518.movies_connectdatabase.util;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.util.Log;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
/**
* 缓存Image的类,当存储Image的大小大于LruCache设定的值,系统自动释放内存
*/
public class BitmapCache {
//LruCache是android3.1及以后提供的缓存类,它是一个泛型类,内部以哈希表的形式存储了APP所需要的缓存
//数据,并提供了用于存和取的set、get方法。值得一说的是它内部支持的是LRU(Least Recently Used)缓存
//算法,就是指当缓存满了的时候,LruCache会移除最近较少使用的缓存对象来为新的缓存对象腾出必要的空间。
private static LruCache<String, Bitmap> mMemoryCache;
//软引用 2.3后偏向回收SoftReference,不建议用,所以先采用了LruCache,但他是3.1以后出现的
private static LinkedHashMap<String, SoftReference<Bitmap>> softreferences = new LinkedHashMap<String, SoftReference<Bitmap>>(
40, 0.75f, true);
public BitmapCache() {
initCache();
}
public static void initCache() {
if (mMemoryCache == null) {
// 获取系统分配给每个应用程序的最大内存,每个应用系统分配32M
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int mCacheSize = maxMemory / 8;
// 给LruCache分配1/8 4M
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize) {
// 必须重写此方法,来测量Bitmap的大小
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
// 当item被回收或者删掉时调用
@Override
protected void entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
Log.v("tag", "hard cache is full , push to soft cache");
// lurcache会有特定的算法,当我们的缓存到到峰值时,
// 就将缓存中最少使用的移除缓存,这里我们将缓存会移除的东西放入软引用中
softreferences
.put(key, new SoftReference<Bitmap>(oldValue));
}
};
}
}
/**
* 添加Bitmap到内存缓存
*
* @param key
* @param bitmap
*/
public static synchronized void addBitmapToMemoryCache(String key,
Bitmap bitmap) {
if (!TextUtils.isEmpty(key) && getBitmapFromMemCache(key) == null
&& bitmap != null) {
mMemoryCache.put(key, bitmap);
// 考虑到3.1一下版本不支持lurcache,就加入软应用
softreferences.put(key, new SoftReference<Bitmap>(bitmap));
}
}
/**
* 从内存缓存中获取一个Bitmap,避免并发加上synchronized
* @param key
* @return
*/
public static synchronized Bitmap getBitmapFromMemCache(String key) {
if(key==null)
{
return null;
}
if (mMemoryCache == null) {
initCache();
}
// 如果缓存中有,则返回
if (mMemoryCache.get(key) != null) {
return mMemoryCache.get(key);
}
SoftReference<Bitmap> bitmapReference = softreferences.get(key);
// 如果软应用中有,则返回
if (bitmapReference != null) {
final Bitmap bitmap2 = bitmapReference.get();
if (bitmap2 != null)
return bitmap2;
}
// 都没有返回null
return null;
}
/**
* 获取Bitmap, 内存或软应用中没有就去手机或者sd卡中获取,这一步在getView中会调用,比较关键的一步
* @param url
* @return
*/
// 从Cache和该应用的离线图片中查找并获取图片
public static Bitmap showCacheBitmap(String url) {
// 先从手机缓存或软应用中找,如果有就直接返回bitmap
if (getBitmapFromMemCache(url) != null) {
return getBitmapFromMemCache(url);
} else if (FileUtils.isFileExists(url)
&& FileUtils.getFileSize(url) != 0) {
// 从SD卡获取手机里面获取Bitmap
Bitmap bitmap = FileUtils.getBitmap(url);
// 将Bitmap 加入内存缓存
addBitmapToMemoryCache(url, bitmap);
return bitmap;
}
return null;
}
}
10.Constant.java:
package com.example.a15518.movies_connectdatabase.util;
/**
* Android端和数据后台统一字符串序列
* @author 15518
*
*/
public class Constant {
//查询内容为空或条件没有限制
public static String NO_MESSAGE = "No Message";
//按图片名称获取图片
public static String GET_IMAGE = "<#GET_IMAGE#>";
//获取电影列表
public static String GET_MOVIE_LIST="<#GET_MOVIE_LIST#>";
//获取视频列表
public static String GET_VIDEO_LIST="<#GET_VIDEO_LIST#>";
//按名称获取电影详情
public static String SEAECH_CERTAIN_MOVIE = "<#SEAECH_CERTAIN_MOVIE#>";
//登录验证
public static String LOGIN_VALID = "<#LOGIN_VALID#>";
//获取轮播图
public static String GET_SWIPERS = "<#GET_SWIPERS#>";
//获取主页口碑榜
public static String GET_RANKING1 = "<#GET_RANKING1#>";
//获取主页热映榜
public static String GET_RANKING2 = "<#GET_RANKING2#>";
//获取评论动态
public static String GET_EVALUATE = "<#GET_EVALUATE#>";
//插入评论动态
public static String INSERT_EVALUATE = "<#INSERT_EVALUATE#>";
}
11.FileUtils.java:
package com.example.a15518.movies_connectdatabase.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileUtils {
///sd卡的根目录
private static String mSdRootPath = Environment.getExternalStorageDirectory().getPath();
//手机的缓存根目录
private static String mDataRootPath = null;
//保存Image的目录名
private final static String FOLDER_NAME = "/AndroidImage";
public FileUtils(Context context) {
mDataRootPath = context.getCacheDir().getPath();
}
/**
* 获取储存Image的目录
* @return
*/
public static String getStorageDirectory() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED) ? mSdRootPath + FOLDER_NAME
: mDataRootPath + FOLDER_NAME;
}
/**
* 保存Image的方法,有sd卡存储到sd卡,没有就存储到手机目录
* @param fileName
* @param bitmap
* @throws IOException
*/
public static void savaBitmap(String fileName, Bitmap bitmap)
throws IOException {
if (bitmap == null) {
return;
}
String path = getStorageDirectory();
File folderFile = new File(path);
if (!folderFile.exists()) {
folderFile.mkdir();
}
File file = new File(path + File.separator + fileName);
file.createNewFile();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;// 个人喜欢从80开始,
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 200) {
baos.reset();
options -= 10;
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("savaBitmap");
}
//从手机或者sd卡获取Bitmap
public static Bitmap getBitmap(String fileName) {
return BitmapFactory.decodeFile(getStorageDirectory() + File.separator + fileName);
}
//判断文件是否存在
public static boolean isFileExists(String fileName) {
return new File(getStorageDirectory() + File.separator + fileName).exists();
}
//获取文件的大小
public static long getFileSize(String fileName) {
return new File(getStorageDirectory() + File.separator + fileName).length();
}
//获取assert文件
public static String loadFromSDFile(Context context, String fname)
{
String result=null;
try
{
InputStream in=context.getResources().getAssets().open(fname);
int ch=0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch=in.read())!=-1)
{
baos.write(ch);
}
byte[] buff=baos.toByteArray();
baos.close();
in.close();
result=new String(buff,"UTF-8");
result=result.replaceAll("\\r\\n","\n");
}
catch(Exception e)
{
}
return result.substring(1, result.length()-1);
}
}
12.IOUtil.java:
package com.example.a15518.movies_connectdatabase.util;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class IOUtil
{
//读取图片数据
public static byte[] readBytes(DataInputStream din)
{ byte[] data=null;
ByteArrayOutputStream out=new ByteArrayOutputStream(1024);
try
{ int length=0,temRev=0,size;
length=din.readInt();
byte[] buf=new byte[length-temRev];
while((size=din.read(buf))!=-1)
{ temRev+=size;
out.write(buf,0,size);
if(temRev>=length) { break; }
buf=new byte[length-temRev];
}
data=out.toByteArray();
}
catch(IOException e)
{ e.printStackTrace(); }
finally
{ try{ out.close(); }
catch(IOException e)
{ e.printStackTrace(); }
}
return data;
}
}
13.MyPort.java:
package com.example.a15518.movies_connectdatabase.util;
import android.app.Application;
/**
* 端口号
*/
public class MyPort extends Application {
public static String socketIp="10.210.254.225";
}
14.NetInfoUtil.java:
package com.example.a15518.movies_connectdatabase.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class NetInfoUtil {
public static String message = "";
// 缓冲:针对8888端口的输入输出数据流
// 创建处理界面加载任务的输入输出数据流
public static Socket cachess = null;
public static DataInputStream cachedin = null;
public static DataOutputStream cachedos = null;
static Lock cacheLock = new ReentrantLock();
// 通信建立(缓冲)
public static void cacheConnect() throws Exception {
cacheLock.lock();
cachess = new Socket();// 创建一个ServerSocket对象
SocketAddress socketAddress = new InetSocketAddress(
MyPort.socketIp, 8888); // 绑定到指定IP和端口
cachess.connect(socketAddress, 5000);// 设置连接超时时间
// 创建新数据输入流
cachedin = new DataInputStream(cachess.getInputStream());
// 创建新数据输出流
cachedos = new DataOutputStream(cachess.getOutputStream());
}
// 通信关闭(缓冲)
public static void cacheDisConnect() {
if (cachedos != null) {
try { cachedos.flush(); }
catch (Exception e) { e.printStackTrace(); }
}
if (cachedin != null) {
try { cachedin.close(); }
catch (Exception e) { e.printStackTrace(); }
}
if (cachess != null) {
try { cachess.close(); }
catch (Exception e) { e.printStackTrace(); }
}
cacheLock.unlock();
}
public static List<String[]> getMovieList() {// 获取电影列表
try {
cacheConnect(); //连接服务器
//向服务器发送参数值:Constant.GET_RECOMMEND_MENU
cachedos.writeUTF(Constant.GET_MOVIE_LIST);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的数据
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将电影由字符串转化为list并返回。
}
public static List<String[]> getVideoList() {// 获取视频列表
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_VIDEO_LIST);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的视频列表
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将视频由字符串转化为list并返回。
}
public static List<String[]> getEvaluateList() {// 获取评论列表
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_EVALUATE);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将评论由字符串转化为list并返回。
}
public static void insertEvaluate(String username, String detailevaluate) {// 插入评论
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.INSERT_EVALUATE+username+"#"+detailevaluate);
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
}
public static List<String[]> getSwipers() {// 获取轮播图
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_SWIPERS);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的轮播图
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将轮播图由字符串转化为list并返回。
}
public static List<String[]> getRanking1() {// 获取主页口碑榜
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_RANKING1);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的口碑榜
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将口碑榜列表由字符串转化为list并返回。
}
public static List<String[]> getRanking2() {// 获取主页热映榜
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_RANKING2);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的热映榜
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将热映榜列表由字符串转化为list并返回。
}
public static byte[] getCachePicture(String picName) {// 获取图片(按名称图片名)
byte[] data = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.GET_IMAGE + picName);
data = IOUtil.readBytes(cachedin);
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return data;
}
public static String getCRETAIN_MOVIE(String menuId) {// 按电影名获取电影详细信息
String message = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.SEAECH_CERTAIN_MOVIE + menuId);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
cacheDisConnect();
}
return message;
}
public static String getLogInfo(String usname) {// 按usname获取用户信息
String message = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.LOGIN_VALID + usname);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
cacheDisConnect();
}
return message;
}
}
15.StrListChange.java:
package com.example.a15518.movies_connectdatabase.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class NetInfoUtil {
public static String message = "";
// 缓冲:针对8888端口的输入输出数据流
// 创建处理界面加载任务的输入输出数据流
public static Socket cachess = null;
public static DataInputStream cachedin = null;
public static DataOutputStream cachedos = null;
static Lock cacheLock = new ReentrantLock();
// 通信建立(缓冲)
public static void cacheConnect() throws Exception {
cacheLock.lock();
cachess = new Socket();// 创建一个ServerSocket对象
SocketAddress socketAddress = new InetSocketAddress(
MyPort.socketIp, 8888); // 绑定到指定IP和端口
cachess.connect(socketAddress, 5000);// 设置连接超时时间
// 创建新数据输入流
cachedin = new DataInputStream(cachess.getInputStream());
// 创建新数据输出流
cachedos = new DataOutputStream(cachess.getOutputStream());
}
// 通信关闭(缓冲)
public static void cacheDisConnect() {
if (cachedos != null) {
try { cachedos.flush(); }
catch (Exception e) { e.printStackTrace(); }
}
if (cachedin != null) {
try { cachedin.close(); }
catch (Exception e) { e.printStackTrace(); }
}
if (cachess != null) {
try { cachess.close(); }
catch (Exception e) { e.printStackTrace(); }
}
cacheLock.unlock();
}
public static List<String[]> getMovieList() {// 获取电影列表
try {
cacheConnect(); //连接服务器
//向服务器发送参数值:Constant.GET_RECOMMEND_MENU
cachedos.writeUTF(Constant.GET_MOVIE_LIST);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的数据
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将电影由字符串转化为list并返回。
}
public static List<String[]> getVideoList() {// 获取视频列表
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_VIDEO_LIST);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的视频列表
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将视频由字符串转化为list并返回。
}
public static List<String[]> getEvaluateList() {// 获取评论列表
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_EVALUATE);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将评论由字符串转化为list并返回。
}
public static void insertEvaluate(String username, String detailevaluate) {// 插入评论
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.INSERT_EVALUATE+username+"#"+detailevaluate);
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
}
public static List<String[]> getSwipers() {// 获取轮播图
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_SWIPERS);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的轮播图
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将轮播图由字符串转化为list并返回。
}
public static List<String[]> getRanking1() {// 获取主页口碑榜
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_RANKING1);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的口碑榜
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将口碑榜列表由字符串转化为list并返回。
}
public static List<String[]> getRanking2() {// 获取主页热映榜
try {
cacheConnect(); //连接服务器
cachedos.writeUTF(Constant.GET_RANKING2);
message = cachedin.readUTF(); //从服务器返回从数据库中获取的热映榜
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return StrListChange.StrToList(message); //将热映榜列表由字符串转化为list并返回。
}
public static byte[] getCachePicture(String picName) {// 获取图片(按名称图片名)
byte[] data = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.GET_IMAGE + picName);
data = IOUtil.readBytes(cachedin);
} catch (Exception e) {
e.printStackTrace();
} finally {
cacheDisConnect();
}
return data;
}
public static String getCRETAIN_MOVIE(String menuId) {// 按电影名获取电影详细信息
String message = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.SEAECH_CERTAIN_MOVIE + menuId);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
cacheDisConnect();
}
return message;
}
public static String getLogInfo(String usname) {// 按usname获取用户信息
String message = null;
try {
cacheConnect();
cachedos.writeUTF(Constant.LOGIN_VALID + usname);
message = cachedin.readUTF();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
cacheDisConnect();
}
return message;
}
}
六、备注:需要源码私~
到了这里,关于电影APP项目(Android+Java+MySQL)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!