diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3830495 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea +.DS_Store +/build +/captures +/app/google-services.json diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..6d2780d --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,67 @@ +apply plugin: 'com.android.application' +apply plugin: 'com.neenbedankt.android-apt' +apply plugin: 'com.noveogroup.android.check' + +repositories { + maven { url "https://jitpack.io" } +} + +android { + compileSdkVersion 25 + buildToolsVersion "25.0.0" + + defaultConfig { + applicationId "com.udacity.stockhawk" + minSdkVersion 21 + targetSdkVersion 25 + versionCode 1 + versionName "1.0" + multiDexEnabled true + } + + buildTypes { + + release { + minifyEnabled false + shrinkResources false + proguardFile "proguard-butterknife-7.pro" + proguardFile "proguard-google-play-services.pro" + proguardFile "proguard-guava.pro" + proguardFile "proguard-square-okhttp3.pro" + proguardFile "proguard-square-okio.pro" + proguardFile "proguard-support-v7-appcompat.pro" + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + lintOptions { + warning 'InvalidPackage' + } +} + +check { + checkstyle { config hard() } + findbugs { config hard() } + pmd { + config hard() + skip true + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + testCompile 'junit:junit:4.12' + compile 'com.android.support:appcompat-v7:25.0.0' + compile 'com.android.support:recyclerview-v7:25.0.0' + compile 'com.android.support:design:25.0.0' + compile 'com.jakewharton:butterknife:8.1.0' + apt 'com.jakewharton:butterknife-compiler:8.1.0' + compile 'com.google.guava:guava:19.0' + compile 'com.squareup.okio:okio:1.8.0' + compile 'com.squareup.okhttp3:okhttp:3.3.1' + compile 'com.yahoofinance-api:YahooFinanceAPI:3.3.0' + compile 'com.jakewharton.timber:timber:4.1.2' + compile 'com.melnykov:floatingactionbutton:1.3.0' + compile 'net.sf.opencsv:opencsv:2.3' + compile 'com.github.PhilJay:MPAndroidChart:v2.2.5' +} diff --git a/app/proguard-butterknife-7.pro b/app/proguard-butterknife-7.pro new file mode 100644 index 0000000..a04d9bc --- /dev/null +++ b/app/proguard-butterknife-7.pro @@ -0,0 +1,13 @@ +# ButterKnife 7 + +-keep class butterknife.** { *; } +-dontwarn butterknife.internal.** +-keep class **$$ViewBinder { *; } + +-keepclasseswithmembernames class * { + @butterknife.* ; +} + +-keepclasseswithmembernames class * { + @butterknife.* ; +} \ No newline at end of file diff --git a/app/proguard-google-play-services.pro b/app/proguard-google-play-services.pro new file mode 100644 index 0000000..ce55733 --- /dev/null +++ b/app/proguard-google-play-services.pro @@ -0,0 +1,19 @@ +## Google Play Services 4.3.23 specific rules ## +## https://developer.android.com/google/play-services/setup.html#Proguard ## + +-keep class * extends java.util.ListResourceBundle { + protected Object[][] getContents(); +} + +-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable { + public static final *** NULL; +} + +-keepnames @com.google.android.gms.common.annotation.KeepName class * +-keepclassmembernames class * { + @com.google.android.gms.common.annotation.KeepName *; +} + +-keepnames class * implements android.os.Parcelable { + public static final ** CREATOR; +} diff --git a/app/proguard-guava.pro b/app/proguard-guava.pro new file mode 100644 index 0000000..898255b --- /dev/null +++ b/app/proguard-guava.pro @@ -0,0 +1,31 @@ +# Configuration for Guava 18.0 +# +# disagrees with instructions provided by Guava project: https://code.google.com/p/guava-libraries/wiki/UsingProGuardWithGuava + +-keep class com.google.common.io.Resources { + public static ; +} +-keep class com.google.common.collect.Lists { + public static ** reverse(**); +} +-keep class com.google.common.base.Charsets { + public static ; +} + +-keep class com.google.common.base.Joiner { + public static com.google.common.base.Joiner on(java.lang.String); + public ** join(...); +} + +-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry +-keep class com.google.common.cache.LocalCache$ReferenceEntry + +# http://stackoverflow.com/questions/9120338/proguard-configuration-for-guava-with-obfuscation-and-optimization +-dontwarn javax.annotation.** +-dontwarn javax.inject.** +-dontwarn sun.misc.Unsafe + +# Guava 19.0 +-dontwarn java.lang.ClassValue +-dontwarn com.google.j2objc.annotations.Weak +-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..b29c183 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,26 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/silver/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + + +-assumenosideeffects class java.util.logging.Logger { + public *** log(...); +} + +-keep class com.github.mikephil.charting.** { *; } + +-dontwarn io.realm.** diff --git a/app/proguard-square-okhttp3.pro b/app/proguard-square-okhttp3.pro new file mode 100644 index 0000000..64e6852 --- /dev/null +++ b/app/proguard-square-okhttp3.pro @@ -0,0 +1,6 @@ +# OkHttp +-keepattributes Signature +-keepattributes *Annotation* +-keep class okhttp3.** { *; } +-keep interface okhttp3.** { *; } +-dontwarn okhttp3.** \ No newline at end of file diff --git a/app/proguard-square-okio.pro b/app/proguard-square-okio.pro new file mode 100644 index 0000000..589e679 --- /dev/null +++ b/app/proguard-square-okio.pro @@ -0,0 +1,5 @@ +# Okio +-keep class sun.misc.Unsafe { *; } +-dontwarn java.nio.file.* +-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement +-dontwarn okio.** \ No newline at end of file diff --git a/app/proguard-support-v7-appcompat.pro b/app/proguard-support-v7-appcompat.pro new file mode 100644 index 0000000..65068d0 --- /dev/null +++ b/app/proguard-support-v7-appcompat.pro @@ -0,0 +1,7 @@ +-keep public class android.support.v7.widget.** { *; } +-keep public class android.support.v7.internal.widget.** { *; } +-keep public class android.support.v7.internal.view.menu.** { *; } + +-keep public class * extends android.support.v4.view.ActionProvider { + public (android.content.Context); +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1d2192d --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/udacity/stockhawk/StockHawkApp.java b/app/src/main/java/com/udacity/stockhawk/StockHawkApp.java new file mode 100644 index 0000000..8218e56 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/StockHawkApp.java @@ -0,0 +1,18 @@ +package com.udacity.stockhawk; + +import android.app.Application; + +import timber.log.Timber; + +public class StockHawkApp extends Application { + + @Override + public void onCreate() { + super.onCreate(); + + if (BuildConfig.DEBUG) { + Timber.uprootAll(); + Timber.plant(new Timber.DebugTree()); + } + } +} diff --git a/app/src/main/java/com/udacity/stockhawk/data/Contract.java b/app/src/main/java/com/udacity/stockhawk/data/Contract.java new file mode 100644 index 0000000..c6402bf --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/data/Contract.java @@ -0,0 +1,56 @@ +package com.udacity.stockhawk.data; + + +import android.net.Uri; +import android.provider.BaseColumns; + +public class Contract { + + public static final String AUTHORITY = "com.udacity.stockhawk"; + + public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY); + + public static final String PATH_QUOTE = "quote"; + public static final String PATH_QUOTE_WITH_SYMBOL = "quote/*"; + + public static final class Quote implements BaseColumns { + + public static final Uri uri = BASE_URI.buildUpon().appendPath(PATH_QUOTE).build(); + + public static final String TABLE_NAME = "quotes"; + + public static final String COLUMN_SYMBOL = "symbol"; + public static final String COLUMN_PRICE = "price"; + public static final String COLUMN_ABSOLUTE_CHANGE = "absolute_change"; + public static final String COLUMN_PERCENTAGE_CHANGE = "percentage_change"; + public static final String COLUMN_HISTORY = "history"; + + + public static final int POSITION_ID = 0; + public static final int POSITION_SYMBOL = 1; + public static final int POSITION_PRICE = 2; + public static final int POSITION_ABSOLUTE_CHANGE = 3; + public static final int POSITION_PERCENTAGE_CHANGE = 4; + public static final int POSITION_HISTORY = 5; + + public static final String[] QUOTE_COLUMNS = { + _ID, + COLUMN_SYMBOL, + COLUMN_PRICE, + COLUMN_ABSOLUTE_CHANGE, + COLUMN_PERCENTAGE_CHANGE, + COLUMN_HISTORY + }; + + public static Uri makeUriForStock(String symbol) { + return uri.buildUpon().appendPath(symbol).build(); + } + + public static String getStockFromUri(Uri uri) { + return uri.getLastPathSegment(); + } + + + } + +} diff --git a/app/src/main/java/com/udacity/stockhawk/data/DbHelper.java b/app/src/main/java/com/udacity/stockhawk/data/DbHelper.java new file mode 100644 index 0000000..522798a --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/data/DbHelper.java @@ -0,0 +1,43 @@ +package com.udacity.stockhawk.data; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import com.udacity.stockhawk.data.Contract.Quote; + + +public class DbHelper extends SQLiteOpenHelper { + + + static final String NAME = "StockHawk.db"; + private static final int VERSION = 1; + + + public DbHelper(Context context) { + super(context, NAME, null, VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + String builder = "CREATE TABLE " + Quote.TABLE_NAME + " (" + + Quote._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + Quote.COLUMN_SYMBOL + " TEXT NOT NULL, " + + Quote.COLUMN_PRICE + " REAL NOT NULL, " + + Quote.COLUMN_ABSOLUTE_CHANGE + " REAL NOT NULL, " + + Quote.COLUMN_PERCENTAGE_CHANGE + " REAL NOT NULL, " + + Quote.COLUMN_HISTORY + " TEXT NOT NULL, " + + "UNIQUE (" + Quote.COLUMN_SYMBOL + ") ON CONFLICT REPLACE);"; + + db.execSQL(builder); + + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + db.execSQL(" DROP TABLE IF EXISTS " + Quote.TABLE_NAME); + + onCreate(db); + } +} diff --git a/app/src/main/java/com/udacity/stockhawk/data/PrefUtils.java b/app/src/main/java/com/udacity/stockhawk/data/PrefUtils.java new file mode 100644 index 0000000..6fc8e9a --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/data/PrefUtils.java @@ -0,0 +1,91 @@ +package com.udacity.stockhawk.data; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; + +import com.udacity.stockhawk.R; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public final class PrefUtils { + + private PrefUtils() { + } + + public static Set getStocks(Context context) { + String stocksKey = context.getString(R.string.pref_stocks_key); + String initializedKey = context.getString(R.string.pref_stocks_initialized_key); + String[] defaultStocksList = context.getResources().getStringArray(R.array.default_stocks); + + HashSet defaultStocks = new HashSet<>(Arrays.asList(defaultStocksList)); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + + + boolean initialized = prefs.getBoolean(initializedKey, false); + + if (!initialized) { + SharedPreferences.Editor editor = prefs.edit(); + editor.putBoolean(initializedKey, true); + editor.putStringSet(stocksKey, defaultStocks); + editor.apply(); + return defaultStocks; + } + return prefs.getStringSet(stocksKey, new HashSet()); + + } + + public static void editStockPref(Context context, String symbol, Boolean add) { + String key = context.getString(R.string.pref_stocks_key); + Set stocks = getStocks(context); + + if (add) { + stocks.add(symbol); + } else { + stocks.remove(symbol); + } + + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + SharedPreferences.Editor editor = prefs.edit(); + editor.putStringSet(key, stocks); + editor.apply(); + } + + public static void addStock(Context context, String symbol) { + editStockPref(context, symbol, true); + } + + public static void removeStock(Context context, String symbol) { + editStockPref(context, symbol, false); + } + + public static String getDisplayMode(Context context) { + String key = context.getString(R.string.pref_display_mode_key); + String defaultValue = context.getString(R.string.pref_display_mode_default); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + return prefs.getString(key, defaultValue); + } + + public static void toggleDisplayMode(Context context) { + String key = context.getString(R.string.pref_display_mode_key); + String absoluteKey = context.getString(R.string.pref_display_mode_absolute_key); + String percentageKey = context.getString(R.string.pref_display_mode_percentage_key); + + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + + String displayMode = getDisplayMode(context); + + SharedPreferences.Editor editor = prefs.edit(); + + if (displayMode.equals(absoluteKey)) { + editor.putString(key, percentageKey); + } else { + editor.putString(key, absoluteKey); + } + + editor.apply(); + } + +} diff --git a/app/src/main/java/com/udacity/stockhawk/data/StockProvider.java b/app/src/main/java/com/udacity/stockhawk/data/StockProvider.java new file mode 100644 index 0000000..8060d12 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/data/StockProvider.java @@ -0,0 +1,179 @@ +package com.udacity.stockhawk.data; + +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.UriMatcher; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.net.Uri; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; + + +public class StockProvider extends ContentProvider { + + static final int QUOTE = 100; + static final int QUOTE_FOR_SYMBOL = 101; + + static UriMatcher uriMatcher = buildUriMatcher(); + + private DbHelper dbHelper; + + static UriMatcher buildUriMatcher() { + UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); + matcher.addURI(Contract.AUTHORITY, Contract.PATH_QUOTE, QUOTE); + matcher.addURI(Contract.AUTHORITY, Contract.PATH_QUOTE_WITH_SYMBOL, QUOTE_FOR_SYMBOL); + return matcher; + } + + + @Override + public boolean onCreate() { + dbHelper = new DbHelper(getContext()); + return true; + } + + @Nullable + @Override + public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + Cursor returnCursor; + SQLiteDatabase db = dbHelper.getReadableDatabase(); + + switch (uriMatcher.match(uri)) { + case QUOTE: + returnCursor = db.query( + Contract.Quote.TABLE_NAME, + projection, + selection, + selectionArgs, + null, + null, + sortOrder + ); + break; + + case QUOTE_FOR_SYMBOL: + returnCursor = db.query( + Contract.Quote.TABLE_NAME, + projection, + Contract.Quote.COLUMN_SYMBOL + " = ?", + new String[]{Contract.Quote.getStockFromUri(uri)}, + null, + null, + sortOrder + ); + + break; + default: + throw new UnsupportedOperationException("Unknown URI:" + uri); + } + + returnCursor.setNotificationUri(getContext().getContentResolver(), uri); + +// if (db.isOpen()) { +// db.close(); +// } + + return returnCursor; + } + + @Nullable + @Override + public String getType(Uri uri) { + return null; + } + + @Nullable + @Override + public Uri insert(@NonNull Uri uri, ContentValues values) { + SQLiteDatabase db = dbHelper.getWritableDatabase(); + Uri returnUri; + + switch (uriMatcher.match(uri)) { + case QUOTE: + db.insert( + Contract.Quote.TABLE_NAME, + null, + values + ); + returnUri = Contract.Quote.uri; + break; + default: + throw new UnsupportedOperationException("Unknown URI:" + uri); + } + + getContext().getContentResolver().notifyChange(uri, null); + + + return returnUri; + } + + @Override + public int delete(Uri uri, String selection, String[] selectionArgs) { + final SQLiteDatabase db = dbHelper.getWritableDatabase(); + int rowsDeleted; + + if (null == selection) selection = "1"; + switch (uriMatcher.match(uri)) { + case QUOTE: + rowsDeleted = db.delete( + Contract.Quote.TABLE_NAME, + selection, + selectionArgs + ); + + break; + + case QUOTE_FOR_SYMBOL: + String symbol = Contract.Quote.getStockFromUri(uri); + rowsDeleted = db.delete( + Contract.Quote.TABLE_NAME, + '"' + symbol + '"' + " =" + Contract.Quote.COLUMN_SYMBOL, + selectionArgs + ); + break; + default: + throw new UnsupportedOperationException("Unknown URI:" + uri); + } + + if (rowsDeleted != 0) { + getContext().getContentResolver().notifyChange(uri, null); + } + return rowsDeleted; + } + + @Override + public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { + return 0; + } + + @Override + public int bulkInsert(Uri uri, ContentValues[] values) { + + final SQLiteDatabase db = dbHelper.getWritableDatabase(); + + switch (uriMatcher.match(uri)) { + case QUOTE: + db.beginTransaction(); + int returnCount = 0; + try { + for (ContentValues value : values) { + db.insert( + Contract.Quote.TABLE_NAME, + null, + value + ); + } + db.setTransactionSuccessful(); + } finally { + db.endTransaction(); + } + getContext().getContentResolver().notifyChange(uri, null); + return returnCount; + default: + return super.bulkInsert(uri, values); + } + + + } +} diff --git a/app/src/main/java/com/udacity/stockhawk/sync/QuoteIntentService.java b/app/src/main/java/com/udacity/stockhawk/sync/QuoteIntentService.java new file mode 100644 index 0000000..42bea9b --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/sync/QuoteIntentService.java @@ -0,0 +1,20 @@ +package com.udacity.stockhawk.sync; + +import android.app.IntentService; +import android.content.Intent; + +import timber.log.Timber; + + +public class QuoteIntentService extends IntentService { + + public QuoteIntentService() { + super(QuoteIntentService.class.getSimpleName()); + } + + @Override + protected void onHandleIntent(Intent intent) { + Timber.d("Intent handled"); + QuoteSyncJob.getQuotes(getApplicationContext()); + } +} diff --git a/app/src/main/java/com/udacity/stockhawk/sync/QuoteJobService.java b/app/src/main/java/com/udacity/stockhawk/sync/QuoteJobService.java new file mode 100644 index 0000000..7b06cf1 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/sync/QuoteJobService.java @@ -0,0 +1,26 @@ +package com.udacity.stockhawk.sync; + +import android.app.job.JobParameters; +import android.app.job.JobService; +import android.content.Intent; + +import timber.log.Timber; + +public class QuoteJobService extends JobService { + + + @Override + public boolean onStartJob(JobParameters jobParameters) { + Timber.d("Intent handled"); + Intent nowIntent = new Intent(getApplicationContext(), QuoteIntentService.class); + getApplicationContext().startService(nowIntent); + return true; + } + + @Override + public boolean onStopJob(JobParameters jobParameters) { + return false; + } + + +} diff --git a/app/src/main/java/com/udacity/stockhawk/sync/QuoteSyncJob.java b/app/src/main/java/com/udacity/stockhawk/sync/QuoteSyncJob.java new file mode 100644 index 0000000..c6a3725 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/sync/QuoteSyncJob.java @@ -0,0 +1,168 @@ +package com.udacity.stockhawk.sync; + +import android.app.job.JobInfo; +import android.app.job.JobScheduler; +import android.content.ComponentName; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; + +import com.udacity.stockhawk.data.Contract; +import com.udacity.stockhawk.data.PrefUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import timber.log.Timber; +import yahoofinance.Stock; +import yahoofinance.YahooFinance; +import yahoofinance.histquotes.HistoricalQuote; +import yahoofinance.histquotes.Interval; +import yahoofinance.quotes.stock.StockQuote; + +public final class QuoteSyncJob { + + static final int ONE_OFF_ID = 2; + private static final String ACTION_DATA_UPDATED = "com.udacity.stockhawk.ACTION_DATA_UPDATED"; + private static final int PERIOD = 300000; + private static final int INITIAL_BACKOFF = 10000; + private static final int PERIODIC_ID = 1; + + static void getQuotes(Context context) { + + Timber.d("Running sync job"); + + Calendar from = Calendar.getInstance(); + Calendar to = Calendar.getInstance(); + from.add(Calendar.YEAR, -2); + + try { + + Set stockPref = PrefUtils.getStocks(context); + Set stockCopy = new HashSet<>(); + stockCopy.addAll(stockPref); + String[] stockArray = stockPref.toArray(new String[stockPref.size()]); + + Timber.d(stockCopy.toString()); + + if (stockArray.length == 0) { + return; + } + + Map quotes = YahooFinance.get(stockArray); + Iterator iterator = stockCopy.iterator(); + + Timber.d(quotes.toString()); + + ArrayList quoteCVs = new ArrayList<>(); + + while (iterator.hasNext()) { + String symbol = iterator.next(); + + + Stock stock = quotes.get(symbol); + StockQuote quote = stock.getQuote(); + + float price = quote.getPrice().floatValue(); + float change = quote.getChange().floatValue(); + float percentChange = quote.getChangeInPercent().floatValue(); + + // WARNING! Don't request historical data for a stock that doesn't exist! + // The request will hang forever X_x + List history = stock.getHistory(from, to, Interval.WEEKLY); + + StringBuilder historyBuilder = new StringBuilder(); + + for (HistoricalQuote it : history) { + historyBuilder.append(it.getDate().getTimeInMillis()); + historyBuilder.append(", "); + historyBuilder.append(it.getClose()); + historyBuilder.append("\n"); + } + + ContentValues quoteCV = new ContentValues(); + quoteCV.put(Contract.Quote.COLUMN_SYMBOL, symbol); + quoteCV.put(Contract.Quote.COLUMN_PRICE, price); + quoteCV.put(Contract.Quote.COLUMN_PERCENTAGE_CHANGE, percentChange); + quoteCV.put(Contract.Quote.COLUMN_ABSOLUTE_CHANGE, change); + + + quoteCV.put(Contract.Quote.COLUMN_HISTORY, historyBuilder.toString()); + + quoteCVs.add(quoteCV); + + } + + context.getContentResolver() + .bulkInsert( + Contract.Quote.uri, + quoteCVs.toArray(new ContentValues[quoteCVs.size()])); + + Intent dataUpdatedIntent = new Intent(ACTION_DATA_UPDATED); + context.sendBroadcast(dataUpdatedIntent); + + } catch (IOException exception) { + Timber.e(exception, "Error fetching stock quotes"); + } + } + + private static void schedulePeriodic(Context context) { + Timber.d("Scheduling a periodic task"); + + + JobInfo.Builder builder = new JobInfo.Builder(PERIODIC_ID, new ComponentName(context, QuoteJobService.class)); + + + builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) + .setPeriodic(PERIOD) + .setBackoffCriteria(INITIAL_BACKOFF, JobInfo.BACKOFF_POLICY_EXPONENTIAL); + + + JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + + scheduler.schedule(builder.build()); + } + + + synchronized public static void initialize(final Context context) { + + schedulePeriodic(context); + syncImmediately(context); + + } + + synchronized public static void syncImmediately(Context context) { + + ConnectivityManager cm = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = cm.getActiveNetworkInfo(); + if (networkInfo != null && networkInfo.isConnectedOrConnecting()) { + Intent nowIntent = new Intent(context, QuoteIntentService.class); + context.startService(nowIntent); + } else { + + JobInfo.Builder builder = new JobInfo.Builder(ONE_OFF_ID, new ComponentName(context, QuoteJobService.class)); + + + builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) + .setBackoffCriteria(INITIAL_BACKOFF, JobInfo.BACKOFF_POLICY_EXPONENTIAL); + + + JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + + scheduler.schedule(builder.build()); + + + } + } + + +} diff --git a/app/src/main/java/com/udacity/stockhawk/ui/AddStockDialog.java b/app/src/main/java/com/udacity/stockhawk/ui/AddStockDialog.java new file mode 100644 index 0000000..eaf0c29 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/ui/AddStockDialog.java @@ -0,0 +1,69 @@ +package com.udacity.stockhawk.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.DialogInterface; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.TextView; + +import com.udacity.stockhawk.R; + +import butterknife.BindView; +import butterknife.ButterKnife; + + +public class AddStockDialog extends DialogFragment { + + @BindView(R.id.dialog_stock) + EditText stock; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + + LayoutInflater inflater = LayoutInflater.from(getActivity()); + View custom = inflater.inflate(R.layout.add_stock_dialog, null); + + ButterKnife.bind(this, custom); + + stock.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + addStock(); + return true; + } + }); + builder.setView(custom); + + builder.setMessage(getString(R.string.dialog_title)); + builder.setPositiveButton(getString(R.string.dialog_add), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + addStock(); + } + }); + builder.setNegativeButton(getString(R.string.dialog_cancel), null); + + Dialog dialog = builder.create(); + dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + return dialog; + } + + private void addStock() { + Activity parent = getActivity(); + if (parent instanceof MainActivity) { + ((MainActivity) parent).addStock(stock.getText().toString()); + } + dismissAllowingStateLoss(); + } + + +} diff --git a/app/src/main/java/com/udacity/stockhawk/ui/MainActivity.java b/app/src/main/java/com/udacity/stockhawk/ui/MainActivity.java new file mode 100644 index 0000000..3a53096 --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/ui/MainActivity.java @@ -0,0 +1,190 @@ +package com.udacity.stockhawk.ui; + +import android.content.Context; +import android.database.Cursor; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.support.design.widget.FloatingActionButton; +import android.support.v4.app.LoaderManager; +import android.support.v4.content.CursorLoader; +import android.support.v4.content.Loader; +import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.helper.ItemTouchHelper; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import com.udacity.stockhawk.R; +import com.udacity.stockhawk.data.Contract; +import com.udacity.stockhawk.data.PrefUtils; +import com.udacity.stockhawk.sync.QuoteSyncJob; + +import butterknife.BindView; +import butterknife.ButterKnife; +import timber.log.Timber; + +public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks, + SwipeRefreshLayout.OnRefreshListener, + StockAdapter.StockAdapterOnClickHandler { + + private static final int STOCK_LOADER = 0; + @BindView(R.id.recycler_view) + RecyclerView recyclerView; + @BindView(R.id.fab) + FloatingActionButton fab; + @BindView(R.id.swipe_refresh) + SwipeRefreshLayout swipeRefreshLayout; + @BindView(R.id.error) + TextView error; + private StockAdapter adapter; + + @Override + public void onClick(String symbol) { + Timber.d("Symbol clicked: %s", symbol); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_main); + ButterKnife.bind(this); + + adapter = new StockAdapter(this, this); + recyclerView.setAdapter(adapter); + recyclerView.setLayoutManager(new LinearLayoutManager(this)); + + swipeRefreshLayout.setOnRefreshListener(this); + swipeRefreshLayout.setRefreshing(true); + onRefresh(); + + QuoteSyncJob.initialize(this); + getSupportLoaderManager().initLoader(STOCK_LOADER, null, this); + + new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { + @Override + public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { + return false; + } + + @Override + public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { + String symbol = adapter.getSymbolAtPosition(viewHolder.getAdapterPosition()); + PrefUtils.removeStock(MainActivity.this, symbol); + getContentResolver().delete(Contract.Quote.makeUriForStock(symbol), null, null); + } + }).attachToRecyclerView(recyclerView); + + + } + + private boolean networkUp() { + ConnectivityManager cm = + (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = cm.getActiveNetworkInfo(); + return networkInfo != null && networkInfo.isConnectedOrConnecting(); + } + + @Override + public void onRefresh() { + + QuoteSyncJob.syncImmediately(this); + + if (!networkUp() && adapter.getItemCount() == 0) { + swipeRefreshLayout.setRefreshing(false); + error.setText(getString(R.string.error_no_network)); + error.setVisibility(View.VISIBLE); + } else if (!networkUp()) { + swipeRefreshLayout.setRefreshing(false); + Toast.makeText(this, R.string.toast_no_connectivity, Toast.LENGTH_LONG).show(); + } else if (PrefUtils.getStocks(this).size() == 0) { + Timber.d("WHYAREWEHERE"); + swipeRefreshLayout.setRefreshing(false); + error.setText(getString(R.string.error_no_stocks)); + error.setVisibility(View.VISIBLE); + } else { + error.setVisibility(View.GONE); + } + } + + public void button(View view) { + new AddStockDialog().show(getFragmentManager(), "StockDialogFragment"); + } + + void addStock(String symbol) { + if (symbol != null && !symbol.isEmpty()) { + + if (networkUp()) { + swipeRefreshLayout.setRefreshing(true); + } else { + String message = getString(R.string.toast_stock_added_no_connectivity, symbol); + Toast.makeText(this, message, Toast.LENGTH_LONG).show(); + } + + PrefUtils.addStock(this, symbol); + QuoteSyncJob.syncImmediately(this); + } + } + + @Override + public Loader onCreateLoader(int id, Bundle args) { + return new CursorLoader(this, + Contract.Quote.uri, + Contract.Quote.QUOTE_COLUMNS, + null, null, Contract.Quote.COLUMN_SYMBOL); + } + + @Override + public void onLoadFinished(Loader loader, Cursor data) { + swipeRefreshLayout.setRefreshing(false); + + if (data.getCount() != 0) { + error.setVisibility(View.GONE); + } + adapter.setCursor(data); + } + + + @Override + public void onLoaderReset(Loader loader) { + swipeRefreshLayout.setRefreshing(false); + adapter.setCursor(null); + } + + + private void setDisplayModeMenuItemIcon(MenuItem item) { + if (PrefUtils.getDisplayMode(this) + .equals(getString(R.string.pref_display_mode_absolute_key))) { + item.setIcon(R.drawable.ic_percentage); + } else { + item.setIcon(R.drawable.ic_dollar); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main_activity_settings, menu); + MenuItem item = menu.findItem(R.id.action_change_units); + setDisplayModeMenuItemIcon(item); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.action_change_units) { + PrefUtils.toggleDisplayMode(this); + setDisplayModeMenuItemIcon(item); + adapter.notifyDataSetChanged(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/com/udacity/stockhawk/ui/StockAdapter.java b/app/src/main/java/com/udacity/stockhawk/ui/StockAdapter.java new file mode 100644 index 0000000..75a916e --- /dev/null +++ b/app/src/main/java/com/udacity/stockhawk/ui/StockAdapter.java @@ -0,0 +1,138 @@ +package com.udacity.stockhawk.ui; + + +import android.content.Context; +import android.database.Cursor; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.udacity.stockhawk.R; +import com.udacity.stockhawk.data.Contract; +import com.udacity.stockhawk.data.PrefUtils; + +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Locale; + +import butterknife.BindView; +import butterknife.ButterKnife; + +class StockAdapter extends RecyclerView.Adapter { + + final private Context context; + final private DecimalFormat dollarFormatWithPlus; + final private DecimalFormat dollarFormat; + final private DecimalFormat percentageFormat; + private Cursor cursor; + private StockAdapterOnClickHandler clickHandler; + + StockAdapter(Context context, StockAdapterOnClickHandler clickHandler) { + this.context = context; + this.clickHandler = clickHandler; + + dollarFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US); + dollarFormatWithPlus = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.US); + dollarFormatWithPlus.setPositivePrefix("+$"); + percentageFormat = (DecimalFormat) NumberFormat.getPercentInstance(Locale.getDefault()); + percentageFormat.setMaximumFractionDigits(2); + percentageFormat.setMinimumFractionDigits(2); + percentageFormat.setPositivePrefix("+"); + } + + void setCursor(Cursor cursor) { + this.cursor = cursor; + notifyDataSetChanged(); + } + + String getSymbolAtPosition(int position) { + + cursor.moveToPosition(position); + return cursor.getString(Contract.Quote.POSITION_SYMBOL); + } + + @Override + public StockViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + + View item = LayoutInflater.from(context).inflate(R.layout.list_item_quote, parent, false); + + return new StockViewHolder(item); + } + + @Override + public void onBindViewHolder(StockViewHolder holder, int position) { + + cursor.moveToPosition(position); + + + holder.symbol.setText(cursor.getString(Contract.Quote.POSITION_SYMBOL)); + holder.price.setText(dollarFormat.format(cursor.getFloat(Contract.Quote.POSITION_PRICE))); + + + float rawAbsoluteChange = cursor.getFloat(Contract.Quote.POSITION_ABSOLUTE_CHANGE); + float percentageChange = cursor.getFloat(Contract.Quote.POSITION_PERCENTAGE_CHANGE); + + if (rawAbsoluteChange > 0) { + holder.change.setBackgroundResource(R.drawable.percent_change_pill_green); + } else { + holder.change.setBackgroundResource(R.drawable.percent_change_pill_red); + } + + String change = dollarFormatWithPlus.format(rawAbsoluteChange); + String percentage = percentageFormat.format(percentageChange / 100); + + if (PrefUtils.getDisplayMode(context) + .equals(context.getString(R.string.pref_display_mode_absolute_key))) { + holder.change.setText(change); + } else { + holder.change.setText(percentage); + } + + + } + + @Override + public int getItemCount() { + int count = 0; + if (cursor != null) { + count = cursor.getCount(); + } + return count; + } + + + interface StockAdapterOnClickHandler { + void onClick(String symbol); + } + + class StockViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + + @BindView(R.id.symbol) + TextView symbol; + + @BindView(R.id.price) + TextView price; + + @BindView(R.id.change) + TextView change; + + StockViewHolder(View itemView) { + super(itemView); + ButterKnife.bind(this, itemView); + itemView.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + int adapterPosition = getAdapterPosition(); + cursor.moveToPosition(adapterPosition); + int symbolColumn = cursor.getColumnIndex(Contract.Quote.COLUMN_SYMBOL); + clickHandler.onClick(cursor.getString(symbolColumn)); + + } + + + } +} diff --git a/app/src/main/res/drawable-hdpi/ic_dollar.png b/app/src/main/res/drawable-hdpi/ic_dollar.png new file mode 100644 index 0000000..3f3e34d Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_dollar.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_percentage.png b/app/src/main/res/drawable-hdpi/ic_percentage.png new file mode 100644 index 0000000..36caaf5 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_percentage.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_dollar.png b/app/src/main/res/drawable-mdpi/ic_dollar.png new file mode 100644 index 0000000..6cd6bae Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_dollar.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_percentage.png b/app/src/main/res/drawable-mdpi/ic_percentage.png new file mode 100644 index 0000000..7bdfa16 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_percentage.png differ diff --git a/app/src/main/res/drawable-nodpi/stocks_widget_preview.png b/app/src/main/res/drawable-nodpi/stocks_widget_preview.png new file mode 100644 index 0000000..1e14629 Binary files /dev/null and b/app/src/main/res/drawable-nodpi/stocks_widget_preview.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_dollar.png b/app/src/main/res/drawable-xhdpi/ic_dollar.png new file mode 100644 index 0000000..c4eef5a Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_dollar.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_percentage.png b/app/src/main/res/drawable-xhdpi/ic_percentage.png new file mode 100644 index 0000000..7a57f1e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_percentage.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_dollar.png b/app/src/main/res/drawable-xxhdpi/ic_dollar.png new file mode 100644 index 0000000..0236dbe Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_dollar.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_percentage.png b/app/src/main/res/drawable-xxhdpi/ic_percentage.png new file mode 100644 index 0000000..d9e7610 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_percentage.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_dollar.png b/app/src/main/res/drawable-xxxhdpi/ic_dollar.png new file mode 100644 index 0000000..4ae2e17 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_dollar.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_percentage.png b/app/src/main/res/drawable-xxxhdpi/ic_percentage.png new file mode 100644 index 0000000..09d857d Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_percentage.png differ diff --git a/app/src/main/res/drawable/fab_plus.xml b/app/src/main/res/drawable/fab_plus.xml new file mode 100644 index 0000000..7a65b19 --- /dev/null +++ b/app/src/main/res/drawable/fab_plus.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/percent_change_pill_green.xml b/app/src/main/res/drawable/percent_change_pill_green.xml new file mode 100644 index 0000000..027c6a5 --- /dev/null +++ b/app/src/main/res/drawable/percent_change_pill_green.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/percent_change_pill_red.xml b/app/src/main/res/drawable/percent_change_pill_red.xml new file mode 100644 index 0000000..e5ce5f3 --- /dev/null +++ b/app/src/main/res/drawable/percent_change_pill_red.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..40f6e87 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/add_stock_dialog.xml b/app/src/main/res/layout/add_stock_dialog.xml new file mode 100644 index 0000000..7a54cc8 --- /dev/null +++ b/app/src/main/res/layout/add_stock_dialog.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/layout/list_item_quote.xml b/app/src/main/res/layout/list_item_quote.xml new file mode 100644 index 0000000..91c5d51 --- /dev/null +++ b/app/src/main/res/layout/list_item_quote.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + diff --git a/app/src/main/res/menu/main_activity_settings.xml b/app/src/main/res/menu/main_activity_settings.xml new file mode 100644 index 0000000..1d7e021 --- /dev/null +++ b/app/src/main/res/menu/main_activity_settings.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..cde69bc Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..c133a0c Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..bfa42f0 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..324e72c Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..aee44e1 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml new file mode 100644 index 0000000..6ee83c5 --- /dev/null +++ b/app/src/main/res/values/arrays.xml @@ -0,0 +1,9 @@ + + + + @string/default_stocks_apple + @string/default_stocks_yahoo + @string/default_stocks_microsoft + @string/default_stocks_facebook + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..756a300 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,13 @@ + + + #3F51B5 + #303F9F + #FF4081 + + + #1976D2 + #2196F3 + #D50000 + #00C853 + + diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..fe991af --- /dev/null +++ b/app/src/main/res/values/dimens.xml @@ -0,0 +1,4 @@ + + 16dp + 16dp + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..910735b --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,39 @@ + + Stock Hawk + + initialized + + stocks + + No data + + + Display Mode + displayMode + @string/pref_display_mode_percentage_key + + absolute + percentage + + YHOO + AAPL + MSFT + FB + + + @string/pref_display_mode_key + + + Add Stock + Symbol (e.g. GOOG) + Cancel + Add + + Symbol %s is invalid! + No network connectivity! Will load stock cursor when the network is available. + No stocks added! Hit the floating action button to add one. + + Symbol %s added. Will refresh when network available. + Will refresh when network available. + + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..29570a4 --- /dev/null +++ b/app/src/main/res/values/styles.xml @@ -0,0 +1,23 @@ + + + + + + + + + + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..6ed72f0 --- /dev/null +++ b/build.gradle @@ -0,0 +1,23 @@ +apply plugin: 'com.github.ben-manes.versions' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.2.2' + classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' + classpath 'com.github.ben-manes:gradle-versions-plugin:0.12.0' + classpath 'com.noveogroup.android:check:1.2.3' + } +} + +allprojects { + repositories { + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..1d3591c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..9aa616c --- /dev/null +++ b/gradlew @@ -0,0 +1,169 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..e7b4def --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':app'