├── app
├── .gitignore
├── src
│ └── main
│ │ ├── web_hi_res_512.png
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ ├── ic_done.png
│ │ │ ├── ic_empty.png
│ │ │ └── ic_icons8_book_24.png
│ │ ├── drawable-mdpi
│ │ │ ├── ic_done.png
│ │ │ ├── ic_empty.png
│ │ │ └── ic_icons8_book_24.png
│ │ ├── drawable-xhdpi
│ │ │ ├── ic_done.png
│ │ │ ├── ic_empty.png
│ │ │ └── ic_icons8_book_24.png
│ │ ├── drawable-xxhdpi
│ │ │ ├── ic_done.png
│ │ │ ├── ic_empty.png
│ │ │ └── ic_icons8_book_24.png
│ │ ├── drawable-xxxhdpi
│ │ │ ├── ic_done.png
│ │ │ ├── ic_empty.png
│ │ │ └── ic_icons8_book_24.png
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── values
│ │ │ ├── integer.xml
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── menu
│ │ │ ├── menu_editor.xml
│ │ │ └── menu_catalog.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout
│ │ │ ├── activity_catalog.xml
│ │ │ ├── list_item.xml
│ │ │ └── activity_editor.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── botsone
│ │ └── android
│ │ └── bookstore
│ │ ├── data
│ │ ├── BookDbHelper.java
│ │ ├── BookContract.java
│ │ └── BookProvider.java
│ │ ├── BookCursorAdapter.java
│ │ ├── CatalogActivity.java
│ │ └── EditorActivity.java
├── build.gradle
└── proguard-rules.pro
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── caches
│ └── build_file_checksums.ser
├── vcs.xml
├── runConfigurations.xml
├── gradle.xml
├── misc.xml
└── codeStyles
│ └── Project.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/app/src/main/web_hi_res_512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/web_hi_res_512.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.idea/caches/build_file_checksums.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/.idea/caches/build_file_checksums.ser
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-hdpi/ic_done.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-hdpi/ic_empty.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-mdpi/ic_done.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-mdpi/ic_empty.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xhdpi/ic_done.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xhdpi/ic_empty.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxhdpi/ic_done.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxhdpi/ic_empty.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxxhdpi/ic_done.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxxhdpi/ic_empty.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-hdpi/ic_icons8_book_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-hdpi/ic_icons8_book_24.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-mdpi/ic_icons8_book_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-mdpi/ic_icons8_book_24.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xhdpi/ic_icons8_book_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xhdpi/ic_icons8_book_24.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxhdpi/ic_icons8_book_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxhdpi/ic_icons8_book_24.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable-xxxhdpi/ic_icons8_book_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bots/BookStore-app/master/app/src/main/res/drawable-xxxhdpi/ic_icons8_book_24.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/libraries
5 | /.idea/modules.xml
6 | /.idea/workspace.xml
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/integer.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 1
4 | 2
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Apr 23 17:19:58 MDT 2018
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-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 |
5 |
6 | 16dp
7 |
8 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 | defaultConfig {
6 | applicationId "com.botsone.android.bookstore"
7 | minSdkVersion 15
8 | targetSdkVersion 27
9 | versionCode 1
10 | versionName "1.0"
11 | }
12 | buildTypes {
13 | release {
14 | minifyEnabled false
15 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
16 | }
17 | }
18 | }
19 |
20 | dependencies {
21 | implementation 'com.android.support:appcompat-v7:27.1.1'
22 | implementation 'com.android.support:design:27.1.1'
23 | implementation 'com.squareup.picasso:picasso:2.71828'
24 | implementation 'com.android.support:exifinterface:27.1.1'
25 | }
26 |
--------------------------------------------------------------------------------
/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 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
15 | #F0514B
16 |
17 |
18 | #C0403C
19 |
20 |
21 | #F0514B
22 |
23 |
24 | #2D3640
25 |
26 |
27 | #394450
28 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_editor.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_catalog.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
24 |
25 |
28 |
29 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.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 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/data/BookDbHelper.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore.data;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.database.sqlite.SQLiteOpenHelper;
6 |
7 | import com.botsone.android.bookstore.data.BookContract.BookEntry;
8 |
9 | public class BookDbHelper extends SQLiteOpenHelper {
10 |
11 | /**
12 | * name of the database file
13 | */
14 | private static final String DATABASE_NAME = "bookstore.db";
15 |
16 | /**
17 | * Database version, if you change schema, increment this
18 | */
19 | private static final int DATABASE_VERSION = 3;
20 |
21 | public BookDbHelper(Context context) {
22 | super(context, DATABASE_NAME, null, DATABASE_VERSION);
23 | }
24 |
25 | @Override
26 | public void onCreate(SQLiteDatabase db) {
27 | // CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, picture BLOB...
28 | String SQL_CREATE_BOOKS_TABLE = "CREATE TABLE " + BookEntry.TABLE_NAME + "("
29 | + BookEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
30 | + BookEntry.COLUMN_BOOK_PICTURE + " TEXT NOT NULL, "
31 | + BookEntry.COLUMN_BOOK_NAME + " TEXT NOT NULL, "
32 | + BookEntry.COLUMN_BOOK_SECTION + " TEXT NOT NULL, "
33 | + BookEntry.COLUMN_BOOK_AUTHOR + " TEXT, "
34 | + BookEntry.COLUMN_BOOK_PUBLISHER + " TEXT, "
35 | + BookEntry.COLUMN_BOOK_PRICE + " INTEGER NOT NULL, "
36 | + BookEntry.COLUMN_BOOK_QUANTITY + " INTEGER NOT NULL DEFAULT 0, "
37 | + BookEntry.COLUMN_BOOK_SUPPLIER + " TEXT, "
38 | + BookEntry.COLUMN_BOOK_SUPPLIER_PHONE + " TEXT);";
39 |
40 | db.execSQL(SQL_CREATE_BOOKS_TABLE);
41 | }
42 |
43 | @Override
44 | public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/data/BookContract.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore.data;
2 |
3 | import android.content.ContentResolver;
4 | import android.net.Uri;
5 | import android.provider.BaseColumns;
6 |
7 | public final class BookContract {
8 |
9 | private BookContract() {
10 |
11 | }
12 |
13 | public static final String CONTENT_AUTHORITY = "com.botsone.android.bookstore";
14 |
15 | public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
16 |
17 | public static final String PATH_BOOKS = "books";
18 |
19 | public static final class BookEntry implements BaseColumns {
20 |
21 | public static final String TABLE_NAME = "books";
22 |
23 | public static final String COLUMN_BOOK_PICTURE = "picture";
24 | public static final String COLUMN_BOOK_NAME = "name";
25 | public static final String COLUMN_BOOK_SECTION = "section";
26 | public static final String COLUMN_BOOK_AUTHOR = "author";
27 | public static final String COLUMN_BOOK_PUBLISHER = "publisher";
28 | public static final String COLUMN_BOOK_PRICE = "price";
29 | public static final String COLUMN_BOOK_QUANTITY = "quantity";
30 | public static final String COLUMN_BOOK_SUPPLIER = "supplier";
31 | public static final String COLUMN_BOOK_SUPPLIER_PHONE = "phone";
32 |
33 | public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_BOOKS);
34 |
35 | /**
36 | * The MIME type of the {@link #CONTENT_URI} for a list of books.
37 | */
38 | public static final String CONTENT_LIST_TYPE =
39 | ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_BOOKS;
40 |
41 | /**
42 | * The MIME type of the {@link #CONTENT_URI} for a single book.
43 | */
44 | public static final String CONTENT_ITEM_TYPE =
45 | ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_BOOKS;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/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 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
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 Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
15 |
20 |
21 |
22 |
27 |
28 |
29 |
38 |
39 |
40 |
46 |
47 |
48 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_catalog.xml:
--------------------------------------------------------------------------------
1 |
12 |
17 |
18 |
22 |
23 |
24 |
29 |
30 |
36 |
37 |
47 |
48 |
59 |
60 |
61 |
62 |
70 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
25 |
26 |
32 |
33 |
41 |
42 |
48 |
49 |
50 |
51 |
55 |
56 |
64 |
65 |
71 |
72 |
73 |
74 |
79 |
80 |
88 |
89 |
95 |
96 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/BookCursorAdapter.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore;
2 |
3 | import android.content.ContentResolver;
4 | import android.content.ContentUris;
5 | import android.content.ContentValues;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.content.res.Resources;
9 | import android.database.Cursor;
10 | import android.net.Uri;
11 | import android.support.v7.widget.RecyclerView;
12 | import android.util.Log;
13 | import android.view.LayoutInflater;
14 | import android.view.View;
15 | import android.view.ViewGroup;
16 | import android.widget.Button;
17 | import android.widget.CursorAdapter;
18 | import android.widget.ImageView;
19 | import android.widget.TextView;
20 | import android.widget.Toast;
21 |
22 | import com.botsone.android.bookstore.data.BookContract.BookEntry;
23 | import com.squareup.picasso.Picasso;
24 |
25 | import java.util.zip.Inflater;
26 |
27 | import static com.botsone.android.bookstore.data.BookContract.BookEntry.CONTENT_URI;
28 |
29 | /**
30 | * {@link BookCursorAdapter} is an adapter for a list or grid view
31 | * that uses a {@link Cursor} of book data as its data source. This adapter knows
32 | * how to create list items for each row of book data in the {@link Cursor}.
33 | */
34 | public class BookCursorAdapter extends CursorAdapter {
35 |
36 | private int bookQuantity;
37 | private Context context;
38 | private LayoutInflater inflater;
39 |
40 | /**
41 | * Constructs a new {@link BookCursorAdapter}.
42 | *
43 | * @param context The context
44 | * @param c The cursor from which to get the data.
45 | */
46 | public BookCursorAdapter(Context context, Cursor c) {
47 | super(context, c, 0 /* flags */);
48 | this.context = context;
49 |
50 | }
51 |
52 | /**
53 | * Makes a new blank list item view. No data is set (or bound) to the views yet.
54 | *
55 | * @param context app context
56 | * @param cursor The cursor from which to get the data. The cursor is already
57 | * moved to the correct position.
58 | * @param parent The parent to which the new view is attached to
59 | * @return the newly created list item view.
60 | */
61 | @Override
62 | public View newView(Context context, Cursor cursor, ViewGroup parent) {
63 | return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
64 | }
65 |
66 | /**
67 | * This method binds the book data (in the current row pointed to by cursor) to the given
68 | * list item layout. For example, the name for the current book can be set on the name TextView
69 | * in the list item layout.
70 | *
71 | * @param view Existing view, returned earlier by newView() method
72 | * @param context app context
73 | * @param cursor The cursor from which to get the data. The cursor is already moved to the
74 | * correct row.
75 | */
76 | @Override
77 | public void bindView(View view, final Context context, final Cursor cursor) {
78 |
79 |
80 | // Find the views that we want to modify in the list item layout
81 | TextView nameTextView = (TextView) view.findViewById(R.id.name);
82 | TextView priceTextView = (TextView) view.findViewById(R.id.price);
83 | TextView quantityTextView = (TextView) view.findViewById(R.id.quantity);
84 | Button button = (Button) view.findViewById(R.id.sale_button);
85 | ImageView imageView = (ImageView) view.findViewById(R.id.list_item_image_view);
86 |
87 | nameTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_BOOK_NAME)));
88 | priceTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_BOOK_PRICE)));
89 | quantityTextView.setText(cursor.getString(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_BOOK_QUANTITY)));
90 |
91 | /* Get values from db */
92 | final int currentQuantity = cursor.getInt(cursor.getColumnIndexOrThrow(BookEntry.COLUMN_BOOK_QUANTITY));
93 | String currentId = cursor.getString(cursor.getColumnIndexOrThrow(BookEntry._ID));
94 | final Uri currentUri = ContentUris.withAppendedId(BookEntry.CONTENT_URI, Long.parseLong(currentId));
95 |
96 | int pictureColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_PICTURE);
97 | int nameColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_NAME);
98 | int priceColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_PRICE);
99 | int quantityColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_QUANTITY);
100 | String bookPicture = cursor.getString(pictureColumnIndex);
101 | String bookName = cursor.getString(nameColumnIndex);
102 | Double bookPrice = cursor.getDouble(priceColumnIndex);
103 | bookQuantity = cursor.getInt(quantityColumnIndex);
104 | Uri bookPictureUri = Uri.parse(bookPicture);
105 |
106 | button.setOnClickListener(new View.OnClickListener() {
107 | @Override
108 | public void onClick(View v) {
109 | ContentValues values = new ContentValues();
110 |
111 | if (currentQuantity == 0) {
112 | Toast.makeText(context, R.string.sale_button_zero, Toast.LENGTH_SHORT).show();
113 | } else {
114 | values.put(BookEntry.COLUMN_BOOK_QUANTITY, currentQuantity - 1);
115 | context.getContentResolver().update(currentUri, values, null, null);
116 | }
117 | }
118 | });
119 |
120 | if (bookPicture != null) {
121 | Picasso.get().load(bookPictureUri).into(imageView);
122 | } else {
123 | Picasso.get().load(R.drawable.ic_empty).into(imageView);
124 | }
125 | nameTextView.setText(bookName);
126 | priceTextView.setText("$" + bookPrice.toString());
127 | quantityTextView.setText(Integer.toString(bookQuantity));
128 |
129 | }
130 |
131 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
15 | BookStore
16 |
17 |
18 | Insert Dummy Data
19 |
20 |
21 | Delete All Books
22 |
23 |
24 | Add a Book
25 |
26 |
27 | Edit Book
28 |
29 |
30 | Save
31 |
32 |
33 | Delete
34 |
35 |
36 | Book Name *
37 |
38 |
39 | Section
40 |
41 |
42 | Author
43 |
44 |
45 | Publisher
46 |
47 |
48 | Price *
49 |
50 |
51 | Quantity *
52 |
53 |
54 | Supplier
55 |
56 |
57 | Supplier Phone
58 |
59 |
60 | Book Name
61 |
62 |
63 | Bookstore Section
64 |
65 |
66 | Author
67 |
68 |
69 | Book Publisher
70 |
71 |
72 | Price
73 |
74 |
75 | Quantity in Stock
76 |
77 |
78 | Book Supplier
79 |
80 |
81 | Book Supplier Phone Number
82 |
83 |
84 | Book saved
85 |
86 |
87 | Error with saving book
88 |
89 |
90 | Book updated
91 |
92 |
93 | Error updating book
94 |
95 |
96 | Name, Price, and Quantity are required fields.
97 |
98 |
99 | * Denotes a required field
100 |
101 |
102 | Book deleted
103 |
104 |
105 | Error deleting book
106 |
107 |
108 | Delete this book?
109 |
110 |
111 | Delete
112 |
113 |
114 | Cancel
115 |
116 |
117 | Discard your changes and quit editing?
118 |
119 |
120 | Discard
121 |
122 | There is no dialer app installed.
123 |
124 | No more stock!
125 |
126 | Sale
127 |
128 |
129 | Keep Editing
130 |
131 |
132 | Book Name:
133 |
134 |
135 | Price:
136 |
137 |
138 | Quantity:
139 |
140 |
141 | Sale
142 |
143 |
144 | Image of current book
145 |
146 |
147 | It\'s a bit lonely here...
148 |
149 |
150 | Get started by adding a book
151 |
152 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/CatalogActivity.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore;
2 |
3 | import android.app.LoaderManager;
4 | import android.content.ContentResolver;
5 | import android.content.ContentUris;
6 | import android.content.ContentValues;
7 | import android.content.CursorLoader;
8 | import android.content.Intent;
9 | import android.content.Loader;
10 | import android.database.Cursor;
11 | import android.graphics.Bitmap;
12 | import android.graphics.BitmapFactory;
13 | import android.graphics.drawable.Drawable;
14 | import android.net.Uri;
15 | import android.os.Build;
16 | import android.os.Bundle;
17 | import android.service.carrier.CarrierMessagingService;
18 | import android.support.design.widget.FloatingActionButton;
19 | import android.support.v7.app.AppCompatActivity;
20 | import android.util.Log;
21 | import android.view.View;
22 | import android.view.Menu;
23 | import android.view.MenuItem;
24 | import android.widget.AdapterView;
25 | import android.widget.Button;
26 | import android.widget.ImageView;
27 | import android.widget.ListView;
28 | import android.widget.TextView;
29 |
30 | import com.botsone.android.bookstore.data.BookContract.BookEntry;
31 | import com.squareup.picasso.Picasso;
32 |
33 | import java.util.List;
34 |
35 | /**
36 | * Displays list of books that were entered and stored in the app.
37 | */
38 | public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {
39 |
40 | private static final String LOG_TAG = CatalogActivity.class.getSimpleName();
41 |
42 | private static final int BOOK_LOADER = 0;
43 |
44 | BookCursorAdapter mCursorAdapter;
45 |
46 | ImageView imageView;
47 |
48 | @Override
49 | protected void onCreate(Bundle savedInstanceState) {
50 | super.onCreate(savedInstanceState);
51 | setContentView(R.layout.activity_catalog);
52 |
53 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
54 | fab.setOnClickListener(new View.OnClickListener() {
55 | @Override
56 | public void onClick(View view) {
57 | Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
58 | startActivity(intent);
59 | }
60 | });
61 |
62 | // Find the listView which will be populated with book data
63 | ListView bookListView = (ListView) findViewById(R.id.list);
64 |
65 | // Find and set empty view on listview when there are 0 books
66 | View emptyView = findViewById(R.id.empty_view);
67 | bookListView.setEmptyView(emptyView);
68 |
69 | imageView = (ImageView) findViewById(R.id.list_item_image_view);
70 |
71 | // Set up and adapter to create a list item for each row of book data in the cursor
72 | // There is no book data yet (until the loader finishes) so pass null for the cursor
73 | mCursorAdapter = new BookCursorAdapter(this, null);
74 | bookListView.setAdapter(mCursorAdapter);
75 |
76 | // Set up the item click listener for each cell in the listview
77 | bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
78 | @Override
79 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
80 | // Create new intent to go to editorActivity
81 | Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
82 |
83 | // Form the content uri that represents the specific book that was clicked on
84 | // by appending the "id" (passed as an input to this method) onto the contentUri
85 | Uri currentBookUri = ContentUris.withAppendedId(BookEntry.CONTENT_URI, id);
86 |
87 | // Set the URI on the data field of the intent
88 | intent.setData(currentBookUri);
89 |
90 | startActivity(intent);
91 |
92 | }
93 | });
94 |
95 | // Kick off the loader
96 | getLoaderManager().initLoader(BOOK_LOADER, null, this);
97 | }
98 |
99 | @Override
100 | protected void onStart() {
101 | super.onStart();
102 | }
103 |
104 | private void insertBook() {
105 |
106 | // Create a contentValues object where column names are the keys,
107 | // and Star Wars attributes are the values
108 | ContentValues values = new ContentValues();
109 |
110 | Uri uri = Uri.parse("android.resource://com.botsone.android.bookstore/drawable/ic_empty");
111 |
112 | values.put(BookEntry.COLUMN_BOOK_PICTURE, uri.toString());
113 | values.put(BookEntry.COLUMN_BOOK_NAME, "Star Wars");
114 | values.put(BookEntry.COLUMN_BOOK_SECTION, "Sci-fi");
115 | values.put(BookEntry.COLUMN_BOOK_AUTHOR, "George Danson");
116 | values.put(BookEntry.COLUMN_BOOK_PUBLISHER, "Penguin Books Inc.");
117 | values.put(BookEntry.COLUMN_BOOK_PRICE, 6.99);
118 | values.put(BookEntry.COLUMN_BOOK_QUANTITY, 10);
119 | values.put(BookEntry.COLUMN_BOOK_SUPPLIER, "FakeSupplier Co.");
120 | values.put(BookEntry.COLUMN_BOOK_SUPPLIER_PHONE, "5438943221");
121 |
122 | Uri newUri = getContentResolver().insert(BookEntry.CONTENT_URI, values);
123 | }
124 |
125 | /**
126 | * Helper to delete all books from the db for testing purposes
127 | */
128 | private void deleteAllBooks() {
129 | int rowsDeleted = getContentResolver().delete(BookEntry.CONTENT_URI,
130 | null,
131 | null);
132 | Log.v("CatalogActivity", rowsDeleted + " rows deleted from book database");
133 |
134 | }
135 |
136 | @Override
137 | public boolean onCreateOptionsMenu(Menu menu) {
138 | // Inflate the menu; this adds items to the action bar if it is present.
139 | getMenuInflater().inflate(R.menu.menu_catalog, menu);
140 | return true;
141 | }
142 |
143 | @Override
144 | public boolean onOptionsItemSelected(MenuItem item) {
145 | // User clicked on a menu option in the app bar overflow menu
146 | switch (item.getItemId()) {
147 | // Respond to a click on the "Insert dummy data" menu option
148 | case R.id.action_insert_dummy_data:
149 |
150 | insertBook();
151 | return true;
152 | // Respond to a click on the "Delete all entries" menu option
153 | case R.id.action_delete_all_entries:
154 | deleteAllBooks();
155 | return true;
156 | }
157 | return super.onOptionsItemSelected(item);
158 | }
159 |
160 | @Override
161 | public Loader onCreateLoader(int id, Bundle args) {
162 | // Define a projection for the columns we are interested in
163 | String[] projection = {
164 | BookEntry._ID,
165 | BookEntry.COLUMN_BOOK_PICTURE,
166 | BookEntry.COLUMN_BOOK_NAME,
167 | BookEntry.COLUMN_BOOK_PRICE,
168 | BookEntry.COLUMN_BOOK_QUANTITY
169 | };
170 |
171 | // This loader will execute the ContentProvider's query method on a background thread
172 | return new CursorLoader(this, // Parent activity context
173 | BookEntry.CONTENT_URI, // Provider content to query
174 | projection, // Columns to include in resulting cursor
175 | null, // No selection clause
176 | null, // No selection args
177 | null); // Default sort order
178 | }
179 |
180 | @Override
181 | public void onLoadFinished(Loader loader, Cursor data) {
182 | // Pass resulting cursor into CursorAdapter
183 | mCursorAdapter.swapCursor(data);
184 | }
185 |
186 | @Override
187 | public void onLoaderReset(Loader loader) {
188 | // Called when the data needs to be deleted
189 | mCursorAdapter.swapCursor(null);
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_editor.xml:
--------------------------------------------------------------------------------
1 |
12 |
15 |
16 |
23 |
24 |
29 |
30 |
36 |
37 |
38 |
45 |
46 |
47 |
51 |
52 |
53 |
58 |
59 |
60 |
67 |
68 |
69 |
70 |
71 |
75 |
76 |
77 |
82 |
83 |
84 |
91 |
92 |
93 |
94 |
95 |
99 |
100 |
101 |
106 |
107 |
108 |
115 |
116 |
117 |
118 |
119 |
123 |
124 |
125 |
130 |
131 |
132 |
139 |
140 |
141 |
142 |
143 |
147 |
148 |
149 |
154 |
155 |
156 |
163 |
164 |
165 |
166 |
167 |
171 |
172 |
173 |
178 |
179 |
180 |
187 |
188 |
194 |
195 |
200 |
201 |
206 |
207 |
208 |
209 |
210 |
211 |
215 |
216 |
217 |
222 |
223 |
224 |
231 |
232 |
233 |
234 |
235 |
239 |
240 |
241 |
246 |
247 |
248 |
255 |
256 |
262 |
263 |
268 |
269 |
270 |
271 |
272 |
273 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/data/BookProvider.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore.data;
2 |
3 | import android.content.ContentProvider;
4 | import android.content.ContentUris;
5 | import android.content.ContentValues;
6 | import android.content.UriMatcher;
7 | import android.database.Cursor;
8 | import android.database.sqlite.SQLiteDatabase;
9 | import android.net.Uri;
10 | import android.support.annotation.NonNull;
11 | import android.support.annotation.Nullable;
12 | import android.util.Log;
13 |
14 | import com.botsone.android.bookstore.data.BookContract.BookEntry;
15 |
16 | public class BookProvider extends ContentProvider {
17 |
18 | /**
19 | * Tag for the log messages
20 | */
21 | public static final String LOG_TAG = BookProvider.class.getSimpleName();
22 |
23 | // Database helper object
24 | private BookDbHelper mDbHelper;
25 |
26 | /**
27 | * URI matcher code for the content URI for the books table
28 | */
29 | private static final int BOOKS = 100;
30 |
31 | /**
32 | * URI matcher code for the content URI for a single book in the books table
33 | */
34 | private static final int BOOK_ID = 101;
35 |
36 | /**
37 | * UriMatcher object to match a content URI to a corresponding code.
38 | * The input passed into the constructor represents the code to return for the root URI.
39 | * It's common to use NO_MATCH as the input for this case.
40 | */
41 | private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
42 |
43 | // Static initializer. This is run the first time anything is called from this class.
44 | static {
45 | // The calls to addURI() go here, for all of the content URI patterns that the provider
46 | // should recognize. All paths added to the UriMatcher have a corresponding code to return
47 | // when a match is found.
48 |
49 | sUriMatcher.addURI(BookContract.CONTENT_AUTHORITY, BookContract.PATH_BOOKS, BOOKS);
50 | sUriMatcher.addURI(BookContract.CONTENT_AUTHORITY, BookContract.PATH_BOOKS + "/#", BOOK_ID);
51 | }
52 |
53 | @Override
54 | public boolean onCreate() {
55 | mDbHelper = new BookDbHelper(getContext());
56 | return true;
57 | }
58 |
59 | /**
60 | * Perform the query for the given URI. Use the given projection, selection, selection arguments,
61 | * and sort order.
62 | */
63 | @Nullable
64 | @Override
65 | public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection,
66 | @Nullable String[] selectionArgs, @Nullable String sortOrder) {
67 |
68 | SQLiteDatabase database = mDbHelper.getReadableDatabase();
69 |
70 | Cursor cursor;
71 |
72 | int match = sUriMatcher.match(uri);
73 | switch (match) {
74 | case BOOKS:
75 | cursor = database.query(BookEntry.TABLE_NAME, projection, selection, selectionArgs,
76 | null, null, sortOrder);
77 | break;
78 | case BOOK_ID:
79 | selection = BookEntry._ID + "=?";
80 | selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
81 | cursor = database.query(BookEntry.TABLE_NAME, projection, selection, selectionArgs,
82 | null, null, sortOrder);
83 | break;
84 | default:
85 | throw new IllegalArgumentException("Cannot query unknown URI " + uri);
86 | }
87 |
88 | // Set notification URI on the cursor so we know what content URI the Cursor was
89 | // Created for. If data at this URI changes, we know to update the cursor
90 | cursor.setNotificationUri(getContext().getContentResolver(), uri);
91 |
92 | // Return the cursor
93 | return cursor;
94 | }
95 |
96 | /**
97 | * Insert new data into the provider with the given ContentValues.
98 | */
99 | @Nullable
100 | @Override
101 | public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
102 | final int match = sUriMatcher.match(uri);
103 | switch (match) {
104 | case BOOKS:
105 | return insertBook(uri, contentValues);
106 | default:
107 | throw new IllegalArgumentException("Insertion is not supported for " + uri);
108 | }
109 | }
110 |
111 |
112 | /**
113 | * Insert a book into the database with the given content values. Return the new content URI
114 | * for that specific row in the database.
115 | */
116 | private Uri insertBook(Uri uri, ContentValues values) {
117 | // Check that the name is not null
118 | String name = values.getAsString(BookEntry.COLUMN_BOOK_NAME);
119 | if (name == null) {
120 | throw new IllegalArgumentException("Book requires a name");
121 | }
122 |
123 | // Check that the price is not null or negative
124 | Integer price = values.getAsInteger(BookEntry.COLUMN_BOOK_PRICE);
125 | if (price == null) {
126 | throw new IllegalArgumentException("Book requires a price");
127 | } else if (price < 0) {
128 | throw new IllegalArgumentException("Book price cannot be negative");
129 | }
130 |
131 | // Check that the quantity is not null or negative
132 | Integer quantity = values.getAsInteger(BookEntry.COLUMN_BOOK_QUANTITY);
133 | if (quantity == null) {
134 | throw new IllegalArgumentException("Book requires a quantity");
135 | } else if (quantity < 0) {
136 | throw new IllegalArgumentException("Book quantity cannot be negative");
137 | }
138 |
139 | // Get writable database
140 | SQLiteDatabase database = mDbHelper.getWritableDatabase();
141 |
142 | // Insert the book into the db
143 | long id = database.insert(BookEntry.TABLE_NAME, null, values);
144 |
145 | if (id == -1) {
146 | Log.e(LOG_TAG, "Failed to insert row for " + uri);
147 | return null;
148 | }
149 |
150 | // Notify all listeners that the data has changed for the book content uri
151 | getContext().getContentResolver().notifyChange(uri, null);
152 |
153 | // Once we know the ID of the new row in the table,
154 | // return the new URI with the ID appended to the end of it
155 | return ContentUris.withAppendedId(uri, id);
156 | }
157 |
158 | /**
159 | * Updates the data at the given selection and selection arguments, with the new ContentValues.
160 | */
161 | @Override
162 | public int update(Uri uri, ContentValues contentValues, String selection,
163 | String[] selectionArgs) {
164 | final int match = sUriMatcher.match(uri);
165 | switch (match) {
166 | case BOOKS:
167 | return updateBook(uri, contentValues, selection, selectionArgs);
168 | case BOOK_ID:
169 | // For the BOOK_ID code, extract out the ID from the URI,
170 | // so we know which row to update. Selection will be "_id=?" and selection
171 | // arguments will be a String array containing the actual ID.
172 | selection = BookEntry._ID + "=?";
173 | selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
174 | return updateBook(uri, contentValues, selection, selectionArgs);
175 | default:
176 | throw new IllegalArgumentException("Update is not supported for " + uri);
177 | }
178 | }
179 |
180 | /**
181 | * Update books in the database with the given content values. Apply the changes to the rows
182 | * specified in the selection and selection arguments (which could be 0 or 1 or more books).
183 | * Return the number of rows that were successfully updated.
184 | */
185 | private int updateBook(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
186 | // If the COLUMN_BOOK_NAME key is present, make sure it's not null
187 | if (values.containsKey(BookEntry.COLUMN_BOOK_NAME)) {
188 | String name = values.getAsString(BookEntry.COLUMN_BOOK_NAME);
189 | if (name == null) {
190 | throw new IllegalArgumentException("Book requires a name");
191 | }
192 | }
193 |
194 | // If the COLUMN_BOOK_PRICE key is present, make sure it's not null or negative
195 | if (values.containsKey(BookEntry.COLUMN_BOOK_PRICE)) {
196 | Integer price = values.getAsInteger(BookEntry.COLUMN_BOOK_PRICE);
197 | if (price == null) {
198 | throw new IllegalArgumentException("Book requires a price");
199 | } else if (price < 0) {
200 | throw new IllegalArgumentException("Book price cannot be negative");
201 | }
202 | }
203 |
204 | // If the COLUMN_BOOK_QUANTITY key is present, make sure it's not null or negative
205 | if (values.containsKey(BookEntry.COLUMN_BOOK_QUANTITY)) {
206 | Integer quantity = values.getAsInteger(BookEntry.COLUMN_BOOK_QUANTITY);
207 | if (quantity == null) {
208 | throw new IllegalArgumentException("Book requires a quantity");
209 | } else if (quantity < 0) {
210 | throw new IllegalArgumentException("Book quantity cannot be negative");
211 | }
212 | }
213 |
214 | // If there are no values to update, then don't try to update the database
215 | if (values.size() == 0) {
216 | return 0;
217 | }
218 |
219 | // Otherwise, get writable database and update the data
220 | SQLiteDatabase database = mDbHelper.getWritableDatabase();
221 |
222 | // Perform the update on the database and get the number of rows affected
223 | int rowsUpdated = database.update(BookEntry.TABLE_NAME, values, selection, selectionArgs);
224 |
225 | // If 1 or more rows were updated notify all listeners that the data at
226 | // the given URI has changed
227 | if (rowsUpdated != 0) {
228 | getContext().getContentResolver().notifyChange(uri, null);
229 | }
230 |
231 | // Return the number of rows updated
232 | return rowsUpdated;
233 | }
234 |
235 | /**
236 | * Delete the data at the given selection and selection arguments.
237 | */
238 | @Override
239 | public int delete(Uri uri, String selection, String[] selectionArgs) {
240 | // Get writable database
241 | SQLiteDatabase database = mDbHelper.getWritableDatabase();
242 |
243 | // Track the number of rows deleted
244 | int rowsDeleted;
245 |
246 | final int match = sUriMatcher.match(uri);
247 | switch (match) {
248 | case BOOKS:
249 | // Delete all rows that match the selection and selection args
250 | rowsDeleted = database.delete(BookEntry.TABLE_NAME, selection, selectionArgs);
251 | break;
252 | case BOOK_ID:
253 | // Delete a single row given by the ID in the URI
254 | selection = BookEntry._ID + "=?";
255 | selectionArgs = new String[]{String.valueOf(ContentUris.parseId(uri))};
256 | rowsDeleted = database.delete(BookEntry.TABLE_NAME, selection, selectionArgs);
257 | break;
258 | default:
259 | throw new IllegalArgumentException("Deletion is not supported for " + uri);
260 | }
261 |
262 | // If 1 or more rows were deleted, notify all listeners that the data at
263 | // the given URI has changed
264 | if (rowsDeleted != 0) {
265 | getContext().getContentResolver().notifyChange(uri, null);
266 | }
267 |
268 | // Return the number of rows deleted
269 | return rowsDeleted;
270 | }
271 |
272 | /**
273 | * Returns the MIME type of data for the content URI.
274 | */
275 | @Nullable
276 | @Override
277 | public String getType(@NonNull Uri uri) {
278 | final int match = sUriMatcher.match(uri);
279 | switch (match) {
280 | case BOOKS:
281 | return BookEntry.CONTENT_LIST_TYPE;
282 | case BOOK_ID:
283 | return BookEntry.CONTENT_ITEM_TYPE;
284 | default:
285 | throw new IllegalStateException("Unknown URI " + uri + " with match " + match);
286 | }
287 | }
288 | }
289 |
--------------------------------------------------------------------------------
/app/src/main/java/com/botsone/android/bookstore/EditorActivity.java:
--------------------------------------------------------------------------------
1 | package com.botsone.android.bookstore;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.app.LoaderManager;
6 | import android.content.ContentResolver;
7 | import android.content.ContentValues;
8 | import android.content.CursorLoader;
9 | import android.content.DialogInterface;
10 | import android.content.Intent;
11 | import android.content.Loader;
12 | import android.database.Cursor;
13 | import android.graphics.Bitmap;
14 | import android.graphics.BitmapFactory;
15 | import android.graphics.drawable.Drawable;
16 | import android.net.Uri;
17 | import android.os.Build;
18 | import android.os.Bundle;
19 | import android.provider.ContactsContract;
20 | import android.support.v4.app.NavUtils;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.text.TextUtils;
23 | import android.util.Log;
24 | import android.view.Menu;
25 | import android.view.MenuItem;
26 | import android.view.MotionEvent;
27 | import android.view.View;
28 | import android.widget.Button;
29 | import android.widget.EditText;
30 | import android.widget.ImageButton;
31 | import android.widget.ImageView;
32 | import android.widget.Toast;
33 |
34 | import com.botsone.android.bookstore.data.BookContract.BookEntry;
35 | import com.squareup.picasso.Picasso;
36 |
37 | import org.w3c.dom.Text;
38 |
39 | import java.io.FileNotFoundException;
40 | import java.io.IOException;
41 | import java.io.InputStream;
42 | import java.sql.Blob;
43 | import java.text.NumberFormat;
44 |
45 | /**
46 | * Allows user to create a new book or edit an existing one.
47 | */
48 | public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {
49 |
50 | /**
51 | * identifier for the book data loader
52 | */
53 | private static final int EXISTING_BOOK_LOADER = 0;
54 |
55 | /**
56 | * Content URI for the existing book (null if it's a new book)
57 | */
58 | private Uri mCurrentBookUri;
59 |
60 | /**
61 | * Log tag for debug purposes
62 | */
63 | private static final String LOG_TAG = EditorActivity.class.getSimpleName();
64 |
65 | /**
66 | * EditText field to enter the book's name
67 | */
68 | private EditText mNameEditText;
69 |
70 | /**
71 | * EditText field to enter the book's store section
72 | */
73 | private EditText mSectionEditText;
74 |
75 | /**
76 | * EditText field to enter the book's author
77 | */
78 | private EditText mAuthorEditText;
79 |
80 | /**
81 | * EditText field to enter the book's publisher
82 | */
83 | private EditText mPublisherEditText;
84 |
85 | /**
86 | * EditText field to enter the book's price
87 | */
88 | private EditText mPriceEditText;
89 |
90 | /**
91 | * EditText field to enter the book's quantity
92 | */
93 | private EditText mQuantityEditText;
94 |
95 | /**
96 | * EditText field to enter the book's supplier
97 | */
98 | private EditText mSupplierEditText;
99 |
100 | /**
101 | * EditText field to enter the book's supplier phone number
102 | */
103 | private EditText mSupplierPhoneEditText;
104 |
105 | private Uri mUri;
106 |
107 | private ImageView mImageView;
108 |
109 | private Button mMinusButton;
110 | private Button mPlusButton;
111 |
112 | private Button mCallButton;
113 |
114 | private static final int PICK_IMAGE_REQUEST = 0;
115 | private static final int SEND_MAIL_REQUEST = 1;
116 |
117 | /**
118 | * Boolean flag to keep track of whether book has been edited
119 | */
120 | private boolean mBookHasChanged = false;
121 |
122 | /**
123 | * onTouchListener that listens for any user touches on a view, implying that the user is
124 | * modifying the view, if so we change mBookHasChanged to true
125 | */
126 | private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
127 | @Override
128 | public boolean onTouch(View v, MotionEvent event) {
129 | mBookHasChanged = true;
130 | return false;
131 | }
132 | };
133 |
134 | @Override
135 | protected void onCreate(Bundle savedInstanceState) {
136 | super.onCreate(savedInstanceState);
137 | setContentView(R.layout.activity_editor);
138 |
139 | // Examine the intent that was used to launch this activity in order to figure out
140 | // if we are creating a new book or editing an existing one
141 | Intent intent = getIntent();
142 | mCurrentBookUri = intent.getData();
143 |
144 | // If the intent doesn't contain a specific URI we know to create a new book
145 | if (mCurrentBookUri == null) {
146 | // This is a new book, change the app bar to say "Add a Book"
147 | setTitle(R.string.editor_activity_title_new_book);
148 |
149 | // Invalidate the options menu so "Delete" doesn't appear and confuse user
150 | invalidateOptionsMenu();
151 | } else {
152 | // Otherwise this is an existing book, change bar to say "Edit Book"
153 | setTitle(R.string.editor_activity_title_edit_book);
154 | }
155 |
156 | // Find all the relevant views that we will need to read user input from
157 | mMinusButton = (Button) findViewById(R.id.minus_button);
158 | mPlusButton = (Button) findViewById(R.id.plus_button);
159 | mCallButton = (Button) findViewById(R.id.call_button);
160 | mImageView = (ImageButton) findViewById(R.id.edit_image_view);
161 | mNameEditText = (EditText) findViewById(R.id.edit_book_name);
162 | mSectionEditText = (EditText) findViewById(R.id.edit_book_section);
163 | mAuthorEditText = (EditText) findViewById(R.id.edit_book_author);
164 | mPublisherEditText = (EditText) findViewById(R.id.edit_book_publisher);
165 | mPriceEditText = (EditText) findViewById(R.id.edit_book_price);
166 | mQuantityEditText = (EditText) findViewById(R.id.edit_book_quantity);
167 | mSupplierEditText = (EditText) findViewById(R.id.edit_book_supplier);
168 | mSupplierPhoneEditText = (EditText) findViewById(R.id.edit_book_supplier_phone);
169 |
170 | // Initialize a loader to read the book data from the db and display
171 | // the current values in the editor
172 | getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
173 |
174 | // Set up onClickListener for imageView
175 | mImageView.setOnClickListener(new View.OnClickListener() {
176 | @Override
177 | public void onClick(View v) {
178 | openImageSelector();
179 | }
180 | });
181 |
182 | // Set up click listener for minus button
183 | mMinusButton.setOnClickListener(new View.OnClickListener() {
184 | @Override
185 | public void onClick(View v) {
186 | if (mQuantityEditText.getText().toString().equals("")) {
187 | mQuantityEditText.setText("1");
188 | }
189 | String quantityString = mQuantityEditText.getText().toString();
190 | int quantity = Integer.parseInt(quantityString);
191 |
192 | if (quantity < 1) {
193 | Toast.makeText(getApplicationContext(), R.string.sale_button_zero, Toast.LENGTH_SHORT).show();
194 | } else {
195 | quantity--;
196 | }
197 | mQuantityEditText.setText(String.valueOf(quantity));
198 | }
199 | });
200 |
201 | // Set up click listener for plus button
202 | mPlusButton.setOnClickListener(new View.OnClickListener() {
203 | @Override
204 | public void onClick(View v) {
205 | if (mQuantityEditText.getText().toString().equals("")) {
206 | mQuantityEditText.setText("0");
207 | }
208 | String quantityString = mQuantityEditText.getText().toString();
209 | int quantity = Integer.parseInt(quantityString);
210 | quantity++;
211 | mQuantityEditText.setText(String.valueOf(quantity));
212 | }
213 | });
214 |
215 | // Set up click listener for call button
216 | mCallButton.setOnClickListener(new View.OnClickListener() {
217 | @Override
218 | public void onClick(View v) {
219 | String phoneNumber = mSupplierPhoneEditText.getText().toString();
220 | Intent intent = new Intent(Intent.ACTION_DIAL);
221 | intent.setData(Uri.parse("tel:" + phoneNumber));
222 | if (intent.resolveActivity(getPackageManager()) != null) {
223 |
224 | startActivity(intent);
225 |
226 | } else {
227 | Toast.makeText(getApplicationContext(), R.string.no_dialer_installed, Toast.LENGTH_SHORT).show();
228 | }
229 |
230 | }
231 | });
232 |
233 | // Setup onTouchListeners on all input fields to determine whether the user has
234 | // touched them so we can warn about unsaved changes
235 | mImageView.setOnTouchListener(mTouchListener);
236 | mNameEditText.setOnTouchListener(mTouchListener);
237 | mSectionEditText.setOnTouchListener(mTouchListener);
238 | mAuthorEditText.setOnTouchListener(mTouchListener);
239 | mPublisherEditText.setOnTouchListener(mTouchListener);
240 | mPriceEditText.setOnTouchListener(mTouchListener);
241 | mQuantityEditText.setOnTouchListener(mTouchListener);
242 | mSupplierEditText.setOnTouchListener(mTouchListener);
243 | mSupplierPhoneEditText.setOnTouchListener(mTouchListener);
244 | }
245 |
246 | public void openImageSelector() {
247 | Intent intent;
248 |
249 | if (Build.VERSION.SDK_INT < 19) {
250 | intent = new Intent(Intent.ACTION_GET_CONTENT);
251 | } else {
252 | intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
253 | intent.addCategory(Intent.CATEGORY_OPENABLE);
254 | }
255 |
256 | intent.setType("image/*");
257 | startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
258 | }
259 |
260 | @Override
261 | public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
262 | // The ACTION_OPEN_DOCUMENT intent was sent with the request code READ_REQUEST_CODE.
263 | // If the request code seen here doesn't match, it's the response to some other intent,
264 | // and the below code shouldn't run at all.
265 |
266 | if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
267 | // The document selected by the user won't be returned in the intent.
268 | // Instead, a URI to that document will be contained in the return intent
269 | // provided to this method as a parameter. Pull that uri using "resultData.getData()"
270 |
271 | if (resultData != null) {
272 | mUri = resultData.getData();
273 | Log.i(LOG_TAG, "Uri: " + mUri.toString());
274 |
275 | //mImageView.setImageBitmap(getBitmapFromUri(mUri));
276 | Picasso.get().load(mUri).resize(400, 400).into(mImageView);
277 | }
278 | }
279 | }
280 |
281 | public Bitmap getBitmapFromUri(Uri uri) {
282 |
283 | if (uri == null || uri.toString().isEmpty())
284 | return null;
285 |
286 | // Get the dimensions of the View
287 | int targetW = mImageView.getWidth();
288 | int targetH = mImageView.getHeight();
289 |
290 | InputStream input = null;
291 | try {
292 | input = this.getContentResolver().openInputStream(uri);
293 |
294 | // Get the dimensions of the bitmap
295 | BitmapFactory.Options bmOptions = new BitmapFactory.Options();
296 | bmOptions.inJustDecodeBounds = true;
297 | BitmapFactory.decodeStream(input, null, bmOptions);
298 | input.close();
299 |
300 | int photoW = bmOptions.outWidth;
301 | int photoH = bmOptions.outHeight;
302 |
303 | // Determine how much to scale down the image
304 | int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
305 |
306 | // Decode the image file into a Bitmap sized to fill the View
307 | bmOptions.inJustDecodeBounds = false;
308 | bmOptions.inSampleSize = scaleFactor;
309 | bmOptions.inPurgeable = true;
310 |
311 | input = this.getContentResolver().openInputStream(uri);
312 | Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
313 | input.close();
314 | return bitmap;
315 |
316 | } catch (FileNotFoundException fne) {
317 | Log.e(LOG_TAG, "Failed to load image.", fne);
318 | return null;
319 | } catch (Exception e) {
320 | Log.e(LOG_TAG, "Failed to load image.", e);
321 | return null;
322 | } finally {
323 | try {
324 | input.close();
325 | } catch (IOException ioe) {
326 |
327 | }
328 | }
329 | }
330 |
331 | private void saveBook() {
332 | // Read input from fields
333 | // Use trim to trim leading or trailing whitespace
334 |
335 | String pictureString;
336 | if (mUri != null) {
337 | pictureString = mUri.toString();
338 | } else {
339 | mUri = Uri.parse("android.resource://com.botsone.android.bookstore/drawable/ic_empty");
340 | pictureString = mUri.toString();
341 | }
342 |
343 | String nameString = mNameEditText.getText().toString().trim();
344 | String sectionString = mSectionEditText.getText().toString().trim();
345 | String authorString = mAuthorEditText.getText().toString().trim();
346 | String publisherString = mPublisherEditText.getText().toString().trim();
347 | String priceString = mPriceEditText.getText().toString().trim();
348 | String quantityString = mQuantityEditText.getText().toString().trim();
349 | String supplierString = mSupplierEditText.getText().toString().trim();
350 | String supplierNumberString = mSupplierPhoneEditText.getText().toString().trim();
351 |
352 | // Convert price to double and quantity to int
353 | double price = Double.parseDouble(priceString);
354 |
355 | int quantity = Integer.parseInt(quantityString);
356 |
357 | // Create a ContentValues object where column names are the keys,
358 | // and book attributes from the editor are the values.
359 | ContentValues values = new ContentValues();
360 |
361 | values.put(BookEntry.COLUMN_BOOK_PICTURE, pictureString);
362 | values.put(BookEntry.COLUMN_BOOK_NAME, nameString);
363 | values.put(BookEntry.COLUMN_BOOK_SECTION, sectionString);
364 | values.put(BookEntry.COLUMN_BOOK_AUTHOR, authorString);
365 | values.put(BookEntry.COLUMN_BOOK_PUBLISHER, publisherString);
366 | values.put(BookEntry.COLUMN_BOOK_PRICE, price);
367 | values.put(BookEntry.COLUMN_BOOK_QUANTITY, quantity);
368 | values.put(BookEntry.COLUMN_BOOK_SUPPLIER, supplierString);
369 | values.put(BookEntry.COLUMN_BOOK_SUPPLIER_PHONE, supplierNumberString);
370 |
371 | // Determine if this is a new book or not by checking if mCurrentBookUri is null
372 | if (mCurrentBookUri == null)
373 |
374 | {
375 | // NEW BOOK - insert book into the provider, return the URI for the new book
376 | Uri newUri = getContentResolver().insert(BookEntry.CONTENT_URI, values);
377 |
378 | // Pop toast saying whether or not we had success
379 | if (newUri == null) {
380 | // ERROR
381 | Toast.makeText(this, getString(R.string.editor_insert_book_failed),
382 | Toast.LENGTH_SHORT).show();
383 | } else {
384 | // Insertion successful
385 | Toast.makeText(this, getString(R.string.editor_insert_book_successful),
386 | Toast.LENGTH_SHORT).show();
387 | }
388 |
389 | } else
390 |
391 | {
392 | // EXISTING BOOK - update book with content URI mCurrentBookUri and pass in the
393 | // new ContentValues. Pass null for selection and selectionArgs because mCurrentBookUri
394 | // will already identify the correct row in the db that we want to modify
395 | int rowsAffected = getContentResolver().update(mCurrentBookUri, values,
396 | null, null);
397 |
398 | // Pop toast saying whether update was successful
399 | if (rowsAffected == 0) {
400 | // ERROR
401 | Toast.makeText(this, getString(R.string.editor_update_book_failed),
402 | Toast.LENGTH_SHORT).show();
403 | } else {
404 | // update successful
405 | Toast.makeText(this, getString(R.string.editor_update_book_successful),
406 | Toast.LENGTH_SHORT).show();
407 | }
408 |
409 |
410 | }
411 |
412 | }
413 |
414 | @Override
415 | public boolean onCreateOptionsMenu(Menu menu) {
416 | // Inflate the menu options from the res/menu/menu_editor.xml file.
417 | // This adds menu items to the app bar.
418 | getMenuInflater().inflate(R.menu.menu_editor, menu);
419 | return true;
420 | }
421 |
422 | // This method is called after invalidateOptionsMenu so that the menu can be updated
423 | @Override
424 | public boolean onPrepareOptionsMenu(Menu menu) {
425 | super.onPrepareOptionsMenu(menu);
426 |
427 | // If this is a new book hide the delete menu item
428 | if (mCurrentBookUri == null) {
429 | MenuItem menuItem = menu.findItem(R.id.action_delete);
430 | menuItem.setVisible(false);
431 | }
432 | return true;
433 | }
434 |
435 | @Override
436 | public boolean onOptionsItemSelected(MenuItem item) {
437 | // User clicked on a menu option in the app bar overflow menu
438 | switch (item.getItemId()) {
439 | // Respond to a click on the "Save" menu option
440 | case R.id.action_save:
441 |
442 | // Check to make sure name price and quantity are entered
443 | if (mNameEditText.getText().toString().isEmpty() ||
444 | mPriceEditText.getText().toString().isEmpty() ||
445 | mQuantityEditText.getText().toString().isEmpty()) {
446 | Toast.makeText(this, R.string.editor_enter_info,
447 | Toast.LENGTH_SHORT).show();
448 | return true;
449 | } else {
450 | saveBook();
451 | finish();
452 | return true;
453 | }
454 |
455 | // Respond to a click on the "Delete" menu option
456 | case R.id.action_delete:
457 | // Pop confirmation dialog
458 | showDeleteConfirmationDialog();
459 | return true;
460 | // Respond to a click on the "Up" arrow button in the app bar
461 | case android.R.id.home:
462 | // If no changes were made go up to parent activity
463 | if (!mBookHasChanged) {
464 | NavUtils.navigateUpFromSameTask(this);
465 | return true;
466 | }
467 |
468 | // If there are unsaved changes, pop a dialog
469 | DialogInterface.OnClickListener discardButtonClickListener =
470 | new DialogInterface.OnClickListener() {
471 | @Override
472 | public void onClick(DialogInterface dialogInterface, int i) {
473 | // User clicked "Discard" button, navigate to parent activity.
474 | NavUtils.navigateUpFromSameTask(EditorActivity.this);
475 | }
476 | };
477 |
478 | // Show a dialog that notifies the user they have unsaved changes
479 | showUnsavedChangesDialog(discardButtonClickListener);
480 | return true;
481 | }
482 | return super.onOptionsItemSelected(item);
483 | }
484 |
485 | /**
486 | * This method is called when the back button is pressed
487 | */
488 | @Override
489 | public void onBackPressed() {
490 | // If book hasn't changed, continue with back press
491 | if (!mBookHasChanged) {
492 | super.onBackPressed();
493 | return;
494 | }
495 |
496 | // Otherwise unsaved changes were made, pop a dialog.
497 | DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() {
498 | @Override
499 | public void onClick(DialogInterface dialog, int which) {
500 | // User clicked Discard button close the current activity
501 | finish();
502 | }
503 | };
504 |
505 | // Show dialog that there are unsaved changes
506 | showUnsavedChangesDialog(discardButtonClickListener);
507 | }
508 |
509 | @Override
510 | public Loader onCreateLoader(int i, Bundle bundle) {
511 | if (mCurrentBookUri == null) {
512 | return null;
513 | }
514 |
515 | // This loader will execute the ContentProvider's query method on
516 | // a background thread
517 | return new CursorLoader(this, // Parent activity context
518 | mCurrentBookUri, // Query the contentUri for the current book
519 | null, // Columns to include
520 | null, // No selection clause
521 | null, // No selection args
522 | null); // Default sort order
523 | }
524 |
525 | @Override
526 | public void onLoadFinished(Loader loader, Cursor cursor) {
527 | // Bail early if cursor is null or there is less than 1 row in the cursor
528 | if (cursor == null || cursor.getCount() < 1) {
529 | return;
530 | }
531 |
532 | // Proceed with moving to the first row of the cursor and reading data from it
533 | // (This should be the only row in the cursor)
534 | if (cursor.moveToFirst()) {
535 | // Find the columns of book attributes that we're interested in
536 | int pictureColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_PICTURE);
537 | int nameColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_NAME);
538 | int sectionColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_SECTION);
539 | int authorColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_AUTHOR);
540 | int publisherColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_PUBLISHER);
541 | int priceColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_PRICE);
542 | int quantityColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_QUANTITY);
543 | int supplierColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_SUPPLIER);
544 | int supplierPhoneColumnIndex = cursor.getColumnIndex(BookEntry.COLUMN_BOOK_SUPPLIER_PHONE);
545 |
546 | // Extract out the value from the cursor for the given column index
547 | String picture = cursor.getString(pictureColumnIndex);
548 | String name = cursor.getString(nameColumnIndex);
549 | String section = cursor.getString(sectionColumnIndex);
550 | String author = cursor.getString(authorColumnIndex);
551 | String publisher = cursor.getString(publisherColumnIndex);
552 | double price = cursor.getDouble(priceColumnIndex);
553 | String stringPrice = Double.toString(price);
554 | int quantity = cursor.getInt(quantityColumnIndex);
555 | String stringQuantity = Integer.toString(quantity);
556 | String supplier = cursor.getString(supplierColumnIndex);
557 | String supplierPhone = cursor.getString(supplierPhoneColumnIndex);
558 |
559 | //mImageView.setImageURI(Uri.parse(picture));
560 | Picasso.get().load(Uri.parse(picture)).resize(400, 400).into(mImageView);
561 | mNameEditText.setText(name);
562 | mSectionEditText.setText(section);
563 | mAuthorEditText.setText(author);
564 | mPublisherEditText.setText(publisher);
565 | mPriceEditText.setText(stringPrice);
566 | mQuantityEditText.setText(stringQuantity);
567 | mSupplierEditText.setText(supplier);
568 | mSupplierPhoneEditText.setText(supplierPhone);
569 | }
570 | }
571 |
572 | @Override
573 | public void onLoaderReset(Loader loader) {
574 | // If the loader is invalidated, clear out all data from the input fields
575 | mImageView.setImageURI(null);
576 | mNameEditText.setText("");
577 | mSectionEditText.setText("");
578 | mAuthorEditText.setText("");
579 | mPublisherEditText.setText("");
580 | mPriceEditText.setText("");
581 | mQuantityEditText.setText("");
582 | mSupplierEditText.setText("");
583 | mSupplierPhoneEditText.setText("");
584 | }
585 |
586 | private void showUnsavedChangesDialog(
587 | DialogInterface.OnClickListener discardButtonClickListener) {
588 | // Create an AlertDialog.Builder and set the message, and click listeners
589 | // for the positive and negative buttons on the dialog.
590 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
591 | builder.setMessage(R.string.unsaved_changes_dialog_msg);
592 | builder.setPositiveButton(R.string.discard, discardButtonClickListener);
593 | builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
594 | public void onClick(DialogInterface dialog, int id) {
595 | // User clicked the "Keep editing" button, so dismiss the dialog
596 | // and continue editing the book.
597 | if (dialog != null) {
598 | dialog.dismiss();
599 | }
600 | }
601 | });
602 |
603 | // Create and show the AlertDialog
604 | AlertDialog alertDialog = builder.create();
605 | alertDialog.show();
606 | }
607 |
608 | /**
609 | * Prompt the user to confirm that they want to delete this book.
610 | */
611 | private void showDeleteConfirmationDialog() {
612 | // Create an AlertDialog.Builder and set the message, and click listeners
613 | // for the postivie and negative buttons on the dialog.
614 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
615 | builder.setMessage(R.string.delete_dialog_msg);
616 | builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
617 | public void onClick(DialogInterface dialog, int id) {
618 | // User clicked the "Delete" button, so delete the book.
619 | deleteBook();
620 | }
621 | });
622 | builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
623 | public void onClick(DialogInterface dialog, int id) {
624 | // User clicked the "Cancel" button, so dismiss the dialog
625 | // and continue editing the book.
626 | if (dialog != null) {
627 | dialog.dismiss();
628 | }
629 | }
630 | });
631 |
632 | // Create and show the AlertDialog
633 | AlertDialog alertDialog = builder.create();
634 | alertDialog.show();
635 | }
636 |
637 | /**
638 | * Perform the deletion of the book in the database.
639 | */
640 | private void deleteBook() {
641 | // Only perform delete if this is an existing book
642 | if (mCurrentBookUri != null) {
643 | // Call the ContentResolver to delete the book at the given content URI.
644 | // Pass in null for the selection and selection args because the mCurrentBookUri
645 | // content URI already identifies the book that we want.
646 | int rowsDeleted = getContentResolver().delete(mCurrentBookUri, null, null);
647 | // Show a toast message depending on whether or not the delete was successful.
648 | if (rowsDeleted == 0) {
649 | // If no rows were deleted, then there was an error with the delete.
650 | Toast.makeText(this, getString(R.string.editor_delete_book_failed),
651 | Toast.LENGTH_SHORT).show();
652 | } else {
653 | // Otherwise, the delete was successful and we can display a toast.
654 | Toast.makeText(this, getString(R.string.editor_delete_book_successful),
655 | Toast.LENGTH_SHORT).show();
656 | }
657 |
658 | }
659 |
660 | // Notify the content resolver and close the activity
661 | getContentResolver().notifyChange(mCurrentBookUri, null);
662 | finish();
663 | }
664 | }
665 |
--------------------------------------------------------------------------------