├── .idea
├── .name
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── vcs.xml
├── modules.xml
├── runConfigurations.xml
├── gradle.xml
├── compiler.xml
└── misc.xml
├── app
├── .gitignore
├── libs
│ ├── volley_lib.jar
│ ├── fastjson-1.1.43.jar
│ └── universal-image-loader-1.9.3.jar
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ ├── messi.png
│ │ │ │ ├── last_page_nor.png
│ │ │ │ ├── next_page_nor.png
│ │ │ │ ├── last_page_pressed.png
│ │ │ │ ├── next_page_pressed.png
│ │ │ │ ├── board_list_content_bg.9.png
│ │ │ │ ├── image_default.xml
│ │ │ │ ├── next_page_selector.xml
│ │ │ │ └── last_page_selector.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── styles.xml
│ │ │ │ └── dimens.xml
│ │ │ ├── values-w820dp
│ │ │ │ └── dimens.xml
│ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ └── layout
│ │ │ │ ├── test.xml
│ │ │ │ ├── activity_main.xml
│ │ │ │ ├── activity_hotel_list.xml
│ │ │ │ ├── list_footer_layout.xml
│ │ │ │ └── hotel_list_item_layout.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── itheima
│ │ │ │ └── datastorage
│ │ │ │ ├── util
│ │ │ │ ├── LogUtil.java
│ │ │ │ ├── ToastUtil.java
│ │ │ │ └── HotelSQLiteOpenHelper.java
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── model
│ │ │ │ └── Hotel.java
│ │ │ │ ├── ui
│ │ │ │ └── BaseViewHolder.java
│ │ │ │ ├── MainApplication.java
│ │ │ │ ├── hotel
│ │ │ │ ├── HotelListAdapter.java
│ │ │ │ └── HotelListActivity.java
│ │ │ │ └── net
│ │ │ │ └── DataCenter.java
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── itheima
│ │ │ └── datastorage
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── itheima
│ │ └── datastorage
│ │ ├── ApplicationTest.java
│ │ └── LrucacheTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── screenshot.gif
├── screenshot_1.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── README.md
├── gradle.properties
├── gradlew.bat
└── gradlew
/.idea/.name:
--------------------------------------------------------------------------------
1 | DataStorage
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/screenshot.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/screenshot.gif
--------------------------------------------------------------------------------
/screenshot_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/screenshot_1.png
--------------------------------------------------------------------------------
/app/libs/volley_lib.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/libs/volley_lib.jar
--------------------------------------------------------------------------------
/app/libs/fastjson-1.1.43.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/libs/fastjson-1.1.43.jar
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/messi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/messi.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/app/libs/universal-image-loader-1.9.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/libs/universal-image-loader-1.9.3.jar
--------------------------------------------------------------------------------
/app/src/main/res/drawable/last_page_nor.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/last_page_nor.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/next_page_nor.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/next_page_nor.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/last_page_pressed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/last_page_pressed.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/next_page_pressed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/next_page_pressed.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/board_list_content_bg.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jiyouliang/DataStorage/HEAD/app/src/main/res/drawable/board_list_content_bg.9.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DataStorage
3 | Settings
4 | HotelListActivity
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/image_default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Oct 21 11:34:03 PDT 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/next_page_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/last_page_selector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/util/LogUtil.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.util;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Created by youliang.ji on 2016/5/3.
7 | */
8 | public class LogUtil {
9 |
10 | private static final String TAG = "result";
11 |
12 | public static void d(String msg){
13 | Log.d(TAG, msg);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/util/ToastUtil.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.util;
2 |
3 | import android.content.Context;
4 | import android.widget.Toast;
5 |
6 | /**
7 | * Created by youliang.ji on 2016/5/4.
8 | */
9 | public class ToastUtil {
10 |
11 | public static void showToast(Context context, String msg){
12 | Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/test/java/com/itheima/datastorage/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/itheima/datastorage/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 三级存储:如何将网络json存储到内存,缓存到数据库(文件也是一样的道理)
2 |
3 | ### 1.JSON三级存储
4 |
5 | 你听过图片三级存储,但肯定没听过如何处理json三级存储
6 |
7 | ### 2.截图
8 |
9 | 
10 |
11 | ### 3.使用技术
12 |
13 | * 1.Lrucache处理内存存储
14 | * 2.Volley请求网络
15 | * 3.UniversalImageLoader加载图片
16 | * 4.Sqllite存储缓存处理
17 |
18 | ### 4.Usage
19 |
20 | 结合服务器使用
21 |
22 | * 1.服务器:[https://github.com/jiyouliang/VolleyTest](https://github.com/jiyouliang/VolleyTest "VolleyTest")部署到MyEclipse
23 | * 2.客户端:DataStorage
24 | * DataCenter类中改成你的ip,如下图
25 |
26 | 
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/test.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in E:\AndroidSdkOld/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | import com.itheima.datastorage.hotel.HotelListActivity;
9 |
10 | public class MainActivity extends Activity {
11 |
12 | @Override
13 | protected void onCreate(Bundle savedInstanceState) {
14 | super.onCreate(savedInstanceState);
15 | setContentView(R.layout.activity_main);
16 | }
17 |
18 | /**
19 | * 进入酒店列表页
20 | * @param v
21 | */
22 | public void hotelList(View v){
23 | Intent intent = new Intent(this, HotelListActivity.class);
24 | startActivity(intent);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_hotel_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 19
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | applicationId "com.itheima.datastorage"
9 | minSdkVersion 8
10 | targetSdkVersion 19
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | compile 'com.android.support:appcompat-v7:19.1.0'
25 | compile files('libs/fastjson-1.1.43.jar')
26 | compile files('libs/volley_lib.jar')
27 | compile files('libs/universal-image-loader-1.9.3.jar')
28 | }
29 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/util/HotelSQLiteOpenHelper.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.util;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.database.sqlite.SQLiteOpenHelper;
6 |
7 | /**
8 | * Created by youliang.ji on 2016/5/23.
9 | */
10 | public class HotelSQLiteOpenHelper extends SQLiteOpenHelper {
11 | public final static String HOTEL_TABLE = "hotel_list";
12 |
13 | public HotelSQLiteOpenHelper(Context context) {
14 | super(context, "heima.db", null, 1);
15 | }
16 |
17 | @Override
18 | public void onCreate(SQLiteDatabase db) {
19 | db.execSQL("CREATE TABLE "+HOTEL_TABLE+"(id INTEGER PRIMARY KEY AUTOINCREMENT,pagenum INTEGER,data VARCHAR(20),time VARCHAR(20))");
20 | }
21 |
22 | @Override
23 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
24 |
25 | }
26 |
27 | /**
28 | * 删除Least recently unused数据
29 | */
30 | public void deleteLruData(){
31 |
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/model/Hotel.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.model;
2 |
3 | import java.io.Serializable;
4 |
5 | /**酒店对象
6 | * Created by youliang.ji on 2016/5/1.
7 | */
8 | public class Hotel implements Serializable {
9 |
10 | private String price;//价格:价格为什么是字符串,很多公司所有返回json数据都是字符串,为了统一,当然如果你们公司返回double也没问题
11 | private String name;//酒店名称
12 | private String img;//酒店图片url
13 |
14 | public String getPrice() {
15 | return price;
16 | }
17 |
18 | public void setPrice(String price) {
19 | this.price = price;
20 | }
21 |
22 | public String getName() {
23 | return name;
24 | }
25 |
26 | public void setName(String name) {
27 | this.name = name;
28 | }
29 |
30 | public String getImg() {
31 | return img;
32 | }
33 |
34 | public void setImg(String img) {
35 | this.img = img;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return "Hotel{" +
41 | "price='" + price + '\'' +
42 | ", name='" + name + '\'' +
43 | ", img='" + img + '\'' +
44 | '}';
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/ui/BaseViewHolder.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.ui;
2 |
3 | import android.content.Context;
4 | import android.util.SparseArray;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 |
9 | /**
10 | * 通用ViewHolder,避免每个Adapter都需要写ViewHolder
11 | *
12 | * @author YouLiang.Ji
13 | */
14 | public class BaseViewHolder {
15 |
16 | private SparseArray mView;
17 | private int mPosition;
18 | private View mConvertView;
19 |
20 | public BaseViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
21 | mPosition = position;
22 | mView = new SparseArray();
23 | mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
24 | mConvertView.setTag(this);
25 | }
26 |
27 | public static BaseViewHolder getViewHolder(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
28 | if (convertView == null) {
29 | return new BaseViewHolder(context, parent, layoutId, position);
30 | } else {
31 | BaseViewHolder viewHolder = (BaseViewHolder) convertView.getTag();
32 | viewHolder.mPosition = position;
33 | return viewHolder;
34 | }
35 | }
36 |
37 | public View getConvertView() {
38 | return mConvertView;
39 | }
40 |
41 | /**
42 | * 通过id获取控件
43 | */
44 | public T findViewById(int viewId) {
45 | View view = mView.get(viewId);
46 | if (view == null) {
47 | view = mConvertView.findViewById(viewId);
48 | mView.put(viewId, view);
49 | }
50 | return (T) view;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
7 | import com.nostra13.universalimageloader.core.ImageLoader;
8 | import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
9 | import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
10 |
11 | /**
12 | * Created by youliang.ji on 2016/5/1.
13 | */
14 | public class MainApplication extends Application {
15 |
16 | @Override
17 | public void onCreate() {
18 | super.onCreate();
19 | initImageLoader(getApplicationContext());
20 | }
21 |
22 | /**
23 | * 初始化ImageLoader
24 | * @param context
25 | */
26 | public static void initImageLoader(Context context) {
27 | // This configuration tuning is custom. You can tune every option, you may tune some of them,
28 | // or you can create default configuration by
29 | // ImageLoaderConfiguration.createDefault(this);
30 | // method.
31 | ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
32 | config.threadPriority(Thread.NORM_PRIORITY - 2);
33 | config.denyCacheImageMultipleSizesInMemory();
34 | config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
35 | config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
36 | config.tasksProcessingOrder(QueueProcessingType.LIFO);
37 | config.writeDebugLogs(); // Remove for release app
38 |
39 | // Initialize ImageLoader with configuration.
40 | ImageLoader.getInstance().init(config.build());
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/list_footer_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 |
20 |
21 |
27 |
28 |
36 |
37 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/hotel_list_item_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
15 |
16 |
22 |
23 |
34 |
35 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/hotel/HotelListAdapter.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.hotel;
2 |
3 | import android.content.Context;
4 | import android.graphics.Color;
5 | import android.util.Log;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ArrayAdapter;
9 | import android.widget.ImageView;
10 | import android.widget.TextView;
11 |
12 | import com.itheima.datastorage.R;
13 | import com.itheima.datastorage.model.Hotel;
14 | import com.itheima.datastorage.ui.BaseViewHolder;
15 | import com.nostra13.universalimageloader.core.DisplayImageOptions;
16 | import com.nostra13.universalimageloader.core.ImageLoader;
17 | import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
18 | import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
19 |
20 | import java.util.List;
21 |
22 | /**酒店列表适配器
23 | * Created by youliang.ji on 2016/5/1.
24 | */
25 | public class HotelListAdapter extends ArrayAdapter{
26 |
27 | private DisplayImageOptions options;
28 |
29 | public HotelListAdapter(Context context, List data) {
30 | super(context, 0, data);
31 |
32 | setImageLoaderOptions();
33 | }
34 |
35 | private void setImageLoaderOptions() {
36 | options = new DisplayImageOptions.Builder()
37 | .showImageOnLoading(R.drawable.image_default)
38 | .showImageForEmptyUri(R.drawable.image_default)
39 | .showImageOnFail(R.drawable.image_default)
40 | .cacheInMemory(true)
41 | .cacheOnDisk(true)
42 | .considerExifParams(true)
43 | .displayer(new SimpleBitmapDisplayer())//default
44 | .build();
45 | }
46 |
47 | @Override
48 | public View getView(int position, View convertView, ViewGroup parent) {
49 | BaseViewHolder holder = BaseViewHolder.getViewHolder(getContext(), convertView, parent, R.layout.hotel_list_item_layout, position);
50 |
51 | Hotel hotel = getItem(position);
52 | ImageView mImageView = holder.findViewById(R.id.image);
53 | TextView mTvName = holder.findViewById(R.id.tv_name);
54 | TextView mTvPrice = holder.findViewById(R.id.tv_price);
55 | ImageLoader.getInstance().displayImage(hotel.getImg(), mImageView);
56 | mTvName.setText(hotel.getName());
57 | mTvPrice.setText("价格:"+hotel.getPrice());
58 |
59 | return holder.getConvertView();
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/itheima/datastorage/LrucacheTest.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage;
2 |
3 |
4 | import android.database.Cursor;
5 | import android.database.sqlite.SQLiteDatabase;
6 | import android.support.v4.util.LruCache;
7 |
8 | import com.itheima.datastorage.util.HotelSQLiteOpenHelper;
9 | import com.itheima.datastorage.util.LogUtil;
10 |
11 | import java.util.Map;
12 |
13 | /**
14 | * Created by youliang.ji on 2016/5/24.
15 | */
16 | public class LrucacheTest extends ApplicationTest {
17 |
18 | private LruCache lruCache;
19 |
20 | public void test(){
21 | if(lruCache == null){
22 | lruCache = new LruCache(9){
23 | @Override
24 | protected int sizeOf(String key, String value) {
25 | return value.getBytes().length;
26 | }
27 | };
28 | }
29 |
30 | lruCache.put("1", "AAA");
31 | lruCache.put("2", "BBB");
32 | print();
33 | lruCache.put("3", "CCC");
34 | print();
35 | lruCache.put("4", "DDD");
36 | print();
37 | String value = lruCache.get("2");
38 | LogUtil.d("key=2,value="+value);
39 | print();
40 | String value4 = lruCache.get("4");
41 | LogUtil.d("key=4,value=" + value4);
42 | print();
43 | lruCache.put("5","EEE");
44 | print();
45 |
46 |
47 | }
48 |
49 | private void print(){
50 | LogUtil.d("==========打印开始==========");
51 | for(Map.Entry entry : lruCache.snapshot().entrySet()){
52 | LogUtil.d("key="+entry.getKey()+",value="+entry.getValue());
53 | }
54 | LogUtil.d("==========打印结束==========");
55 | }
56 |
57 | public void test2(){
58 | String value1 = "1464054613534";
59 | String value2 = "1464054629950";
60 |
61 |
62 | }
63 |
64 | /**
65 | *测试数据库排序
66 | */
67 | public void test4(){
68 | HotelSQLiteOpenHelper sqLiteOpenHelper = new HotelSQLiteOpenHelper(getContext());
69 | SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
70 | if(db != null){
71 | Cursor cursor = db.query(HotelSQLiteOpenHelper.HOTEL_TABLE, new String[]{"pagenum"}, null, null, null, null, "time ASC");
72 | if(cursor != null){
73 | if (cursor.moveToFirst()){
74 | int pagenum = cursor.getInt(0);
75 | LogUtil.d("pagenum="+pagenum);
76 | }
77 | cursor.close();
78 | }
79 | db.close();
80 | }
81 |
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/hotel/HotelListActivity.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.hotel;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.DialogInterface;
6 | import android.os.Bundle;
7 | import android.view.View;
8 | import android.widget.ImageView;
9 | import android.widget.ListView;
10 | import android.widget.ProgressBar;
11 | import android.widget.TextView;
12 | import android.widget.Toast;
13 |
14 | import com.alibaba.fastjson.JSON;
15 | import com.android.volley.RequestQueue;
16 | import com.android.volley.Response;
17 | import com.android.volley.VolleyError;
18 | import com.android.volley.toolbox.Volley;
19 | import com.itheima.datastorage.R;
20 | import com.itheima.datastorage.model.Hotel;
21 | import com.itheima.datastorage.net.DataCenter;
22 | import com.itheima.datastorage.util.LogUtil;
23 |
24 | import java.util.ArrayList;
25 | import java.util.List;
26 |
27 | public class HotelListActivity extends Activity implements View.OnClickListener, Response.Listener, Response.ErrorListener {
28 |
29 | private ListView mListView;
30 | private List hotelList;
31 | private HotelListAdapter mAdapter;
32 | private int pagenum = 1;//当前页码
33 | private String reqFlag = this.getClass().getName();//标记volley请求,当页面finish时,通过标取消请求(volley和activity什么周期绑定)
34 | private RequestQueue queue;
35 | private View listFooterView;
36 | private ImageView mImageLastPage;//上一页
37 | private ImageView mImageNextPage;//下一页
38 | private TextView mTvCurPage;//当前页码
39 | private ProgressBar mProgressBar;
40 | private final static int PAGE_SIZE = 10;//每页10条数据
41 | private AlertDialog dialog;
42 |
43 |
44 | @Override
45 | protected void onCreate(Bundle savedInstanceState) {
46 | super.onCreate(savedInstanceState);
47 | setContentView(R.layout.activity_hotel_list);
48 |
49 | initView();
50 | initData();
51 | setListener();
52 | }
53 |
54 | private void setListener() {
55 | mImageLastPage.setOnClickListener(this);
56 | mImageNextPage.setOnClickListener(this);
57 | }
58 |
59 | private void initData() {
60 | queue = Volley.newRequestQueue(this);
61 | DataCenter.getInstance(this).getHotelList(reqFlag, queue, pagenum, this, this);
62 | }
63 |
64 | private void initView() {
65 | mListView = (ListView) findViewById(R.id.listView);
66 | mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
67 | listFooterView = View.inflate(this, R.layout.list_footer_layout, null);
68 | mTvCurPage = (TextView) listFooterView.findViewById(R.id.tv_cur_page);
69 | mImageLastPage = (ImageView) listFooterView.findViewById(R.id.iv_last_page);
70 | mImageNextPage = (ImageView) listFooterView.findViewById(R.id.iv_next_page);
71 | mTvCurPage.setText("第1页");
72 |
73 | hotelList = new ArrayList();
74 | mAdapter = new HotelListAdapter(this, hotelList);
75 | mListView.addFooterView(listFooterView);
76 | mListView.setAdapter(mAdapter);
77 |
78 | }
79 |
80 | @Override
81 | public void onClick(View v) {
82 | switch (v.getId()) {
83 | case R.id.iv_last_page://上一页
84 | pagenum--;
85 | showProgressBar();
86 | DataCenter.getInstance(this).getHotelList(reqFlag, queue, pagenum, this, this);
87 |
88 | break;
89 | case R.id.iv_next_page://下一页
90 | showProgressBar();
91 | pagenum++;
92 | DataCenter.getInstance(this).getHotelList(reqFlag, queue, pagenum, this, this);
93 | break;
94 | }
95 | }
96 |
97 |
98 | @Override
99 | public void onResponse(String result) {
100 | LogUtil.d(result);
101 |
102 | List hotels = JSON.parseArray(result, Hotel.class);
103 | if (hotels != null && hotels.size() > 0) {
104 | hotelList.clear();
105 | hotelList.addAll(hotels);
106 | mAdapter.notifyDataSetChanged();
107 | mTvCurPage.setText("第" + pagenum + "页");
108 | }
109 | hideProgressBar();
110 |
111 | if (pagenum == 1) {//第一页,不显示返回上一页按钮
112 | mImageLastPage.setVisibility(View.INVISIBLE);
113 | } else {
114 | mImageLastPage.setVisibility(View.VISIBLE);
115 | }
116 | if (hotelList.size() < PAGE_SIZE) {
117 | mImageNextPage.setVisibility(View.INVISIBLE);
118 | } else {
119 | mImageNextPage.setVisibility(View.VISIBLE);
120 | }
121 | }
122 |
123 | @Override
124 | public void onErrorResponse(VolleyError error) {
125 | hideProgressBar();
126 | LogUtil.d(error.getMessage());
127 | if (dialog == null) {
128 | dialog = new AlertDialog.Builder(this)
129 | .setTitle("网络异常!")
130 | .setMessage("请检查MyEclipse服务器是否开启,或访问地址是否正确。若未下载服务器代码,请下载:https://github.com/jiyouliang/VolleyTest")
131 | .setPositiveButton("确定", new DialogInterface.OnClickListener() {
132 | @Override
133 | public void onClick(DialogInterface dialog, int which) {
134 | dialog.dismiss();
135 | }
136 | })
137 | .create();
138 | }
139 | dialog.show();
140 | }
141 |
142 | private void showProgressBar() {
143 | mProgressBar.setVisibility(View.VISIBLE);
144 | }
145 |
146 | private void hideProgressBar() {
147 | mProgressBar.setVisibility(View.GONE);
148 | }
149 |
150 | @Override
151 | public void finish() {
152 | queue.cancelAll(reqFlag);//页面消失,取消发送
153 | LogUtil.d("退出页面,Volley已经和Activity声明周期联动");
154 | Toast.makeText(HotelListActivity.this, "退出酒店模块", Toast.LENGTH_SHORT).show();
155 | if (dialog != null && dialog.isShowing()) dialog.dismiss();
156 | DataCenter.getInstance(this).deleteAllData();
157 | super.finish();
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/app/src/main/java/com/itheima/datastorage/net/DataCenter.java:
--------------------------------------------------------------------------------
1 | package com.itheima.datastorage.net;
2 |
3 | import android.content.ContentValues;
4 | import android.content.Context;
5 | import android.database.Cursor;
6 | import android.database.sqlite.SQLiteDatabase;
7 | import android.os.Handler;
8 | import android.support.v4.util.LruCache;
9 | import android.text.TextUtils;
10 | import android.widget.Toast;
11 |
12 | import com.android.volley.RequestQueue;
13 | import com.android.volley.Response;
14 | import com.android.volley.toolbox.StringRequest;
15 | import com.itheima.datastorage.util.HotelSQLiteOpenHelper;
16 | import com.itheima.datastorage.util.LogUtil;
17 |
18 | import java.io.File;
19 | import java.util.Map;
20 |
21 | /**
22 | * 数据中心:获取数据,存储数据
23 | * Created by youliang.ji on 2016/5/23.
24 | */
25 | public class DataCenter {
26 |
27 | private static DataCenter instance;
28 | private Context context;
29 | private final static String url = "http://192.168.0.104:8080/VolleyTest/HotelList";
30 | private MemoryLrucache memoryCache;
31 | private HotelSQLiteOpenHelper sqLiteOpenHelper;
32 | private String cacheData;
33 | private MyHandler handler;
34 | /**内存最大存储*/
35 | private final static int MAX_SIZE_MEMORY = 3 * 1024;//3KB,正式开发肯定没这么小,这里为了测试
36 | /**缓存最大存储*/
37 | private final static int MAX_SIZE_CACHE = 30 * 1024;//30KB,正式开发肯定没这么小,这里为了测试
38 |
39 | private DataCenter() {
40 | }
41 |
42 | public static DataCenter getInstance(Context context) {
43 | if (instance == null) {
44 | synchronized (DataCenter.class) {
45 | instance = new DataCenter();
46 | instance.context = context;
47 | }
48 | }
49 | return instance;
50 | }
51 |
52 | /**
53 | * 获取酒店列表数据
54 | *
55 | * @param reqFlag 请求标识
56 | * @param queue 请求队列
57 | * @param pagenum 页码
58 | * @param listener 成功回调
59 | * @param errListener 错误回调
60 | */
61 | public void getHotelList(final String reqFlag, RequestQueue queue, final int pagenum,
62 | final Response.Listener listener, Response.ErrorListener errListener) {
63 | if (exitInMemory(pagenum)) {
64 | listener.onResponse(getFromMemory(pagenum));
65 | return;
66 | } else if(exitInCache(pagenum)){
67 | showToast("从缓存中获取第"+pagenum+"页数据");
68 | LogUtil.d("缓冲中存在第页"+pagenum+"数据:"+cacheData);
69 | listener.onResponse(cacheData);
70 | return;
71 | }else {
72 | getFromInternet(reqFlag, queue, pagenum, listener, errListener);
73 | }
74 | }
75 |
76 | /**
77 | * 从网络获取数据
78 | *
79 | * @param reqFlag
80 | * @param queue
81 | * @param pagenum
82 | * @param listener
83 | * @param errListener
84 | */
85 | private void getFromInternet(String reqFlag, RequestQueue queue, final int pagenum, final Response.Listener listener, Response.ErrorListener errListener) {
86 | StringRequest request = new StringRequest(url + "?pagenum=" + pagenum, new Response.Listener() {
87 | @Override
88 | public void onResponse(String response) {
89 | LogUtil.d("从网络获取第"+pagenum+"页数据");
90 | showToast("从网络获取第" + pagenum+"页数据");
91 | //存储到内存中
92 | storeToMemory(pagenum, response);
93 | storeToCache(pagenum, response);
94 | listener.onResponse(response);
95 | }
96 | }, errListener);
97 | request.setTag(reqFlag);
98 | queue.add(request);//发起网络请求
99 | }
100 |
101 | /**
102 | * 数据存储到内存中
103 | *
104 | * @param data
105 | */
106 | private void storeToMemory(int pagenum, String data) {
107 | if (memoryCache == null) {
108 | memoryCache = new MemoryLrucache();
109 | }
110 | LogUtil.d("将第" + pagenum + "页数据存储到内存");
111 | memoryCache.put(pagenum + "", data);
112 | printMemoryData();
113 | }
114 |
115 | private String getFromMemory(int pagenum) {
116 | String data = memoryCache.get(pagenum + "");
117 | LogUtil.d("从内存获取第" + pagenum + "页数据:" + data);
118 | showToast("从内存获取第" + pagenum + "页数据");
119 | printMemoryData();
120 | return data;
121 | }
122 |
123 | private boolean exitInMemory(int pagenum) {
124 | if (memoryCache == null) {
125 | LogUtil.d("内存中不存在第" + pagenum + "页数据");
126 | return false;
127 | }
128 | String data = memoryCache.get(pagenum + "");
129 | boolean exit = !TextUtils.isEmpty(data);
130 | if (exit) {
131 | LogUtil.d("内存中存在第" + pagenum + "页数据");
132 | } else {
133 | LogUtil.d("内存中不存在第" + pagenum + "页数据");
134 | }
135 | return exit;
136 | }
137 |
138 | class MemoryLrucache extends LruCache {
139 |
140 |
141 | public MemoryLrucache() {
142 | super(MAX_SIZE_MEMORY);
143 | }
144 |
145 | @Override
146 | protected int sizeOf(String key, String value) {
147 | return value.getBytes().length;
148 | }
149 | }
150 |
151 | /**
152 | * 打印内存中的数据
153 | */
154 | private void printMemoryData() {
155 | Map snapshot = memoryCache.snapshot();
156 | LogUtil.d("打印内存中的数据 start");
157 | for (Map.Entry entry : snapshot.entrySet()) {
158 | LogUtil.d("key=" + entry.getKey() + ",value=" + entry.getValue());
159 | }
160 | LogUtil.d("打印内存中的数据 end");
161 | }
162 |
163 | /**
164 | * 存储到缓冲中
165 | *
166 | * @param pagenum
167 | * @param data
168 | */
169 | private void storeToCache(int pagenum, String data) {
170 | if (sqLiteOpenHelper == null) {
171 | sqLiteOpenHelper = new HotelSQLiteOpenHelper(context);
172 | }
173 |
174 | SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
175 | ContentValues contentValues = new ContentValues();
176 | contentValues.put("pagenum", pagenum);
177 | contentValues.put("data", data);
178 | contentValues.put("time", System.currentTimeMillis() + "");
179 | db.insert(HotelSQLiteOpenHelper.HOTEL_TABLE, null, contentValues);
180 |
181 | LogUtil.d("将第" + pagenum + "页数据存储到缓存中");
182 | db.close();
183 |
184 | while (!canCache()){//如果没有足够空间缓冲,先删除数据,指导空间足够
185 | LogUtil.d("没有足够空间存储数据");
186 | deleteLruCache();
187 | }
188 | }
189 |
190 | private boolean exitInCache(int pagenum) {
191 | if (sqLiteOpenHelper == null) {
192 | sqLiteOpenHelper = new HotelSQLiteOpenHelper(context);
193 | }
194 | SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();
195 | boolean exitInCache = false;
196 | Cursor cursor = db.query(HotelSQLiteOpenHelper.HOTEL_TABLE, new String[]{"data"}, "pagenum=?", new String[]{pagenum + ""}, null, null, null);
197 | if(cursor != null){
198 | if(cursor.moveToFirst()){
199 | cacheData = cursor.getString(0);
200 | if(!TextUtils.isEmpty(cacheData)){
201 | exitInCache = true;
202 | storeToMemory(pagenum, cacheData);
203 | }
204 | }
205 | cursor.close();
206 | }
207 | db.close();
208 | if(!exitInCache) {
209 | LogUtil.d("缓冲中不存在第页"+pagenum+"数据");
210 | }
211 | return exitInCache;
212 | }
213 |
214 | private void showToast(final String msg){
215 | if(handler == null){
216 | handler = new MyHandler();
217 | }
218 | handler.post(new Runnable() {
219 | @Override
220 | public void run() {
221 | Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
222 | }
223 | });
224 |
225 | }
226 |
227 | public void deleteAllData(){
228 |
229 | new Thread(){
230 | @Override
231 | public void run() {
232 | deleteMemoryCache();
233 | deleteCache();
234 | super.run();
235 | }
236 | }.start();
237 | }
238 |
239 | /**
240 | * 删除内存中数据
241 | */
242 | private void deleteMemoryCache(){
243 | LogUtil.d("删除内存中的数据");
244 | showToast("删除内存数据");
245 | memoryCache = null;
246 | }
247 |
248 | /**
249 | * 删除最近最少使用的数据
250 | */
251 | private void deleteLruCache(){
252 | int pagenum = getDeleteCacheIndex();
253 | LogUtil.d("需要删除第"+pagenum+"页数据");
254 | if(pagenum > 0){
255 | SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
256 | if(db != null){
257 | int index = db.delete(HotelSQLiteOpenHelper.HOTEL_TABLE, "pagenum=?", new String[]{pagenum + ""});
258 | LogUtil.d("删除,index="+index);
259 | db.close();
260 | }
261 | }
262 | }
263 |
264 | /**
265 | * 获取需要删除的页码
266 | * @return
267 | */
268 | private int getDeleteCacheIndex(){
269 | int pagenum = -1;
270 | SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
271 | if(db != null){
272 | Cursor cursor = db.query(HotelSQLiteOpenHelper.HOTEL_TABLE, new String[]{"pagenum"}, null, null, null, null, "time ASC");
273 | if(cursor != null){
274 | if (cursor.moveToFirst()){
275 | pagenum = cursor.getInt(0);
276 | LogUtil.d("需要删除页码pagenum="+pagenum);
277 | }
278 | cursor.close();
279 | }
280 | db.close();
281 | }
282 | return pagenum;
283 | }
284 |
285 |
286 | /**
287 | * 是否还有空间存储到数据库
288 | * @return
289 | */
290 | private boolean canCache(){
291 | long size = getCacheSize();
292 | return (size <= MAX_SIZE_CACHE);
293 | }
294 |
295 | /**
296 | * 获取缓存数据库大小
297 | * @return
298 | */
299 | private long getCacheSize(){
300 | SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();
301 | String path = db.getPath();
302 | File file = null;
303 | if(path != null){
304 | file = new File(path);
305 | }
306 | db.close();
307 | LogUtil.d("获取数据库文件大小:"+file.length());
308 | return file.length();//byte
309 | }
310 |
311 | /**
312 | * 删除缓冲数据
313 | */
314 | private void deleteCache(){
315 | if (sqLiteOpenHelper == null) {
316 | sqLiteOpenHelper = new HotelSQLiteOpenHelper(context);
317 | }
318 | SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
319 | if(db != null){
320 | int delete = db.delete(HotelSQLiteOpenHelper.HOTEL_TABLE, null, null);
321 | LogUtil.d("删除缓冲中的数据:"+delete);
322 | db.close();
323 | }
324 | cacheData = null;
325 | showToast("删除缓存数据");
326 | }
327 |
328 | class MyHandler extends Handler{}
329 | }
330 |
--------------------------------------------------------------------------------