From 817d9d0e113bec806a3480f6ac1f40ddbb30c6b8 Mon Sep 17 00:00:00 2001 From: Petr Nohejl Date: Thu, 5 Jul 2018 11:07:50 +0200 Subject: [PATCH] Reformat code with K&R code style --- Base/mobile/build.gradle | 6 +- Base/utils.gradle | 9 +- .../Src-APICall/java/client/APICall.java | 153 +++++--------- .../java/client/APICallListener.java | 4 +- .../java/client/APICallManager.java | 69 ++----- .../Src-APICall/java/client/APICallTask.java | 70 ++----- .../java/client/ResponseStatus.java | 24 +-- .../java/client/parser/ExampleParser.java | 56 ++--- .../java/client/parser/Parser.java | 17 +- .../java/client/request/ExampleRequest.java | 39 +--- .../java/client/request/MultipartRequest.java | 45 ++-- .../java/client/request/Request.java | 29 +-- .../java/client/response/Response.java | 40 +--- .../java/fragment/ExampleFragment.java | 154 +++++--------- .../java/fragment/ExampleFragment.java | 12 +- .../java/ExampleApplication.java | 16 +- .../java/database/dao/DAO.java | 4 +- .../java/database/dao/ProductDAO.java | 41 +--- .../java/database/model/ProductModel.java | 16 +- .../database/query/ProductCreateQuery.java | 12 +- .../database/query/ProductDeleteAllQuery.java | 11 +- .../database/query/ProductDeleteQuery.java | 12 +- .../database/query/ProductReadAllQuery.java | 23 +-- .../database/query/ProductReadFirstQuery.java | 11 +- .../java/database/query/ProductReadQuery.java | 12 +- .../database/query/ProductUpdateQuery.java | 12 +- .../java/database/query/Query.java | 13 +- .../java/fragment/ExampleFragment.java | 126 ++++-------- .../java/database/DatabaseCallListener.java | 4 +- .../java/database/DatabaseCallManager.java | 55 ++--- .../java/database/DatabaseCallTask.java | 49 ++--- .../java/database/DatabaseHelper.java | 66 ++---- .../java/database/dao/DAO.java | 14 +- .../java/database/dao/ProductDAO.java | 42 +--- .../java/database/data/Data.java | 16 +- .../java/database/model/ProductModel.java | 56 ++--- .../database/query/ProductCreateQuery.java | 12 +- .../database/query/ProductDeleteAllQuery.java | 11 +- .../database/query/ProductDeleteQuery.java | 12 +- .../database/query/ProductReadAllQuery.java | 16 +- .../java/database/query/ProductReadQuery.java | 12 +- .../database/query/ProductUpdateQuery.java | 12 +- .../java/database/query/Query.java | 13 +- .../java/entity/ProductEntity.java | 54 ++--- .../java/fragment/ExampleFragment.java | 114 +++------- .../java/dialog/ExampleDialogFragment.java | 38 +--- .../java/utility/DialogStyle.java | 68 +++--- .../selector_dialog_button_text_dark.xml | 15 +- .../selector_dialog_button_text_light.xml | 15 +- .../java/activity/ExampleActivity.java | 55 ++--- .../java/gcm/GcmBroadcastReceiver.java | 7 +- .../Src-GCM/java/gcm/GcmIntentService.java | 40 ++-- Deprecated/Src-GCM/java/gcm/GcmUtility.java | 112 +++------- .../java/fragment/ExampleFragment.java | 45 ++-- .../java/geolocation/Geolocation.java | 88 +++----- .../java/geolocation/GeolocationListener.java | 4 +- .../java/ExampleApplication.java | 23 +-- .../java/fragment/ExampleFragment.java | 20 +- .../java/graphics/FadeInBitmapDisplayer.java | 27 +-- .../listener/AnimateImageLoadingListener.java | 14 +- .../drawable/selector_selectable_item_bg.xml | 7 +- .../java/activity/ExampleActivity.java | 23 +-- .../java/activity/ExampleActivity.java | 19 +- .../ActionBarListNavigationAdapter.java | 22 +- .../java/fragment/ExampleFragment.java | 45 ++-- .../java/activity/ExampleActivity.java | 50 ++--- .../java/adapter/SearchSuggestionAdapter.java | 19 +- .../java/activity/ExampleActivity.java | 26 +-- .../java/activity/PickerActivity.java | 19 +- .../java/fragment/ExampleFragment.java | 26 +-- Src-AlarmManager/java/alarm/ExampleAlarm.java | 28 +-- .../java/receiver/ExampleAlarmReceiver.java | 7 +- .../java/fragment/ExampleFragment.java | 16 +- .../activity/TransitionFirstActivity.java | 22 +- .../activity/TransitionSecondActivity.java | 26 +-- .../java/fragment/ExampleFragment.java | 15 +- .../java/animation/DepthPageTransformer.java | 23 +-- .../ScaleRotationPageTransformer.java | 8 +- .../animation/ZoomOutPageTransformer.java | 26 +-- .../java/fragment/ExampleFragment.java | 40 +--- .../java/ExampleApplication.java | 16 +- .../java/broadcast/ExampleBroadcast.java | 12 +- .../java/fragment/ExampleFragment.java | 33 +-- Src-Bundle/java/activity/ExampleActivity.java | 37 +--- Src-Bundle/java/fragment/ExampleFragment.java | 37 +--- Src-Config/java/ExampleConfig.java | 4 +- .../java/fragment/BottomSheetFragment.java | 22 +- .../java/fragment/OverlapFragment.java | 40 ++-- .../java/widget/ExampleBehavior.java | 15 +- .../widget/QuickReturnFooterBehavior.java | 67 ++---- .../ScalingFloatingActionButtonBehavior.java | 33 +-- .../SlidingFloatingActionButtonBehavior.java | 59 ++---- .../java/entity/ExampleEntity.java | 91 +++----- .../java/dialog/CustomDialogFragment.java | 92 +++------ .../java/dialog/DatePickerDialogFragment.java | 54 ++--- .../java/dialog/FixedDatePickerDialog.java | 28 +-- .../java/dialog/FixedTimePickerDialog.java | 28 +-- .../java/dialog/ItemsDialogFragment.java | 67 ++---- .../MultiChoiceItemsDialogFragment.java | 81 +++----- .../java/dialog/ProgressDialogFragment.java | 29 +-- .../java/dialog/SheetDialogFragment.java | 85 +++----- .../java/dialog/SimpleDialogFragment.java | 61 ++---- .../SingleChoiceItemsDialogFragment.java | 81 +++----- .../java/dialog/TimePickerDialogFragment.java | 54 ++--- .../java/fragment/ExampleFragment.java | 175 +++++----------- .../java/activity/ListingActivity.java | 62 ++---- .../java/activity/SimpleActivity.java | 15 +- .../java/fragment/ListingFragment.java | 48 ++--- .../java/fragment/SimpleFragment.java | 44 ++-- .../java/listener/OnDualPaneShowListener.java | 4 +- Src-Enum/java/entity/IntegerEnum.java | 16 +- Src-Enum/java/entity/StringEnum.java | 12 +- .../ExampleContentObserverService.java | 26 +-- .../service/ExampleFileObserverService.java | 48 ++--- .../java/utility/ExampleContentObserver.java | 15 +- .../java/utility/ExampleFileObserver.java | 50 ++--- .../java/activity/ExampleActivity.java | 14 +- Src-Glide/java/utility/BindingUtility.java | 19 +- Src-Glide/java/utility/GlideUtility.java | 48 ++--- Src-Glide/res/layout/fragment_example.xml | 6 +- .../java/fragment/ExampleFragment.java | 22 +- Src-Intent/java/activity/ExampleActivity.java | 11 +- .../java/service/ExampleService.java | 28 +-- .../java/utility/JobSchedulerUtility.java | 9 +- .../java/viewmodel/ExampleViewModel.java | 90 +++----- .../java/utility/LocationUtility.java | 101 +++------ .../java/activity/ExampleActivity.java | 46 ++--- .../adapter/ExpandableListingAdapter.java | 103 +++------- .../fragment/ExpandableListingFragment.java | 157 +++++--------- .../java/entity/ProductEntity.java | 30 +-- .../java/fragment/SimpleFragment.java | 110 +++------- .../java/fragment/TaskFragment.java | 46 ++--- Src-MVC-Fragment/java/task/LoadDataTask.java | 36 +--- .../java/adapter/ListingAdapter.java | 46 ++--- .../java/fragment/ListingFragment.java | 184 +++++------------ .../adapter/MultiSelectorRecyclerAdapter.java | 44 ++-- .../java/adapter/RecyclerAdapter.java | 174 +++++----------- .../java/fragment/RecyclerFragment.java | 189 +++++------------ .../java/adapter/StickyListingAdapter.java | 64 ++---- .../java/fragment/StickyListingFragment.java | 145 ++++--------- .../java/adapter/TreeListingAdapter.java | 54 ++--- .../java/fragment/TreeListingFragment.java | 194 +++++------------- .../java/fragment/ExampleFragment.java | 38 +--- Src-Map/java/fragment/ExampleFragment.java | 79 +++---- .../java/activity/ExampleActivity.java | 89 +++----- .../java/adapter/DrawerAdapter.java | 42 ++-- .../java/activity/ExampleActivity.java | 81 +++----- .../java/fragment/ExampleFragment.java | 18 +- .../notification/NotificationMessage.java | 172 +++++----------- Src-Parcelable/java/entity/ExampleEntity.java | 43 ++-- .../java/fragment/ExampleFragment.java | 24 +-- .../java/fragment/ExampleFragment.java | 40 +--- .../java/activity/ExampleActivity.java | 26 +-- Src-Preferences/java/utility/Preferences.java | 44 +--- .../java/receiver/BootCompletedReceiver.java | 7 +- .../java/receiver/PhoneStateReceiver.java | 10 +- .../ssl/CertificateAuthoritySslUtility.java | 22 +- .../ssl/CertificateAuthorityTrustManager.java | 43 ++-- .../java/rest/ssl/SelfSignedSslUtility.java | 40 +--- .../java/rest/ssl/SelfSignedTrustManager.java | 100 +++------ .../java/service/ExampleIntentService.java | 38 +--- Src-Service/java/service/ExampleService.java | 47 ++--- .../java/activity/ExampleActivity.java | 83 +++----- .../java/activity/ExampleActivity.java | 7 +- .../java/fragment/ListingFragment.java | 43 +--- .../java/fragment/RecyclerFragment.java | 43 +--- Src-Timer/java/fragment/ExampleFragment.java | 38 +--- .../java/activity/ExampleActivity.java | 30 +-- .../java/activity/IndicatorActivity.java | 19 +- .../java/activity/PagerActivity.java | 19 +- .../java/activity/TabHostActivity.java | 19 +- .../java/activity/TabIndicatorActivity.java | 19 +- .../java/activity/TabLayoutActivity.java | 19 +- .../IndicatorFragmentPagerAdapter.java | 25 +-- .../adapter/PagerFragmentPagerAdapter.java | 25 +-- .../java/adapter/PagerLayoutPagerAdapter.java | 32 +-- .../adapter/TabHostFragmentPagerAdapter.java | 65 ++---- .../TabIndicatorFragmentPagerAdapter.java | 25 +-- .../TabLayoutFragmentPagerAdapter.java | 25 +-- .../java/fragment/ExampleFragment.java | 34 +-- Src-ViewPager/java/widget/FixedScroller.java | 51 ++--- .../java/fragment/ExampleFragment.java | 104 +++------- 182 files changed, 2286 insertions(+), 5685 deletions(-) diff --git a/Base/mobile/build.gradle b/Base/mobile/build.gradle index 7320447..9130abe 100644 --- a/Base/mobile/build.gradle +++ b/Base/mobile/build.gradle @@ -5,17 +5,14 @@ // gradlew test Run local unit test // gradlew connectedAndroidTest Run instrumented unit test - final VERSION_MAJOR = 1 // max two digits final VERSION_MINOR = 0 // max two digits final VERSION_PATCH = 0 // max two digits final VERSION_BUILD = 0 // max three digits - apply plugin: "com.android.application" apply from: "../utils.gradle" - android { compileSdkVersion 27 buildToolsVersion "27.0.2" @@ -70,13 +67,12 @@ android { applicationVariants.all { variant -> - if(variant.buildType.name.equals("release")) { + if (variant.buildType.name.equals("release")) { renameArtifact("example", variant) } } } - dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:support-compat:27.0.2" diff --git a/Base/utils.gradle b/Base/utils.gradle index 3e751d0..3293541 100644 --- a/Base/utils.gradle +++ b/Base/utils.gradle @@ -1,18 +1,15 @@ import groovy.swing.SwingBuilder - ext.getVersionCode = { majorVersion, minorVersion, patchVersion, buildVersion -> return majorVersion * 10000000 + minorVersion * 100000 + patchVersion * 1000 + buildVersion } - ext.getVersionName = { majorVersion, minorVersion, patchVersion -> return "${majorVersion}.${minorVersion}.${patchVersion}" } - ext.renameArtifact = { name, variant -> variant.outputs.all { @@ -22,7 +19,6 @@ ext.renameArtifact = { } } - task askForPasswords { doLast { def storePass @@ -31,7 +27,7 @@ task askForPasswords { def keystorePropertiesFile = new File((String) project.property("keystore.properties")) - if(project.hasProperty("keystore.properties") && keystorePropertiesFile.exists()) { + if (project.hasProperty("keystore.properties") && keystorePropertiesFile.exists()) { println "Loading keystore passwords from property file..." Properties properties = new Properties() properties.load(new FileInputStream(keystorePropertiesFile)) @@ -67,10 +63,9 @@ task askForPasswords { } } - tasks.whenTaskAdded { task -> - if(task.name.equals("packageRelease")) { + if (task.name.equals("packageRelease")) { task.dependsOn "askForPasswords" } } diff --git a/Deprecated/Src-APICall/java/client/APICall.java b/Deprecated/Src-APICall/java/client/APICall.java index a576ccd..7ed7209 100644 --- a/Deprecated/Src-APICall/java/client/APICall.java +++ b/Deprecated/Src-APICall/java/client/APICall.java @@ -21,9 +21,7 @@ import java.net.UnknownHostException; import java.util.zip.GZIPInputStream; - -public class APICall -{ +public class APICall { private Request mRequest = null; private APICallTask mAPICallTask = null; private Exception mException = null; @@ -33,50 +31,35 @@ public class APICall private OutputStream mRequestStream = null; private InputStream mResponseStream = null; - - public APICall(Request request) - { + public APICall(Request request) { mRequest = request; } - - public APICall(Request request, APICallTask task) - { + public APICall(Request request, APICallTask task) { mRequest = request; mAPICallTask = task; } - - public Request getRequest() - { + public Request getRequest() { return mRequest; } - - public Exception getException() - { + public Exception getException() { return mException; } - - public ResponseStatus getResponseStatus() - { + public ResponseStatus getResponseStatus() { return mResponseStatus; } - - public void kill() - { + public void kill() { disconnect(); } - - public Response execute() - { - try - { + public Response execute() { + try { // disables Keep-Alive for all connections - if(mAPICallTask != null && mAPICallTask.isCancelled()) return null; + if (mAPICallTask != null && mAPICallTask.isCancelled()) return null; System.setProperty("http.keepAlive", "false"); // new connection @@ -94,11 +77,11 @@ public Response execute() mConnection.connect(); // send request - if(mAPICallTask != null && mAPICallTask.isCancelled()) return null; + if (mAPICallTask != null && mAPICallTask.isCancelled()) return null; sendRequest(requestData); // receive response - if(mAPICallTask != null && mAPICallTask.isCancelled()) return null; + if (mAPICallTask != null && mAPICallTask.isCancelled()) return null; mResponseStream = receiveResponse(); // response info @@ -109,101 +92,72 @@ public Response execute() //Logcat.d("connection.getResponseMessage() = " + mConnection.getResponseMessage()); // parse response - if(mAPICallTask != null && mAPICallTask.isCancelled()) return null; + if (mAPICallTask != null && mAPICallTask.isCancelled()) return null; Response response = parseResponse(); - if(mAPICallTask != null && mAPICallTask.isCancelled()) return null; + if (mAPICallTask != null && mAPICallTask.isCancelled()) return null; return response; - } - catch(UnknownHostException e) - { + } catch (UnknownHostException e) { mException = e; e.printStackTrace(); return null; - } - catch(FileNotFoundException e) - { + } catch (FileNotFoundException e) { mException = e; e.printStackTrace(); return null; - } - catch(SocketException e) - { + } catch (SocketException e) { mException = e; e.printStackTrace(); return null; - } - catch(SocketTimeoutException e) - { + } catch (SocketTimeoutException e) { mException = e; e.printStackTrace(); return null; - } - catch(JsonParseException e) - { + } catch (JsonParseException e) { mException = e; e.printStackTrace(); return null; - } - catch(IOException e) - { + } catch (IOException e) { mException = e; e.printStackTrace(); return null; - } - catch(Exception e) - { + } catch (Exception e) { mException = e; e.printStackTrace(); return null; - } - finally - { + } finally { disconnect(); } } + private void disconnect() { + try { + if (mRequestStream != null) mRequestStream.close(); + } catch (IOException e) {} - private void disconnect() - { - try - { - if(mRequestStream != null) mRequestStream.close(); - } - catch(IOException e) {} + try { + if (mResponseStream != null) mResponseStream.close(); + } catch (IOException e) {} - try - { - if(mResponseStream != null) mResponseStream.close(); - } - catch(IOException e) {} - - try - { + try { // set status - if(mConnection != null) - { + if (mConnection != null) { mResponseStatus.setStatusCode(mConnection.getResponseCode()); mResponseStatus.setStatusMessage(mConnection.getResponseMessage()); mConnection.disconnect(); } - } - catch(Throwable e) {} + } catch (Throwable e) {} mRequestStream = null; mResponseStream = null; mConnection = null; } - - private void setupConnection(byte[] requestData) throws ProtocolException - { - if(mRequest.getRequestMethod() != null) - { + private void setupConnection(byte[] requestData) throws ProtocolException { + if (mRequest.getRequestMethod() != null) { mConnection.setRequestMethod(mRequest.getRequestMethod()); // GET, POST, OPTIONS, HEAD, PUT, DELETE, TRACE } - if(mRequest.getBasicAuthUsername() != null && mRequest.getBasicAuthPassword() != null) - { + if (mRequest.getBasicAuthUsername() != null && mRequest.getBasicAuthPassword() != null) { mConnection.setRequestProperty("Authorization", getBasicAuthToken(mRequest.getBasicAuthUsername(), mRequest.getBasicAuthPassword())); } mConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); @@ -213,11 +167,10 @@ private void setupConnection(byte[] requestData) throws ProtocolException mConnection.setRequestProperty("Accept-Charset", "UTF-8"); //mConnection.setRequestProperty("Content-Length", requestData == null ? "0" : String.valueOf(requestData.length)); //if(requestData!=null) mConnection.setChunkedStreamingMode(0); - if(requestData != null) mConnection.setFixedLengthStreamingMode(requestData.length); + if (requestData != null) mConnection.setFixedLengthStreamingMode(requestData.length); mConnection.setConnectTimeout(30000); mConnection.setReadTimeout(30000); - if(requestData != null) - { + if (requestData != null) { // this call automatically sets request method to POST on Android 4 // if you don't want your app to POST, you must not call setDoOutput // http://webdiary.com/2011/12/14/ics-get-post/ @@ -227,50 +180,38 @@ private void setupConnection(byte[] requestData) throws ProtocolException mConnection.setUseCaches(false); } - - private void sendRequest(byte[] requestData) throws IOException - { - if(requestData != null) - { + private void sendRequest(byte[] requestData) throws IOException { + if (requestData != null) { mRequestStream = new BufferedOutputStream(mConnection.getOutputStream()); mRequestStream.write(requestData); mRequestStream.flush(); } } - - private InputStream receiveResponse() throws IOException - { + private InputStream receiveResponse() throws IOException { InputStream responseStream; String encoding = mConnection.getHeaderField("Content-Encoding"); boolean gzipped = encoding != null && encoding.toLowerCase().contains("gzip"); - try - { + try { InputStream inputStream = mConnection.getInputStream(); - if(gzipped) responseStream = new BufferedInputStream(new GZIPInputStream(inputStream)); + if (gzipped) responseStream = new BufferedInputStream(new GZIPInputStream(inputStream)); else responseStream = new BufferedInputStream(inputStream); - } - catch(FileNotFoundException e) - { + } catch (FileNotFoundException e) { // error stream InputStream errorStream = mConnection.getErrorStream(); - if(gzipped) responseStream = new BufferedInputStream(new GZIPInputStream(errorStream)); + if (gzipped) responseStream = new BufferedInputStream(new GZIPInputStream(errorStream)); else responseStream = new BufferedInputStream(errorStream); } return responseStream; } - - private Response parseResponse() throws IOException - { + private Response parseResponse() throws IOException { Response response = mRequest.parseResponse(mResponseStream); - if(response == null) throw new RuntimeException("Parser returned null response"); + if (response == null) throw new RuntimeException("Parser returned null response"); return response; } - - private String getBasicAuthToken(String username, String password) - { + private String getBasicAuthToken(String username, String password) { // Base64.NO_WRAP because of Android <4 problem String base64 = Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP); return "Basic " + base64; diff --git a/Deprecated/Src-APICall/java/client/APICallListener.java b/Deprecated/Src-APICall/java/client/APICallListener.java index 5abd10a..af47b4e 100644 --- a/Deprecated/Src-APICall/java/client/APICallListener.java +++ b/Deprecated/Src-APICall/java/client/APICallListener.java @@ -2,9 +2,7 @@ import com.example.client.response.Response; - -public interface APICallListener -{ +public interface APICallListener { void onAPICallRespond(APICallTask task, ResponseStatus status, Response response); void onAPICallFail(APICallTask task, ResponseStatus status, Exception exception); } diff --git a/Deprecated/Src-APICall/java/client/APICallManager.java b/Deprecated/Src-APICall/java/client/APICallManager.java index aa927d9..2c9dc5a 100644 --- a/Deprecated/Src-APICall/java/client/APICallManager.java +++ b/Deprecated/Src-APICall/java/client/APICallManager.java @@ -10,87 +10,61 @@ import java.util.LinkedList; import java.util.List; - -public class APICallManager -{ +public class APICallManager { private List mTaskList = new LinkedList<>(); - - public APICallManager() - { + public APICallManager() { } - - public void executeTask(Request request, APICallListener listener) - { + public void executeTask(Request request, APICallListener listener) { executeTask(request, listener, 1); } - - public void executeTask(Request request, APICallListener listener, int maxAttempts) - { + public void executeTask(Request request, APICallListener listener, int maxAttempts) { APICallTask task = new APICallTask(request, listener, maxAttempts); mTaskList.add(task); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // use AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - else - { + } else { task.execute(); } } - - public boolean finishTask(APICallTask task) - { + public boolean finishTask(APICallTask task) { return mTaskList.remove(task); } - - public int getTasksCount() - { + public int getTasksCount() { return mTaskList.size(); } - - public boolean hasRunningTask(Class requestClass) - { + public boolean hasRunningTask(Class requestClass) { String className = requestClass.getSimpleName(); - for(APICallTask task : mTaskList) - { + for (APICallTask task : mTaskList) { String taskName = task.getRequest().getClass().getSimpleName(); - if(className.equals(taskName)) return true; + if (className.equals(taskName)) return true; } return false; } - - public void cancelAllTasks() - { - for(int i = mTaskList.size() - 1; i >= 0; i--) - { + public void cancelAllTasks() { + for (int i = mTaskList.size() - 1; i >= 0; i--) { APICallTask task = mTaskList.get(i); - if(task != null) - { + if (task != null) { task.cancel(true); mTaskList.remove(task); } } } - - public void killAllTasks() - { - for(int i = mTaskList.size() - 1; i >= 0; i--) - { + public void killAllTasks() { + for (int i = mTaskList.size() - 1; i >= 0; i--) { APICallTask task = mTaskList.get(i); - if(task != null) - { + if (task != null) { task.kill(); task.cancel(true); mTaskList.remove(task); @@ -98,14 +72,11 @@ public void killAllTasks() } } - - public void printRunningTasks() - { - for(APICallTask task : mTaskList) - { + public void printRunningTasks() { + for (APICallTask task : mTaskList) { Logcat.d(task == null ? "null" : (task.getRequest().getClass().getSimpleName() + " " + task.getStatus().toString())); } - if(mTaskList.isEmpty()) Logcat.d("empty"); + if (mTaskList.isEmpty()) Logcat.d("empty"); } } diff --git a/Deprecated/Src-APICall/java/client/APICallTask.java b/Deprecated/Src-APICall/java/client/APICallTask.java index d763a2c..4862308 100644 --- a/Deprecated/Src-APICall/java/client/APICallTask.java +++ b/Deprecated/Src-APICall/java/client/APICallTask.java @@ -9,9 +9,7 @@ import java.lang.ref.WeakReference; - -public class APICallTask extends AsyncTask> -{ +public class APICallTask extends AsyncTask> { private static final int RETRY_MAX_ATTEMPTS = 1; // default value for max number of retries private static final long RETRY_INIT_BACKOFF = 500L; // initial sleep time before retry @@ -19,53 +17,41 @@ public class APICallTask extends AsyncTask> private WeakReference mListener; private int mMaxAttempts = RETRY_MAX_ATTEMPTS; - - public APICallTask(Request request, APICallListener listener) - { + public APICallTask(Request request, APICallListener listener) { mAPICall = new APICall(request, this); setListener(listener); } - - public APICallTask(Request request, APICallListener listener, int maxAttempts) - { + public APICallTask(Request request, APICallListener listener, int maxAttempts) { this(request, listener); setMaxAttempts(maxAttempts); } - @Override - protected Response doInBackground(Void... params) - { + protected Response doInBackground(Void... params) { // response Response response = null; // sleep time before retry long backoff = RETRY_INIT_BACKOFF; - for(int i = 0; i < mMaxAttempts; i++) - { + for (int i = 0; i < mMaxAttempts; i++) { // execute API call response = mAPICall.execute(); // success - if(response != null) - { + if (response != null) { break; } // fail - else - { - if(i == mMaxAttempts) break; + else { + if (i == mMaxAttempts) break; - try - { + try { Logcat.d("sleeping for %d ms before retry", backoff); Thread.sleep(backoff); - } - catch(InterruptedException e) - { + } catch (InterruptedException e) { // activity finished before we complete Logcat.d("thread interrupted so abort remaining retries"); Thread.currentThread().interrupt(); @@ -80,54 +66,38 @@ protected Response doInBackground(Void... params) return response; } - @Override - protected void onPostExecute(Response response) - { - if(isCancelled()) return; + protected void onPostExecute(Response response) { + if (isCancelled()) return; APICallListener listener = mListener.get(); - if(listener != null) - { - if(response != null) - { + if (listener != null) { + if (response != null) { listener.onAPICallRespond(this, mAPICall.getResponseStatus(), response); - } - else - { + } else { listener.onAPICallFail(this, mAPICall.getResponseStatus(), mAPICall.getException()); } } } - @Override - protected void onCancelled() - { + protected void onCancelled() { Logcat.d(""); } - - public Request getRequest() - { + public Request getRequest() { return mAPICall.getRequest(); } - - public void setListener(APICallListener listener) - { + public void setListener(APICallListener listener) { mListener = new WeakReference<>(listener); } - - public void setMaxAttempts(int maxAttempts) - { + public void setMaxAttempts(int maxAttempts) { mMaxAttempts = maxAttempts; } - - public void kill() - { + public void kill() { mAPICall.kill(); } } diff --git a/Deprecated/Src-APICall/java/client/ResponseStatus.java b/Deprecated/Src-APICall/java/client/ResponseStatus.java index 9f36432..be594c3 100644 --- a/Deprecated/Src-APICall/java/client/ResponseStatus.java +++ b/Deprecated/Src-APICall/java/client/ResponseStatus.java @@ -1,38 +1,26 @@ package com.example.client; - -public class ResponseStatus -{ +public class ResponseStatus { // HTTP status codes are defined in HttpURLConnection private int mStatusCode = -1; private String mStatusMessage = "Unknown"; - - public ResponseStatus() - { + public ResponseStatus() { } - - public int getStatusCode() - { + public int getStatusCode() { return mStatusCode; } - - public void setStatusCode(int statusCode) - { + public void setStatusCode(int statusCode) { mStatusCode = statusCode; } - - public String getStatusMessage() - { + public String getStatusMessage() { return mStatusMessage; } - - public void setStatusMessage(String statusMessage) - { + public void setStatusMessage(String statusMessage) { mStatusMessage = statusMessage; } } diff --git a/Deprecated/Src-APICall/java/client/parser/ExampleParser.java b/Deprecated/Src-APICall/java/client/parser/ExampleParser.java index bd78993..ce921b9 100644 --- a/Deprecated/Src-APICall/java/client/parser/ExampleParser.java +++ b/Deprecated/Src-APICall/java/client/parser/ExampleParser.java @@ -13,11 +13,8 @@ import java.util.ArrayList; import java.util.List; - -public class ExampleParser extends Parser -{ - public static Response> parse(InputStream stream) throws IOException, JsonParseException - { +public class ExampleParser extends Parser { + public static Response> parse(InputStream stream) throws IOException, JsonParseException { Response> response = null; // init parser @@ -26,25 +23,19 @@ public static Response> parse(InputStream stream) throws IOE parser = factory.createJsonParser(stream); // parse JSON - if(parser.nextToken() == JsonToken.START_OBJECT) - while(parser.nextToken() != JsonToken.END_OBJECT) - { + if (parser.nextToken() == JsonToken.START_OBJECT) + while (parser.nextToken() != JsonToken.END_OBJECT) { // error - if(parser.getCurrentName().equals("error")) - { + if (parser.getCurrentName().equals("error")) { String type = null; String message = null; - if(parser.nextToken() == JsonToken.START_OBJECT) - while(parser.nextToken() != JsonToken.END_OBJECT) - { - if(parser.getCurrentName().equals("type")) - { - if(parser.getCurrentToken() == JsonToken.VALUE_STRING) type = parser.getText(); - } - else if(parser.getCurrentName().equals("message")) - { - if(parser.getCurrentToken() == JsonToken.VALUE_STRING) message = parser.getText(); + if (parser.nextToken() == JsonToken.START_OBJECT) + while (parser.nextToken() != JsonToken.END_OBJECT) { + if (parser.getCurrentName().equals("type")) { + if (parser.getCurrentToken() == JsonToken.VALUE_STRING) type = parser.getText(); + } else if (parser.getCurrentName().equals("message")) { + if (parser.getCurrentToken() == JsonToken.VALUE_STRING) message = parser.getText(); } } @@ -55,24 +46,17 @@ else if(parser.getCurrentName().equals("message")) } // response - else if(parser.getCurrentName().equals("product")) - { + else if (parser.getCurrentName().equals("product")) { long id = -1L; String name = null; - if(parser.nextToken() == JsonToken.START_OBJECT) - while(parser.nextToken() != JsonToken.END_OBJECT) - { - if(parser.getCurrentName().equals("id")) - { - if(parser.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) id = parser.getLongValue(); - } - else if(parser.getCurrentName().equals("name")) - { - if(parser.getCurrentToken() == JsonToken.VALUE_STRING) name = parser.getText(); - } - else - { + if (parser.nextToken() == JsonToken.START_OBJECT) + while (parser.nextToken() != JsonToken.END_OBJECT) { + if (parser.getCurrentName().equals("id")) { + if (parser.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) id = parser.getLongValue(); + } else if (parser.getCurrentName().equals("name")) { + if (parser.getCurrentToken() == JsonToken.VALUE_STRING) name = parser.getText(); + } else { // unknown parameter handleUnknownParameter(parser); } @@ -91,7 +75,7 @@ else if(parser.getCurrentName().equals("name")) } // close parser - if(parser != null) parser.close(); + if (parser != null) parser.close(); return response; } } diff --git a/Deprecated/Src-APICall/java/client/parser/Parser.java b/Deprecated/Src-APICall/java/client/parser/Parser.java index 089195f..65061a5 100644 --- a/Deprecated/Src-APICall/java/client/parser/Parser.java +++ b/Deprecated/Src-APICall/java/client/parser/Parser.java @@ -6,20 +6,15 @@ import java.io.IOException; - -public class Parser -{ - protected static void handleUnknownParameter(JsonParser parser) throws IOException, JsonParseException - { - if(parser.getCurrentToken() == JsonToken.START_OBJECT) - while(parser.nextToken() != JsonToken.END_OBJECT) - { +public class Parser { + protected static void handleUnknownParameter(JsonParser parser) throws IOException, JsonParseException { + if (parser.getCurrentToken() == JsonToken.START_OBJECT) + while (parser.nextToken() != JsonToken.END_OBJECT) { handleUnknownParameter(parser); } - if(parser.getCurrentToken() == JsonToken.START_ARRAY) - while(parser.nextToken() != JsonToken.END_ARRAY) - { + if (parser.getCurrentToken() == JsonToken.START_ARRAY) + while (parser.nextToken() != JsonToken.END_ARRAY) { handleUnknownParameter(parser); } } diff --git a/Deprecated/Src-APICall/java/client/request/ExampleRequest.java b/Deprecated/Src-APICall/java/client/request/ExampleRequest.java index 4a3cc4b..2da1fb3 100644 --- a/Deprecated/Src-APICall/java/client/request/ExampleRequest.java +++ b/Deprecated/Src-APICall/java/client/request/ExampleRequest.java @@ -13,33 +13,25 @@ import java.io.UnsupportedEncodingException; import java.util.List; - -public class ExampleRequest extends Request -{ +public class ExampleRequest extends Request { private static final String REQUEST_METHOD = "POST"; private static final String REQUEST_PATH = "example"; private int mSkip; private int mTake; - - public ExampleRequest(int skip, int take) - { + public ExampleRequest(int skip, int take) { mSkip = skip; mTake = take; } - @Override - public String getRequestMethod() - { + public String getRequestMethod() { return REQUEST_METHOD; } - @Override - public String getAddress() - { + public String getAddress() { Uri.Builder builder = new Uri.Builder(); builder.encodedPath(REST_BASE_URL); builder.appendEncodedPath(REQUEST_PATH); @@ -48,42 +40,31 @@ public String getAddress() return builder.build().toString(); } - @Override - public Response> parseResponse(InputStream stream) throws IOException, JsonParseException - { + public Response> parseResponse(InputStream stream) throws IOException, JsonParseException { return ExampleParser.parse(stream); } - @Override - public byte[] getContent() - { + public byte[] getContent() { StringBuilder builder = new StringBuilder(); builder.append("content"); - try - { + try { return builder.toString().getBytes(CHARSET); - } - catch(UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } - @Override - public String getBasicAuthUsername() - { + public String getBasicAuthUsername() { return "myusername"; } - @Override - public String getBasicAuthPassword() - { + public String getBasicAuthPassword() { return "mypassword"; } } diff --git a/Deprecated/Src-APICall/java/client/request/MultipartRequest.java b/Deprecated/Src-APICall/java/client/request/MultipartRequest.java index a5774ae..d504fb5 100644 --- a/Deprecated/Src-APICall/java/client/request/MultipartRequest.java +++ b/Deprecated/Src-APICall/java/client/request/MultipartRequest.java @@ -11,9 +11,7 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; - -public class MultipartRequest extends Request -{ +public class MultipartRequest extends Request { private static final String REQUEST_METHOD = "POST"; private static final String REQUEST_PATH = "multipart"; @@ -22,26 +20,20 @@ public class MultipartRequest extends Request private byte[] mBinaryData1; private byte[] mBinaryData2; - - public MultipartRequest(String textData1, String textData2, byte[] binaryData1, byte[] binaryData2) - { + public MultipartRequest(String textData1, String textData2, byte[] binaryData1, byte[] binaryData2) { mTextData1 = textData1; mTextData2 = textData2; mBinaryData1 = binaryData1; mBinaryData2 = binaryData2; } - @Override - public String getRequestMethod() - { + public String getRequestMethod() { return REQUEST_METHOD; } - @Override - public String getAddress() - { + public String getAddress() { StringBuilder builder = new StringBuilder(); // url @@ -51,17 +43,13 @@ public String getAddress() return builder.toString(); } - @Override - public Response parseResponse(InputStream stream) throws IOException, JsonParseException - { + public Response parseResponse(InputStream stream) throws IOException, JsonParseException { return MultipartParser.parse(stream); } - @Override - public byte[] getContent() - { + public byte[] getContent() { StringBuilder plainBuilder = new StringBuilder(); plainBuilder.append("--" + BOUNDARY + "\r\n"); @@ -90,8 +78,7 @@ public byte[] getContent() binary2Builder.append("Content-Type: application/octet-stream\r\n"); binary2Builder.append("\r\n"); - try - { + try { byte[] plainBytes = plainBuilder.toString().getBytes("UTF-8"); byte[] binary1Bytes = binary1Builder.toString().getBytes("UTF-8"); byte[] binary2Bytes = binary2Builder.toString().getBytes("UTF-8"); @@ -101,14 +88,12 @@ public byte[] getContent() // byte stream ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write(plainBytes); - if(mBinaryData1.length > 0) - { + if (mBinaryData1.length > 0) { stream.write(binary1Bytes); stream.write(mBinaryData1); stream.write(breakBytes); } - if(mBinaryData2.length > 0) - { + if (mBinaryData2.length > 0) { stream.write(binary2Bytes); stream.write(mBinaryData2); stream.write(breakBytes); @@ -116,24 +101,18 @@ public byte[] getContent() stream.write(endBytes); return stream.toByteArray(); - } - catch(UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; - } - catch(IOException e) - { + } catch (IOException e) { e.printStackTrace(); return null; } } - // TODO: set proper content type in APICall @Override - public boolean isMultipart() - { + public boolean isMultipart() { return true; } } diff --git a/Deprecated/Src-APICall/java/client/request/Request.java b/Deprecated/Src-APICall/java/client/request/Request.java index dfa46a5..d1d94b6 100644 --- a/Deprecated/Src-APICall/java/client/request/Request.java +++ b/Deprecated/Src-APICall/java/client/request/Request.java @@ -10,53 +10,38 @@ import java.io.IOException; import java.io.InputStream; - -public abstract class Request -{ +public abstract class Request { public static final String REST_BASE_URL = ExampleConfig.REST_BASE_URL; public static final String CHARSET = "UTF-8"; public static final String BOUNDARY = "0xKhTmLbOuNdArY"; private Bundle mMetaData = null; - public abstract String getRequestMethod(); public abstract String getAddress(); public abstract Response parseResponse(InputStream stream) throws IOException, JsonParseException; - - public byte[] getContent() - { + public byte[] getContent() { return null; } - - public String getBasicAuthUsername() - { + public String getBasicAuthUsername() { return null; } - - public String getBasicAuthPassword() - { + public String getBasicAuthPassword() { return null; } - - public boolean isMultipart() - { + public boolean isMultipart() { return false; } - - public Bundle getMetaData() - { + public Bundle getMetaData() { return mMetaData; } - - public void setMetaData(Bundle metaData) - { + public void setMetaData(Bundle metaData) { mMetaData = metaData; } } diff --git a/Deprecated/Src-APICall/java/client/response/Response.java b/Deprecated/Src-APICall/java/client/response/Response.java index d536faa..2d2367d 100644 --- a/Deprecated/Src-APICall/java/client/response/Response.java +++ b/Deprecated/Src-APICall/java/client/response/Response.java @@ -1,63 +1,43 @@ package com.example.client.response; - -public class Response -{ +public class Response { private T mResponseObject; private boolean mError = false; private String mErrorType = null; private String mErrorMessage = null; - - public Response() - { + public Response() { } - - public T getResponseObject() - { + public T getResponseObject() { return mResponseObject; } - - public void setResponseObject(T responseObject) - { + public void setResponseObject(T responseObject) { mResponseObject = responseObject; } - - public boolean isError() - { + public boolean isError() { return mError; } - - public void setError(boolean error) - { + public void setError(boolean error) { mError = error; } - - public String getErrorType() - { + public String getErrorType() { return mErrorType; } - - public void setErrorType(String errorType) - { + public void setErrorType(String errorType) { mErrorType = errorType; } - - public String getErrorMessage() - { + public String getErrorMessage() { return mErrorMessage; } - - public void setErrorMessage(String errorMessage) - { + public void setErrorMessage(String errorMessage) { mErrorMessage = errorMessage; } } diff --git a/Deprecated/Src-APICall/java/fragment/ExampleFragment.java b/Deprecated/Src-APICall/java/fragment/ExampleFragment.java index c0007b0..47585bc 100644 --- a/Deprecated/Src-APICall/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-APICall/java/fragment/ExampleFragment.java @@ -31,9 +31,7 @@ import java.util.Iterator; import java.util.List; - -public class ExampleFragment extends TaskFragment implements APICallListener -{ +public class ExampleFragment extends TaskFragment implements APICallListener { private static final String META_REFRESH = "refresh"; private static final int LAZY_LOADING_TAKE = 16; private static final int LAZY_LOADING_OFFSET = 4; @@ -47,79 +45,63 @@ public class ExampleFragment extends TaskFragment implements APICallListener private APICallManager mAPICallManager = new APICallManager(); private List mProductList = new ArrayList<>(); - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProductList == null || mProductList.isEmpty()) loadData(); + if (mProductList == null || mProductList.isEmpty()) loadData(); // lazy loading progress - if(mLazyLoading) showLazyLoadingProgress(true); + if (mLazyLoading) showLazyLoadingProgress(true); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks mAPICallManager.cancelAllTasks(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onAPICallRespond(final APICallTask task, final ResponseStatus status, final Response response) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getRequest().getClass().equals(ExampleRequest.class)) - { + public void onAPICallRespond(final APICallTask task, final ResponseStatus status, final Response response) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getRequest().getClass().equals(ExampleRequest.class)) { Response> exampleResponse = (Response>) response; // error - if(exampleResponse.isError()) - { + if (exampleResponse.isError()) { Logcat.d("ExampleRequest / " + status.getStatusCode() + " " + status.getStatusMessage() + " / error " + exampleResponse.getErrorType() + " / " + exampleResponse.getErrorMessage()); @@ -128,13 +110,11 @@ public void run() } // response - else - { + else { Logcat.d("ExampleRequest / " + status.getStatusCode() + " " + status.getStatusMessage()); // check meta data - if(task.getRequest().getMetaData() != null && task.getRequest().getMetaData().getBoolean(META_REFRESH, false)) - { + if (task.getRequest().getMetaData() != null && task.getRequest().getMetaData().getBoolean(META_REFRESH, false)) { // refresh mProductList.clear(); } @@ -142,8 +122,7 @@ public void run() // get data List productList = exampleResponse.getResponseObject(); Iterator iterator = productList.iterator(); - while(iterator.hasNext()) - { + while (iterator.hasNext()) { ProductEntity product = iterator.next(); mProductList.add(product); } @@ -158,23 +137,18 @@ public void run() mAPICallManager.finishTask(task); // hide progress popup - if(mAPICallManager.getTasksCount() == 0) showProgress(false); + if (mAPICallManager.getTasksCount() == 0) showProgress(false); } }); } - @Override - public void onAPICallFail(final APICallTask task, final ResponseStatus status, final Exception exception) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getRequest().getClass().equals(ExampleRequest.class)) - { + public void onAPICallFail(final APICallTask task, final ResponseStatus status, final Exception exception) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getRequest().getClass().equals(ExampleRequest.class)) { Logcat.d("ExampleRequest / " + status.getStatusCode() + " " + status.getStatusMessage() + " / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); @@ -190,18 +164,14 @@ public void run() mAPICallManager.finishTask(task); // hide progress popup - if(mAPICallManager.getTasksCount() == 0) showProgress(false); + if (mAPICallManager.getTasksCount() == 0) showProgress(false); } }); } - - public void refreshData() - { - if(NetworkUtility.isOnline(getActivity())) - { - if(!mAPICallManager.hasRunningTask(ExampleRequest.class)) - { + public void refreshData() { + if (NetworkUtility.isOnline(getActivity())) { + if (!mAPICallManager.hasRunningTask(ExampleRequest.class)) { // show progress popup showProgress(true); @@ -215,49 +185,39 @@ public void refreshData() request.setMetaData(bundle); mAPICallManager.executeTask(request, this); } - } - else - { + } else { Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show(); } } - - private void handleError(String errorType, String errorMessage) - { + private void handleError(String errorType, String errorMessage) { // TODO: show dialog } - - private void handleFail(Exception exception) - { + private void handleFail(Exception exception) { int messageId; - if(exception != null && exception.getClass().equals(UnknownHostException.class)) + if (exception != null && exception.getClass().equals(UnknownHostException.class)) messageId = R.string.global_network_unknown_host; - else if(exception != null && exception.getClass().equals(FileNotFoundException.class)) + else if (exception != null && exception.getClass().equals(FileNotFoundException.class)) messageId = R.string.global_network_not_found; - else if(exception != null && exception.getClass().equals(SocketTimeoutException.class)) + else if (exception != null && exception.getClass().equals(SocketTimeoutException.class)) messageId = R.string.global_network_timeout; - else if(exception != null && exception.getClass().equals(JsonParseException.class)) + else if (exception != null && exception.getClass().equals(JsonParseException.class)) messageId = R.string.global_network_parse_fail; - else if(exception != null && exception.getClass().equals(ParseException.class)) + else if (exception != null && exception.getClass().equals(ParseException.class)) messageId = R.string.global_network_parse_fail; - else if(exception != null && exception.getClass().equals(NumberFormatException.class)) + else if (exception != null && exception.getClass().equals(NumberFormatException.class)) messageId = R.string.global_network_parse_fail; - else if(exception != null && exception.getClass().equals(ClassCastException.class)) + else if (exception != null && exception.getClass().equals(ClassCastException.class)) messageId = R.string.global_network_parse_fail; else messageId = R.string.global_network_fail; Toast.makeText(getActivity(), messageId, Toast.LENGTH_LONG).show(); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { - if(!mAPICallManager.hasRunningTask(ExampleRequest.class)) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { + if (!mAPICallManager.hasRunningTask(ExampleRequest.class)) { // show progress mStatefulLayout.showProgress(); @@ -268,18 +228,13 @@ private void loadData() Request request = new ExampleRequest(0, LAZY_LOADING_TAKE); mAPICallManager.executeTask(request, this); } - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void lazyLoadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void lazyLoadData() { + if (NetworkUtility.isOnline(getActivity())) { // show lazy loading progress showLazyLoadingProgress(true); @@ -289,19 +244,14 @@ private void lazyLoadData() } } - - private void showLazyLoadingProgress(boolean visible) - { - if(visible) - { + private void showLazyLoadingProgress(boolean visible) { + if (visible) { mLazyLoading = true; // show footer ListView listView = getListView(); listView.addFooterView(mFooterView); - } - else - { + } else { // hide footer ListView listView = getListView(); listView.removeFooterView(mFooterView); @@ -310,9 +260,7 @@ private void showLazyLoadingProgress(boolean visible) } } - - private void setupView() - { + private void setupView() { // TODO } } diff --git a/Deprecated/Src-Animation-Layout-Animation-Controller/java/fragment/ExampleFragment.java b/Deprecated/Src-Animation-Layout-Animation-Controller/java/fragment/ExampleFragment.java index af97380..0561b29 100644 --- a/Deprecated/Src-Animation-Layout-Animation-Controller/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-Animation-Layout-Animation-Controller/java/fragment/ExampleFragment.java @@ -12,22 +12,16 @@ import com.example.R; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void setupView() - { + private void setupView() { // reference ListView listView = getListView(); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/ExampleApplication.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/ExampleApplication.java index 619e4c0..c35c309 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/ExampleApplication.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/ExampleApplication.java @@ -4,27 +4,19 @@ import com.activeandroid.ActiveAndroid; - -public class ExampleApplication extends com.activeandroid.app.Application -{ +public class ExampleApplication extends com.activeandroid.app.Application { private static ExampleApplication sInstance; - - public ExampleApplication() - { + public ExampleApplication() { sInstance = this; } - - public static Context getContext() - { + public static Context getContext() { return sInstance; } - @Override - public void onCreate() - { + public void onCreate() { super.onCreate(); // logs in ActiveAndroid diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/DAO.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/DAO.java index d1c71d1..fa29041 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/DAO.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/DAO.java @@ -2,9 +2,7 @@ import java.util.List; - -public interface DAO -{ +public interface DAO { long create(T t); T read(long id); T readFirst(); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/ProductDAO.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/ProductDAO.java index d4b1942..51ff516 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/ProductDAO.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/dao/ProductDAO.java @@ -8,42 +8,32 @@ import java.util.ArrayList; import java.util.List; - -public class ProductDAO implements DAO -{ +public class ProductDAO implements DAO { @Override - public long create(ProductEntity product) - { + public long create(ProductEntity product) { ProductModel m = new ProductModel(); m.set(product); return m.save(); } - @Override - public ProductEntity read(long id) - { + public ProductEntity read(long id) { ProductModel m = new Select().from(ProductModel.class).where("Id=?", id).executeSingle(); return m.toEntity(); } - @Override - public ProductEntity readFirst() - { + public ProductEntity readFirst() { ProductModel m = new Select().from(ProductModel.class).limit(1).executeSingle(); return m.toEntity(); } - @Override - public List readAll() - { + public List readAll() { List modelList = new Select().from(ProductModel.class).orderBy("Timestamp ASC").execute(); List entityList = new ArrayList<>(); - for(ProductModel m : modelList) - { + for (ProductModel m : modelList) { ProductEntity e = m.toEntity(); entityList.add(e); } @@ -51,15 +41,12 @@ public List readAll() return entityList; } - @Override - public List readAll(int limit, int offset) - { + public List readAll(int limit, int offset) { List modelList = new Select().from(ProductModel.class).limit(limit).offset(offset).orderBy("Timestamp ASC").execute(); List entityList = new ArrayList<>(); - for(ProductModel m : modelList) - { + for (ProductModel m : modelList) { ProductEntity e = m.toEntity(); entityList.add(e); } @@ -67,26 +54,20 @@ public List readAll(int limit, int offset) return entityList; } - @Override - public long update(ProductEntity product) - { + public long update(ProductEntity product) { ProductModel m = new Select().from(ProductModel.class).where("Id=?", product.getId()).executeSingle(); m.set(product); return m.save(); } - @Override - public void delete(long id) - { + public void delete(long id) { new Delete().from(ProductModel.class).where("Id=?", id).execute(); } - @Override - public void deleteAll() - { + public void deleteAll() { new Delete().from(ProductModel.class).execute(); } } diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/model/ProductModel.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/model/ProductModel.java index 63d3a78..8fb7bd8 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/model/ProductModel.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/model/ProductModel.java @@ -5,25 +5,19 @@ import com.activeandroid.annotation.Table; import com.example.entity.ProductEntity; - @Table(name = "Products") -public class ProductModel extends Model -{ +public class ProductModel extends Model { @Column(name = "Name") public String name; @Column(name = "Quantity") public int quantity; @Column(name = "Timestamp") public long timestamp; @Column(name = "Price") public double price; - // empty constructor - public ProductModel() - { + public ProductModel() { super(); } - - public ProductEntity toEntity() - { + public ProductEntity toEntity() { ProductEntity e = new ProductEntity(); e.setId(getId()); e.setName(name); @@ -33,9 +27,7 @@ public ProductEntity toEntity() return e; } - - public void set(ProductEntity e) - { + public void set(ProductEntity e) { name = e.getName(); quantity = e.getQuantity(); timestamp = e.getTimestamp(); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductCreateQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductCreateQuery.java index 5cabe5e..d7490b0 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductCreateQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductCreateQuery.java @@ -4,21 +4,15 @@ import com.example.database.data.Data; import com.example.entity.ProductEntity; - -public class ProductCreateQuery extends Query -{ +public class ProductCreateQuery extends Query { private ProductEntity mProduct; - - public ProductCreateQuery(ProductEntity product) - { + public ProductCreateQuery(ProductEntity product) { mProduct = product; } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); long id = dao.create(mProduct); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteAllQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteAllQuery.java index 2142822..1cd9b27 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteAllQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteAllQuery.java @@ -3,17 +3,12 @@ import com.example.database.dao.ProductDAO; import com.example.database.data.Data; - -public class ProductDeleteAllQuery extends Query -{ - public ProductDeleteAllQuery() - { +public class ProductDeleteAllQuery extends Query { + public ProductDeleteAllQuery() { } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); dao.deleteAll(); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteQuery.java index e3b4842..be8a4e8 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductDeleteQuery.java @@ -3,21 +3,15 @@ import com.example.database.dao.ProductDAO; import com.example.database.data.Data; - -public class ProductDeleteQuery extends Query -{ +public class ProductDeleteQuery extends Query { private long mId; - - public ProductDeleteQuery(long id) - { + public ProductDeleteQuery(long id) { mId = id; } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); dao.delete(mId); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadAllQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadAllQuery.java index ee98ff8..3eca6c1 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadAllQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadAllQuery.java @@ -6,37 +6,26 @@ import java.util.List; - -public class ProductReadAllQuery extends Query -{ +public class ProductReadAllQuery extends Query { private int mLimit = -1; private int mOffset = -1; - - public ProductReadAllQuery() - { + public ProductReadAllQuery() { } - - public ProductReadAllQuery(int limit, int offset) - { + public ProductReadAllQuery(int limit, int offset) { mLimit = limit; mOffset = offset; } - @Override - public Data> processData() - { + public Data> processData() { ProductDAO dao = new ProductDAO(); List list; - if(mLimit == -1 && mOffset == -1) - { + if (mLimit == -1 && mOffset == -1) { list = dao.readAll(); - } - else - { + } else { list = dao.readAll(mLimit, mOffset); } diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadFirstQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadFirstQuery.java index 00b58bc..25469b4 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadFirstQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadFirstQuery.java @@ -4,17 +4,12 @@ import com.example.database.data.Data; import com.example.entity.ProductEntity; - -public class ProductReadFirstQuery extends Query -{ - public ProductReadFirstQuery() - { +public class ProductReadFirstQuery extends Query { + public ProductReadFirstQuery() { } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); ProductEntity e = dao.readFirst(); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadQuery.java index c31e3ca..a87c0a1 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductReadQuery.java @@ -4,21 +4,15 @@ import com.example.database.data.Data; import com.example.entity.ProductEntity; - -public class ProductReadQuery extends Query -{ +public class ProductReadQuery extends Query { private long mId; - - public ProductReadQuery(long id) - { + public ProductReadQuery(long id) { mId = id; } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); ProductEntity e = dao.read(mId); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductUpdateQuery.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductUpdateQuery.java index adb09b6..cf820c7 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductUpdateQuery.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/ProductUpdateQuery.java @@ -4,21 +4,15 @@ import com.example.database.data.Data; import com.example.entity.ProductEntity; - -public class ProductUpdateQuery extends Query -{ +public class ProductUpdateQuery extends Query { private ProductEntity mProduct; - - public ProductUpdateQuery(ProductEntity product) - { + public ProductUpdateQuery(ProductEntity product) { mProduct = product; } - @Override - public Data processData() - { + public Data processData() { ProductDAO dao = new ProductDAO(); long id = dao.update(mProduct); diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/Query.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/Query.java index bf4ff94..872da31 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/Query.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/database/query/Query.java @@ -4,23 +4,16 @@ import com.example.database.data.Data; - -public abstract class Query -{ +public abstract class Query { private Bundle mMetaData = null; - public abstract Data processData(); - - public Bundle getMetaData() - { + public Bundle getMetaData() { return mMetaData; } - - public void setMetaData(Bundle metaData) - { + public void setMetaData(Bundle metaData) { mMetaData = metaData; } } diff --git a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/fragment/ExampleFragment.java b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/fragment/ExampleFragment.java index e464ae0..f020843 100644 --- a/Deprecated/Src-DatabaseCall-ActiveAndroid/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-DatabaseCall-ActiveAndroid/java/fragment/ExampleFragment.java @@ -24,42 +24,31 @@ import java.util.List; - -public class ExampleFragment extends TaskFragment implements DatabaseCallListener -{ +public class ExampleFragment extends TaskFragment implements DatabaseCallListener { private View mRootView; private DatabaseCallManager mDatabaseCallManager = new DatabaseCallManager(); - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks mDatabaseCallManager.cancelAllTasks(); } - @Override - public void onDatabaseCallRespond(final DatabaseCallTask task, final Data data) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getQuery().getClass().equals(ProductCreateQuery.class)) - { + public void onDatabaseCallRespond(final DatabaseCallTask task, final Data data) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getQuery().getClass().equals(ProductCreateQuery.class)) { Logcat.d("ProductCreateQuery"); // data @@ -67,9 +56,7 @@ public void run() long id = productCreateData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductReadQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadQuery.class)) { Logcat.d("ProductReadQuery"); // data @@ -77,9 +64,7 @@ else if(task.getQuery().getClass().equals(ProductReadQuery.class)) ProductEntity product = productReadData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductReadFirstQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadFirstQuery.class)) { Logcat.d("ProductReadFirstQuery"); // data @@ -87,9 +72,7 @@ else if(task.getQuery().getClass().equals(ProductReadFirstQuery.class)) ProductEntity product = productReadFirstData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadAllQuery.class)) { Logcat.d("ProductReadAllQuery"); // data @@ -97,9 +80,7 @@ else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) List productList = productReadAllData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductUpdateQuery.class)) { Logcat.d("ProductUpdateQuery"); // data @@ -107,18 +88,14 @@ else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) long id = productUpdateData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductDeleteQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteQuery.class)) { Logcat.d("ProductDeleteQuery"); // data Data productDeleteData = (Data) data; // TODO - } - else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) { Logcat.d("ProductDeleteAllQuery"); // data @@ -131,47 +108,30 @@ else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) mDatabaseCallManager.finishTask(task); // hide progress popup - if(mDatabaseCallManager.getTasksCount() == 0) showProgress(false); + if (mDatabaseCallManager.getTasksCount() == 0) showProgress(false); } }); } - @Override - public void onDatabaseCallFail(final DatabaseCallTask task, final Exception exception) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getQuery().getClass().equals(ProductCreateQuery.class)) - { + public void onDatabaseCallFail(final DatabaseCallTask task, final Exception exception) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getQuery().getClass().equals(ProductCreateQuery.class)) { Logcat.d("ProductCreateQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductReadQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadQuery.class)) { Logcat.d("ProductReadQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductReadFirstQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadFirstQuery.class)) { Logcat.d("ProductReadFirstQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadAllQuery.class)) { Logcat.d("ProductReadAllQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductUpdateQuery.class)) { Logcat.d("ProductUpdateQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductDeleteQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteQuery.class)) { Logcat.d("ProductDeleteQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) { Logcat.d("ProductDeleteAllQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); } @@ -179,14 +139,12 @@ else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) mDatabaseCallManager.finishTask(task); // hide progress popup - if(mDatabaseCallManager.getTasksCount() == 0) showProgress(false); + if (mDatabaseCallManager.getTasksCount() == 0) showProgress(false); } }); } - - private void createProduct(ProductEntity product) - { + private void createProduct(ProductEntity product) { // show progress popup showProgress(true); @@ -195,9 +153,7 @@ private void createProduct(ProductEntity product) mDatabaseCallManager.executeTask(query, this); } - - private void readProduct(long id) - { + private void readProduct(long id) { // show progress popup showProgress(true); @@ -206,9 +162,7 @@ private void readProduct(long id) mDatabaseCallManager.executeTask(query, this); } - - private void readFirstProduct() - { + private void readFirstProduct() { // show progress popup showProgress(true); @@ -217,9 +171,7 @@ private void readFirstProduct() mDatabaseCallManager.executeTask(query, this); } - - private void readAllProducts() - { + private void readAllProducts() { // show progress popup showProgress(true); @@ -228,9 +180,7 @@ private void readAllProducts() mDatabaseCallManager.executeTask(query, this); } - - private void updateProduct(ProductEntity product) - { + private void updateProduct(ProductEntity product) { // show progress popup showProgress(true); @@ -239,9 +189,7 @@ private void updateProduct(ProductEntity product) mDatabaseCallManager.executeTask(query, this); } - - private void deleteProduct(long id) - { + private void deleteProduct(long id) { // show progress popup showProgress(true); @@ -250,9 +198,7 @@ private void deleteProduct(long id) mDatabaseCallManager.executeTask(query, this); } - - private void deleteAllProducts() - { + private void deleteAllProducts() { // show progress popup showProgress(true); diff --git a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallListener.java b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallListener.java index 9cc7a26..1b7dda3 100644 --- a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallListener.java +++ b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallListener.java @@ -2,9 +2,7 @@ import com.example.database.data.Data; - -public interface DatabaseCallListener -{ +public interface DatabaseCallListener { void onDatabaseCallRespond(DatabaseCallTask task, Data data); void onDatabaseCallFail(DatabaseCallTask task, Exception exception); } diff --git a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallManager.java b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallManager.java index 431c132..e218597 100644 --- a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallManager.java +++ b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallManager.java @@ -10,81 +10,58 @@ import java.util.LinkedList; import java.util.List; - -public class DatabaseCallManager -{ +public class DatabaseCallManager { private List mTaskList = new LinkedList<>(); - - public DatabaseCallManager() - { + public DatabaseCallManager() { } - - public void executeTask(Query query, DatabaseCallListener listener) - { + public void executeTask(Query query, DatabaseCallListener listener) { DatabaseCallTask task = new DatabaseCallTask(query, listener); mTaskList.add(task); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // use AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - else - { + } else { task.execute(); } } - - public boolean finishTask(DatabaseCallTask task) - { + public boolean finishTask(DatabaseCallTask task) { return mTaskList.remove(task); } - - public int getTasksCount() - { + public int getTasksCount() { return mTaskList.size(); } - - public boolean hasRunningTask(Class queryClass) - { + public boolean hasRunningTask(Class queryClass) { String className = queryClass.getSimpleName(); - for(DatabaseCallTask task : mTaskList) - { + for (DatabaseCallTask task : mTaskList) { String taskName = task.getQuery().getClass().getSimpleName(); - if(className.equals(taskName)) return true; + if (className.equals(taskName)) return true; } return false; } - - public void cancelAllTasks() - { - for(int i = mTaskList.size() - 1; i >= 0; i--) - { + public void cancelAllTasks() { + for (int i = mTaskList.size() - 1; i >= 0; i--) { DatabaseCallTask task = mTaskList.get(i); - if(task != null) - { + if (task != null) { task.cancel(true); mTaskList.remove(task); } } } - - public void printRunningTasks() - { - for(DatabaseCallTask task : mTaskList) - { + public void printRunningTasks() { + for (DatabaseCallTask task : mTaskList) { Logcat.d(task == null ? "null" : (task.getQuery().getClass().getSimpleName() + " " + task.getStatus().toString())); } - if(mTaskList.isEmpty()) Logcat.d("empty"); + if (mTaskList.isEmpty()) Logcat.d("empty"); } } diff --git a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallTask.java b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallTask.java index fb02004..5d2f0e4 100644 --- a/Deprecated/Src-DatabaseCall/java/database/DatabaseCallTask.java +++ b/Deprecated/Src-DatabaseCall/java/database/DatabaseCallTask.java @@ -9,75 +9,54 @@ import java.lang.ref.WeakReference; - -public class DatabaseCallTask extends AsyncTask> -{ +public class DatabaseCallTask extends AsyncTask> { private Query mQuery; private WeakReference mListener; private Exception mException = null; - - public DatabaseCallTask(Query query, DatabaseCallListener listener) - { + public DatabaseCallTask(Query query, DatabaseCallListener listener) { mQuery = query; setListener(listener); } - @Override - protected Data doInBackground(Void... params) - { - try - { + protected Data doInBackground(Void... params) { + try { Data data = mQuery.processData(); - if(isCancelled()) return null; + if (isCancelled()) return null; else return data; - } - catch(Exception e) - { + } catch (Exception e) { mException = e; e.printStackTrace(); return null; } } - @Override - protected void onPostExecute(Data data) - { - if(isCancelled()) return; + protected void onPostExecute(Data data) { + if (isCancelled()) return; DatabaseCallListener listener = mListener.get(); - if(listener != null) - { - if(data != null) - { + if (listener != null) { + if (data != null) { listener.onDatabaseCallRespond(this, data); - } - else - { + } else { listener.onDatabaseCallFail(this, mException); } } } - @Override - protected void onCancelled() - { + protected void onCancelled() { Logcat.d(""); } - - public Query getQuery() - { + public Query getQuery() { return mQuery; } - - public void setListener(DatabaseCallListener listener) - { + public void setListener(DatabaseCallListener listener) { mListener = new WeakReference<>(listener); } } diff --git a/Deprecated/Src-DatabaseCall/java/database/DatabaseHelper.java b/Deprecated/Src-DatabaseCall/java/database/DatabaseHelper.java index 4ac16c9..0786e86 100644 --- a/Deprecated/Src-DatabaseCall/java/database/DatabaseHelper.java +++ b/Deprecated/Src-DatabaseCall/java/database/DatabaseHelper.java @@ -11,9 +11,7 @@ import org.alfonz.utility.Logcat; - -public class DatabaseHelper extends OrmLiteSqliteOpenHelper -{ +public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DATABASE_NAME = "example.db"; private static final int DATABASE_VERSION = 1; @@ -21,92 +19,64 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper private Dao mProductDao = null; - - private DatabaseHelper() - { + private DatabaseHelper() { super(ExampleApplication.getContext(), DATABASE_NAME, null, DATABASE_VERSION); } - // singleton - public static synchronized DatabaseHelper getInstance() - { - if(sInstance == null) sInstance = new DatabaseHelper(); + public static synchronized DatabaseHelper getInstance() { + if (sInstance == null) sInstance = new DatabaseHelper(); return sInstance; } - @Override - public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) - { - try - { + public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { + try { Logcat.d(""); TableUtils.createTable(connectionSource, ProductModel.class); - } - catch(android.database.SQLException e) - { + } catch (android.database.SQLException e) { Logcat.e(e, "can't create database"); e.printStackTrace(); - } - catch(java.sql.SQLException e) - { + } catch (java.sql.SQLException e) { Logcat.e(e, "can't create database"); e.printStackTrace(); } } - @Override - public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) - { - try - { + public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { + try { Logcat.d(""); // TODO: database migration - } - catch(android.database.SQLException e) - { + } catch (android.database.SQLException e) { Logcat.e(e, "can't upgrade database"); e.printStackTrace(); } } - @Override - public void close() - { + public void close() { super.close(); mProductDao = null; } - - public synchronized void clearDatabase() - { - try - { + public synchronized void clearDatabase() { + try { Logcat.d(""); TableUtils.dropTable(getConnectionSource(), ProductModel.class, true); TableUtils.createTable(getConnectionSource(), ProductModel.class); - } - catch(android.database.SQLException e) - { + } catch (android.database.SQLException e) { Logcat.e(e, "can't clear database"); e.printStackTrace(); - } - catch(java.sql.SQLException e) - { + } catch (java.sql.SQLException e) { Logcat.e(e, "can't clear database"); e.printStackTrace(); } } - - public synchronized Dao getProductDao() throws java.sql.SQLException - { - if(mProductDao == null) - { + public synchronized Dao getProductDao() throws java.sql.SQLException { + if (mProductDao == null) { mProductDao = getDao(ProductModel.class); } return mProductDao; diff --git a/Deprecated/Src-DatabaseCall/java/database/dao/DAO.java b/Deprecated/Src-DatabaseCall/java/database/dao/DAO.java index 9610d45..6ae6dbd 100644 --- a/Deprecated/Src-DatabaseCall/java/database/dao/DAO.java +++ b/Deprecated/Src-DatabaseCall/java/database/dao/DAO.java @@ -6,18 +6,12 @@ import java.sql.SQLException; - -public class DAO -{ - public static void printDatabaseInfo() - { +public class DAO { + public static void printDatabaseInfo() { DatabaseHelper databaseHelper = DatabaseHelper.getInstance(); - try - { + try { Logcat.d("%d products", databaseHelper.getProductDao().countOf()); - } - catch(SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } } diff --git a/Deprecated/Src-DatabaseCall/java/database/dao/ProductDAO.java b/Deprecated/Src-DatabaseCall/java/database/dao/ProductDAO.java index e8d4da7..5e94c7f 100644 --- a/Deprecated/Src-DatabaseCall/java/database/dao/ProductDAO.java +++ b/Deprecated/Src-DatabaseCall/java/database/dao/ProductDAO.java @@ -9,33 +9,23 @@ import java.sql.SQLException; import java.util.List; - -public class ProductDAO extends DAO -{ - public static int create(ProductModel product) throws SQLException - { +public class ProductDAO extends DAO { + public static int create(ProductModel product) throws SQLException { Dao dao = getDao(); return dao.create(product); } - - public static ProductModel read(long id) throws SQLException - { + public static ProductModel read(long id) throws SQLException { Dao dao = getDao(); return dao.queryForId(id); } - - public static List readAll(long skip, long take) throws SQLException - { + public static List readAll(long skip, long take) throws SQLException { Dao dao = getDao(); List list; - if(skip == -1L && take == -1L) - { + if (skip == -1L && take == -1L) { list = dao.queryForAll(); - } - else - { + } else { QueryBuilder queryBuilder = dao.queryBuilder(); queryBuilder.offset(skip).limit(take); list = dao.query(queryBuilder.prepare()); @@ -43,38 +33,28 @@ public static List readAll(long skip, long take) throws SQLExcepti return list; } - - public static int update(ProductModel product) throws SQLException - { + public static int update(ProductModel product) throws SQLException { Dao dao = getDao(); return dao.update(product); } - - public static int delete(long id) throws SQLException - { + public static int delete(long id) throws SQLException { Dao dao = getDao(); return dao.deleteById(id); } - - public static int deleteAll() throws SQLException - { + public static int deleteAll() throws SQLException { Dao dao = getDao(); DeleteBuilder deleteBuilder = dao.deleteBuilder(); return dao.delete(deleteBuilder.prepare()); } - - public static int refresh(ProductModel product) throws SQLException - { + public static int refresh(ProductModel product) throws SQLException { Dao dao = getDao(); return dao.refresh(product); } - - private static Dao getDao() throws SQLException - { + private static Dao getDao() throws SQLException { DatabaseHelper databaseHelper = DatabaseHelper.getInstance(); return databaseHelper.getProductDao(); } diff --git a/Deprecated/Src-DatabaseCall/java/database/data/Data.java b/Deprecated/Src-DatabaseCall/java/database/data/Data.java index cb2fde9..bd3f6d6 100644 --- a/Deprecated/Src-DatabaseCall/java/database/data/Data.java +++ b/Deprecated/Src-DatabaseCall/java/database/data/Data.java @@ -1,24 +1,16 @@ package com.example.database.data; - -public class Data -{ +public class Data { private T mDataObject; - - public Data() - { + public Data() { } - - public T getDataObject() - { + public T getDataObject() { return mDataObject; } - - public void setDataObject(T dataObject) - { + public void setDataObject(T dataObject) { mDataObject = dataObject; } } diff --git a/Deprecated/Src-DatabaseCall/java/database/model/ProductModel.java b/Deprecated/Src-DatabaseCall/java/database/model/ProductModel.java index c048876..ad0898c 100644 --- a/Deprecated/Src-DatabaseCall/java/database/model/ProductModel.java +++ b/Deprecated/Src-DatabaseCall/java/database/model/ProductModel.java @@ -4,10 +4,8 @@ import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; - @DatabaseTable -public class ProductModel -{ +public class ProductModel { public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_QUANTITY = "quantity"; @@ -20,15 +18,11 @@ public class ProductModel @DatabaseField(columnName = COLUMN_TIMESTAMP) private long timestamp; @DatabaseField(columnName = COLUMN_PRICE) private double price; - // empty constructor - public ProductModel() - { + public ProductModel() { } - - public ProductEntity toEntity() - { + public ProductEntity toEntity() { ProductEntity e = new ProductEntity(); e.setId(id); e.setName(name); @@ -38,72 +32,50 @@ public ProductEntity toEntity() return e; } - - public void set(ProductEntity e) - { + public void set(ProductEntity e) { name = e.getName(); quantity = e.getQuantity(); timestamp = e.getTimestamp(); price = e.getPrice(); } - - public long getId() - { + public long getId() { return id; } - - public void setId(long id) - { + public void setId(long id) { this.id = id; } - - public String getName() - { + public String getName() { return name; } - - public void setName(String name) - { + public void setName(String name) { this.name = name; } - - public int getQuantity() - { + public int getQuantity() { return quantity; } - - public void setQuantity(int quantity) - { + public void setQuantity(int quantity) { this.quantity = quantity; } - - public long getTimestamp() - { + public long getTimestamp() { return timestamp; } - - public void setTimestamp(long timestamp) - { + public void setTimestamp(long timestamp) { this.timestamp = timestamp; } - - public double getPrice() - { + public double getPrice() { return price; } - - public void setPrice(double price) - { + public void setPrice(double price) { this.price = price; } } diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductCreateQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductCreateQuery.java index 165638a..bcdb732 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductCreateQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductCreateQuery.java @@ -6,21 +6,15 @@ import java.sql.SQLException; - -public class ProductCreateQuery extends Query -{ +public class ProductCreateQuery extends Query { private ProductModel mProduct; - - public ProductCreateQuery(ProductModel product) - { + public ProductCreateQuery(ProductModel product) { mProduct = product; } - @Override - public Data processData() throws SQLException - { + public Data processData() throws SQLException { Data data = new Data<>(); data.setDataObject(ProductDAO.create(mProduct)); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteAllQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteAllQuery.java index e169d90..5046a1a 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteAllQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteAllQuery.java @@ -5,17 +5,12 @@ import java.sql.SQLException; - -public class ProductDeleteAllQuery extends Query -{ - public ProductDeleteAllQuery() - { +public class ProductDeleteAllQuery extends Query { + public ProductDeleteAllQuery() { } - @Override - public Data processData() throws SQLException - { + public Data processData() throws SQLException { Data data = new Data<>(); data.setDataObject(ProductDAO.deleteAll()); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteQuery.java index 598d4ff..62cb3a5 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductDeleteQuery.java @@ -5,21 +5,15 @@ import java.sql.SQLException; - -public class ProductDeleteQuery extends Query -{ +public class ProductDeleteQuery extends Query { private long mId; - - public ProductDeleteQuery(long id) - { + public ProductDeleteQuery(long id) { mId = id; } - @Override - public Data processData() throws SQLException - { + public Data processData() throws SQLException { Data data = new Data<>(); data.setDataObject(ProductDAO.delete(mId)); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductReadAllQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductReadAllQuery.java index 4454a67..b3b34fe 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductReadAllQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductReadAllQuery.java @@ -7,28 +7,20 @@ import java.sql.SQLException; import java.util.List; - -public class ProductReadAllQuery extends Query -{ +public class ProductReadAllQuery extends Query { private long mSkip = -1L; private long mTake = -1L; - - public ProductReadAllQuery() - { + public ProductReadAllQuery() { } - - public ProductReadAllQuery(long skip, long take) - { + public ProductReadAllQuery(long skip, long take) { mSkip = skip; mTake = take; } - @Override - public Data> processData() throws SQLException - { + public Data> processData() throws SQLException { Data> data = new Data<>(); data.setDataObject(ProductDAO.readAll(mSkip, mTake)); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductReadQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductReadQuery.java index a11e331..89fd66c 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductReadQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductReadQuery.java @@ -6,21 +6,15 @@ import java.sql.SQLException; - -public class ProductReadQuery extends Query -{ +public class ProductReadQuery extends Query { private long mId; - - public ProductReadQuery(long id) - { + public ProductReadQuery(long id) { mId = id; } - @Override - public Data processData() throws SQLException - { + public Data processData() throws SQLException { Data data = new Data<>(); data.setDataObject(ProductDAO.read(mId)); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/ProductUpdateQuery.java b/Deprecated/Src-DatabaseCall/java/database/query/ProductUpdateQuery.java index f55a900..8d65128 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/ProductUpdateQuery.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/ProductUpdateQuery.java @@ -6,21 +6,15 @@ import java.sql.SQLException; - -public class ProductUpdateQuery extends Query -{ +public class ProductUpdateQuery extends Query { private ProductModel mProduct; - - public ProductUpdateQuery(ProductModel product) - { + public ProductUpdateQuery(ProductModel product) { mProduct = product; } - @Override - public Data processData() throws SQLException - { + public Data processData() throws SQLException { Data data = new Data<>(); data.setDataObject(ProductDAO.update(mProduct)); return data; diff --git a/Deprecated/Src-DatabaseCall/java/database/query/Query.java b/Deprecated/Src-DatabaseCall/java/database/query/Query.java index 2870034..255879a 100644 --- a/Deprecated/Src-DatabaseCall/java/database/query/Query.java +++ b/Deprecated/Src-DatabaseCall/java/database/query/Query.java @@ -6,23 +6,16 @@ import java.sql.SQLException; - -public abstract class Query -{ +public abstract class Query { private Bundle mMetaData = null; - public abstract Data processData() throws SQLException; - - public Bundle getMetaData() - { + public Bundle getMetaData() { return mMetaData; } - - public void setMetaData(Bundle metaData) - { + public void setMetaData(Bundle metaData) { mMetaData = metaData; } } diff --git a/Deprecated/Src-DatabaseCall/java/entity/ProductEntity.java b/Deprecated/Src-DatabaseCall/java/entity/ProductEntity.java index 6d68fad..b313757 100644 --- a/Deprecated/Src-DatabaseCall/java/entity/ProductEntity.java +++ b/Deprecated/Src-DatabaseCall/java/entity/ProductEntity.java @@ -1,88 +1,62 @@ package com.example.entity; - -public class ProductEntity -{ +public class ProductEntity { private long id; private String name; private int quantity; private long timestamp; private double price; - // empty constructor - public ProductEntity() - { + public ProductEntity() { } - // copy constructor - public ProductEntity(ProductEntity origin) - { + public ProductEntity(ProductEntity origin) { id = origin.id; - if(origin.name != null) name = new String(origin.name); + if (origin.name != null) name = new String(origin.name); quantity = origin.quantity; timestamp = origin.timestamp; price = origin.price; } - - public long getId() - { + public long getId() { return id; } - - public void setId(long id) - { + public void setId(long id) { this.id = id; } - - public String getName() - { + public String getName() { return name; } - - public void setName(String name) - { + public void setName(String name) { this.name = name; } - - public int getQuantity() - { + public int getQuantity() { return quantity; } - - public void setQuantity(int quantity) - { + public void setQuantity(int quantity) { this.quantity = quantity; } - - public long getTimestamp() - { + public long getTimestamp() { return timestamp; } - - public void setTimestamp(long timestamp) - { + public void setTimestamp(long timestamp) { this.timestamp = timestamp; } - - public double getPrice() - { + public double getPrice() { return price; } - - public void setPrice(double price) - { + public void setPrice(double price) { this.price = price; } } diff --git a/Deprecated/Src-DatabaseCall/java/fragment/ExampleFragment.java b/Deprecated/Src-DatabaseCall/java/fragment/ExampleFragment.java index bfde7b9..1588ade 100644 --- a/Deprecated/Src-DatabaseCall/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-DatabaseCall/java/fragment/ExampleFragment.java @@ -23,42 +23,31 @@ import java.util.List; - -public class ExampleFragment extends TaskFragment implements DatabaseCallListener -{ +public class ExampleFragment extends TaskFragment implements DatabaseCallListener { private View mRootView; private DatabaseCallManager mDatabaseCallManager = new DatabaseCallManager(); - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks mDatabaseCallManager.cancelAllTasks(); } - @Override - public void onDatabaseCallRespond(final DatabaseCallTask task, final Data data) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getQuery().getClass().equals(ProductCreateQuery.class)) - { + public void onDatabaseCallRespond(final DatabaseCallTask task, final Data data) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getQuery().getClass().equals(ProductCreateQuery.class)) { Logcat.d("ProductCreateQuery"); // data @@ -66,9 +55,7 @@ public void run() int rows = productCreateData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductReadQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadQuery.class)) { Logcat.d("ProductReadQuery"); // data @@ -76,9 +63,7 @@ else if(task.getQuery().getClass().equals(ProductReadQuery.class)) ProductModel product = productReadData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadAllQuery.class)) { Logcat.d("ProductReadAllQuery"); // data @@ -86,9 +71,7 @@ else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) List productList = productReadAllData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductUpdateQuery.class)) { Logcat.d("ProductUpdateQuery"); // data @@ -96,9 +79,7 @@ else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) int rows = productUpdateData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductDeleteQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteQuery.class)) { Logcat.d("ProductDeleteQuery"); // data @@ -106,9 +87,7 @@ else if(task.getQuery().getClass().equals(ProductDeleteQuery.class)) int rows = productDeleteData.getDataObject(); // TODO - } - else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) { Logcat.d("ProductDeleteAllQuery"); // data @@ -122,43 +101,28 @@ else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) mDatabaseCallManager.finishTask(task); // hide progress popup - if(mDatabaseCallManager.getTasksCount() == 0) showProgress(false); + if (mDatabaseCallManager.getTasksCount() == 0) showProgress(false); } }); } - @Override - public void onDatabaseCallFail(final DatabaseCallTask task, final Exception exception) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed - - if(task.getQuery().getClass().equals(ProductCreateQuery.class)) - { + public void onDatabaseCallFail(final DatabaseCallTask task, final Exception exception) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed + + if (task.getQuery().getClass().equals(ProductCreateQuery.class)) { Logcat.d("ProductCreateQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductReadQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadQuery.class)) { Logcat.d("ProductReadQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductReadAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductReadAllQuery.class)) { Logcat.d("ProductReadAllQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductUpdateQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductUpdateQuery.class)) { Logcat.d("ProductUpdateQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductDeleteQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteQuery.class)) { Logcat.d("ProductDeleteQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); - } - else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) - { + } else if (task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) { Logcat.d("ProductDeleteAllQuery / exception " + exception.getClass().getSimpleName() + " / " + exception.getMessage()); } @@ -166,14 +130,12 @@ else if(task.getQuery().getClass().equals(ProductDeleteAllQuery.class)) mDatabaseCallManager.finishTask(task); // hide progress popup - if(mDatabaseCallManager.getTasksCount() == 0) showProgress(false); + if (mDatabaseCallManager.getTasksCount() == 0) showProgress(false); } }); } - - private void createProduct(ProductModel product) - { + private void createProduct(ProductModel product) { // show progress popup showProgress(true); @@ -182,9 +144,7 @@ private void createProduct(ProductModel product) mDatabaseCallManager.executeTask(query, this); } - - private void readProduct(long id) - { + private void readProduct(long id) { // show progress popup showProgress(true); @@ -193,9 +153,7 @@ private void readProduct(long id) mDatabaseCallManager.executeTask(query, this); } - - private void readAllProducts() - { + private void readAllProducts() { // show progress popup showProgress(true); @@ -204,9 +162,7 @@ private void readAllProducts() mDatabaseCallManager.executeTask(query, this); } - - private void updateProduct(ProductModel product) - { + private void updateProduct(ProductModel product) { // show progress popup showProgress(true); @@ -215,9 +171,7 @@ private void updateProduct(ProductModel product) mDatabaseCallManager.executeTask(query, this); } - - private void deleteProduct(long id) - { + private void deleteProduct(long id) { // show progress popup showProgress(true); @@ -226,9 +180,7 @@ private void deleteProduct(long id) mDatabaseCallManager.executeTask(query, this); } - - private void deleteAllProducts() - { + private void deleteAllProducts() { // show progress popup showProgress(true); diff --git a/Deprecated/Src-Dialog-Style/java/dialog/ExampleDialogFragment.java b/Deprecated/Src-Dialog-Style/java/dialog/ExampleDialogFragment.java index dc3f6e7..873e372 100644 --- a/Deprecated/Src-Dialog-Style/java/dialog/ExampleDialogFragment.java +++ b/Deprecated/Src-Dialog-Style/java/dialog/ExampleDialogFragment.java @@ -10,12 +10,9 @@ import com.example.utility.DialogStyle; - -public class ExampleDialogFragment extends DialogFragment -{ +public class ExampleDialogFragment extends DialogFragment { @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { ContextThemeWrapper context = new ContextThemeWrapper(getActivity(), getTheme(true)); AlertDialog.Builder builder = new AlertDialog.Builder(context); @@ -27,19 +24,13 @@ public Dialog onCreateDialog(Bundle savedInstanceState) final Dialog dialog = builder.create(); // override style - dialog.setOnShowListener(new DialogInterface.OnShowListener() - { + dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override - public void onShow(DialogInterface dialogInterface) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) - { - try - { + public void onShow(DialogInterface dialogInterface) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + try { DialogStyle.overrideStyle(getActivity(), dialog, true); - } - catch(Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } @@ -49,19 +40,12 @@ public void onShow(DialogInterface dialogInterface) return dialog; } - - private int getTheme(boolean light) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) - { + private int getTheme(boolean light) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return light ? android.R.style.Theme_DeviceDefault_Light_Dialog : android.R.style.Theme_DeviceDefault_Dialog; - } - else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - { + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return light ? android.R.style.Theme_Holo_Light_Dialog : android.R.style.Theme_Holo_Dialog; - } - else - { + } else { return android.R.style.Theme_Dialog; } } diff --git a/Deprecated/Src-Dialog-Style/java/utility/DialogStyle.java b/Deprecated/Src-Dialog-Style/java/utility/DialogStyle.java index ca45143..c59a7d1 100644 --- a/Deprecated/Src-Dialog-Style/java/utility/DialogStyle.java +++ b/Deprecated/Src-Dialog-Style/java/utility/DialogStyle.java @@ -18,19 +18,15 @@ import java.util.ArrayList; import java.util.List; - // original AlertDialog implementation, layout and style: // https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/AlertDialog.java // https://github.com/android/platform_frameworks_base/blob/master/core/java/com/android/internal/app/AlertController.java // https://github.com/android/platform_frameworks_base/blob/master/core/res/res/layout/alert_dialog_holo.xml // https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml -public final class DialogStyle -{ +public final class DialogStyle { private DialogStyle() {} - - public static void overrideStyle(Context context, AlertDialog dialog, boolean light) - { + public static void overrideStyle(Context context, AlertDialog dialog, boolean light) { // resources int resourceDialogTitleText = light ? R.color.dialog_title_text_light : R.color.dialog_title_text_dark; int resourceDialogTitleDivider = light ? R.color.dialog_title_divider_light : R.color.dialog_title_divider_dark; @@ -72,28 +68,24 @@ public static void overrideStyle(Context context, AlertDialog dialog, boolean li Button button3View = dialog.findViewById(button3); // dialog background - if(topPanelView != null && contentPanelView != null && customPanelView != null && buttonPanelView != null) - { + if (topPanelView != null && contentPanelView != null && customPanelView != null && buttonPanelView != null) { setBackground(topPanelView, contentPanelView, customPanelView, buttonPanelView, light); } // dialog style - if(alertTitleView != null) + if (alertTitleView != null) alertTitleView.setTextColor(context.getResources().getColor(resourceDialogTitleText)); - if(titleDividerView != null) - { + if (titleDividerView != null) { titleDividerView.setBackgroundColor(context.getResources().getColor(resourceDialogTitleDivider)); ViewGroup.LayoutParams params = titleDividerView.getLayoutParams(); params.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics()); } - if(messageView != null) messageView.setTextColor(context.getResources().getColor(resourceDialogMessageText)); - if(selectDialogListviewView != null) - { + if (messageView != null) messageView.setTextColor(context.getResources().getColor(resourceDialogMessageText)); + if (selectDialogListviewView != null) { selectDialogListviewView.setSelector(resourceSelectorDialogButtonBg); selectDialogListviewView.setDivider(context.getResources().getDrawable(resourceShapeDialogDividerHorizontal)); } - if(button1View != null) - { + if (button1View != null) { button1View.setTextColor(context.getResources().getColor(resourceDialogButtonText)); button1View.setBackgroundResource(resourceSelectorDialogButtonBg); button1View.setTypeface(Typeface.DEFAULT); @@ -102,8 +94,7 @@ public static void overrideStyle(Context context, AlertDialog dialog, boolean li params.setMargins(0, 0, 0, 0); button1View.setLayoutParams(params); } - if(button2View != null) - { + if (button2View != null) { button2View.setTextColor(context.getResources().getColor(resourceDialogButtonText)); button2View.setBackgroundResource(resourceSelectorDialogButtonBg); button2View.setTypeface(Typeface.DEFAULT); @@ -112,8 +103,7 @@ public static void overrideStyle(Context context, AlertDialog dialog, boolean li params.setMargins(0, 0, 0, 0); button2View.setLayoutParams(params); } - if(button3View != null) - { + if (button3View != null) { button3View.setTextColor(context.getResources().getColor(resourceDialogButtonText)); button3View.setBackgroundResource(resourceSelectorDialogButtonBg); button3View.setTypeface(Typeface.DEFAULT); @@ -122,28 +112,22 @@ public static void overrideStyle(Context context, AlertDialog dialog, boolean li params.setMargins(0, 0, 0, 0); button3View.setLayoutParams(params); } - if(buttonPanelView != null) - { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - { + if (buttonPanelView != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { buttonPanelView.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING); buttonPanelView.setDividerDrawable(context.getResources().getDrawable(resourceShapeDialogDividerHorizontal)); } } - if(buttonPanelChildView != null) - { + if (buttonPanelChildView != null) { buttonPanelChildView.setPadding(0, 0, 0, 0); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { buttonPanelChildView.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); buttonPanelChildView.setDividerDrawable(context.getResources().getDrawable(resourceShapeDialogDividerVertical)); } } } - - private static void setBackground(LinearLayout topPanelView, LinearLayout contentPanelView, FrameLayout customPanelView, LinearLayout buttonPanelView, boolean light) - { + private static void setBackground(LinearLayout topPanelView, LinearLayout contentPanelView, FrameLayout customPanelView, LinearLayout buttonPanelView, boolean light) { int resourceDialogFullHolo = light ? R.drawable.dialog_full_holo_light : R.drawable.dialog_full_holo_dark; int resourceDialogTopHolo = light ? R.drawable.dialog_top_holo_light : R.drawable.dialog_top_holo_dark; int resourceDialogMiddleHolo = light ? R.drawable.dialog_middle_holo_light : R.drawable.dialog_middle_holo_dark; @@ -155,27 +139,23 @@ private static void setBackground(LinearLayout topPanelView, LinearLayout conten boolean buttonPanelVisible = buttonPanelView.getVisibility() == View.VISIBLE; List views = new ArrayList<>(); - if(topPanelVisible) views.add(topPanelView); - if(contentPanelVisible) views.add(contentPanelView); - if(customPanelVisible) views.add(customPanelView); - if(buttonPanelVisible) views.add(buttonPanelView); + if (topPanelVisible) views.add(topPanelView); + if (contentPanelVisible) views.add(contentPanelView); + if (customPanelVisible) views.add(customPanelView); + if (buttonPanelVisible) views.add(buttonPanelView); - if(views.size() == 1) - { + if (views.size() == 1) { View v = views.get(0); v.setBackgroundResource(resourceDialogFullHolo); - } - else - { - for(int i = 0; i < views.size(); i++) - { + } else { + for (int i = 0; i < views.size(); i++) { View v = views.get(i); // top - if(i == 0) v.setBackgroundResource(resourceDialogTopHolo); + if (i == 0) v.setBackgroundResource(resourceDialogTopHolo); // bottom - else if(i == views.size() - 1) v.setBackgroundResource(resourceDialogBottomHolo); + else if (i == views.size() - 1) v.setBackgroundResource(resourceDialogBottomHolo); // middle else v.setBackgroundResource(resourceDialogMiddleHolo); diff --git a/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_dark.xml b/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_dark.xml index e30001e..1dde189 100644 --- a/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_dark.xml +++ b/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_dark.xml @@ -1,9 +1,14 @@ - - - - - + + + + + diff --git a/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_light.xml b/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_light.xml index 0b97395..85dd5d0 100644 --- a/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_light.xml +++ b/Deprecated/Src-Dialog-Style/res/color/selector_dialog_button_text_light.xml @@ -1,9 +1,14 @@ - - - - - + + + + + diff --git a/Deprecated/Src-GCM/java/activity/ExampleActivity.java b/Deprecated/Src-GCM/java/activity/ExampleActivity.java index 6ad98b5..8056ed1 100644 --- a/Deprecated/Src-GCM/java/activity/ExampleActivity.java +++ b/Deprecated/Src-GCM/java/activity/ExampleActivity.java @@ -14,17 +14,13 @@ import java.io.IOException; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { private GoogleCloudMessaging mGcm; private String mGcmRegistrationId; private AsyncTask mGcmRegisterAsyncTask; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); @@ -32,79 +28,60 @@ public void onCreate(Bundle savedInstanceState) handleGcmRegistration(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); // check Google Play Services GcmUtility.checkPlayServices(this); } - @Override - public void onDestroy() - { + public void onDestroy() { // cancel async tasks - if(mGcmRegisterAsyncTask != null) mGcmRegisterAsyncTask.cancel(true); + if (mGcmRegisterAsyncTask != null) mGcmRegisterAsyncTask.cancel(true); super.onDestroy(); } - - private void handleGcmRegistration() - { + private void handleGcmRegistration() { final Context context = getApplicationContext(); // check device for Play Services APK - if(GcmUtility.checkPlayServices(this)) - { + if (GcmUtility.checkPlayServices(this)) { // registration id mGcm = GoogleCloudMessaging.getInstance(this); mGcmRegistrationId = GcmUtility.getRegistrationId(context); // register device - if(mGcmRegistrationId.isEmpty()) - { - mGcmRegisterAsyncTask = new AsyncTask() - { + if (mGcmRegistrationId.isEmpty()) { + mGcmRegisterAsyncTask = new AsyncTask() { @Override - protected Void doInBackground(Void... params) - { - try - { + protected Void doInBackground(Void... params) { + try { // register on GCM server - if(mGcm == null) mGcm = GoogleCloudMessaging.getInstance(context); + if (mGcm == null) mGcm = GoogleCloudMessaging.getInstance(context); mGcmRegistrationId = mGcm.register(ExampleConfig.GCM_SENDER_ID); // GcmUtility.register() must be called after successfull GoogleCloudMessaging.register(), // because it sets registration id in shared preferences GcmUtility.register(context, mGcmRegistrationId); - } - catch(IOException e) - { + } catch (IOException e) { e.printStackTrace(); } return null; } - @Override - protected void onPostExecute(Void result) - { + protected void onPostExecute(Void result) { mGcmRegisterAsyncTask = null; } }; mGcmRegisterAsyncTask.execute(null, null, null); - } - else - { + } else { Logcat.d("device is already registered on server with id = %s", mGcmRegistrationId); } - } - else - { + } else { Logcat.d("no valid Google Play Services APK found"); } } diff --git a/Deprecated/Src-GCM/java/gcm/GcmBroadcastReceiver.java b/Deprecated/Src-GCM/java/gcm/GcmBroadcastReceiver.java index 06b7405..8643507 100644 --- a/Deprecated/Src-GCM/java/gcm/GcmBroadcastReceiver.java +++ b/Deprecated/Src-GCM/java/gcm/GcmBroadcastReceiver.java @@ -6,12 +6,9 @@ import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; - -public class GcmBroadcastReceiver extends WakefulBroadcastReceiver -{ +public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) - { + public void onReceive(Context context, Intent intent) { ComponentName component = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); startWakefulService(context, (intent.setComponent(component))); setResultCode(Activity.RESULT_OK); diff --git a/Deprecated/Src-GCM/java/gcm/GcmIntentService.java b/Deprecated/Src-GCM/java/gcm/GcmIntentService.java index 30bf4a4..2152916 100644 --- a/Deprecated/Src-GCM/java/gcm/GcmIntentService.java +++ b/Deprecated/Src-GCM/java/gcm/GcmIntentService.java @@ -11,18 +11,13 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; - -public class GcmIntentService extends IntentService -{ - public GcmIntentService() - { +public class GcmIntentService extends IntentService { + public GcmIntentService() { super("GcmIntentService"); } - @Override - protected void onHandleIntent(Intent intent) - { + protected void onHandleIntent(Intent intent) { Logcat.d("received message " + intent.getExtras()); // get message type @@ -31,36 +26,25 @@ protected void onHandleIntent(Intent intent) // handle messages Bundle extras = intent.getExtras(); - if(!extras.isEmpty()) - { - if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) - { + if (!extras.isEmpty()) { + if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Logcat.d("send error " + extras.toString()); - } - else if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) - { + } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { Logcat.d("deleted messages on server " + extras.toString()); - } - else if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) - { + } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { Logcat.d("received " + extras.toString()); // get type String type = intent.getStringExtra("type"); - if(type != null) - { - if(type.equals("message")) - { - try - { + if (type != null) { + if (type.equals("message")) { + try { // decode String text = intent.getStringExtra("text"); - if(text != null) text = URLDecoder.decode(text, "UTF-8"); + if (text != null) text = URLDecoder.decode(text, "UTF-8"); // TODO - } - catch(UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } diff --git a/Deprecated/Src-GCM/java/gcm/GcmUtility.java b/Deprecated/Src-GCM/java/gcm/GcmUtility.java index 61ccbba..7003897 100644 --- a/Deprecated/Src-GCM/java/gcm/GcmUtility.java +++ b/Deprecated/Src-GCM/java/gcm/GcmUtility.java @@ -19,29 +19,20 @@ import java.net.URL; import java.util.Random; - -public final class GcmUtility -{ +public final class GcmUtility { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private static final Random sRandom = new Random(); - private GcmUtility() {} - - public static boolean checkPlayServices(Activity activity) - { + public static boolean checkPlayServices(Activity activity) { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity); - if(resultCode != ConnectionResult.SUCCESS) - { - if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) - { + if (resultCode != ConnectionResult.SUCCESS) { + if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, activity, PLAY_SERVICES_RESOLUTION_REQUEST).show(); - } - else - { + } else { Logcat.e("this device is not supported"); activity.finish(); } @@ -50,15 +41,12 @@ public static boolean checkPlayServices(Activity activity) return true; } - - public static String getRegistrationId(Context context) - { + public static String getRegistrationId(Context context) { Preferences preferences = new Preferences(); // get saved registration id String registrationId = preferences.getGcmRegistrationId(); - if(registrationId.isEmpty()) - { + if (registrationId.isEmpty()) { Logcat.d("registration id not found"); return ""; } @@ -66,8 +54,7 @@ public static String getRegistrationId(Context context) // check if app was updated int registeredVersion = preferences.getGcmVersionCode(); int currentVersion = VersionUtility.getVersionCode(context); - if(registeredVersion != currentVersion) - { + if (registeredVersion != currentVersion) { Logcat.d("app version has changed"); return ""; } @@ -75,10 +62,8 @@ public static String getRegistrationId(Context context) return registrationId; } - // register this account/device pair within the server - public static void register(final Context context, final String registrationId) - { + public static void register(final Context context, final String registrationId) { Logcat.d("registering device with registration id = %s", registrationId); // request url @@ -94,12 +79,10 @@ public static void register(final Context context, final String registrationId) // Once GCM returns a registration id, we need to register it on the server. // As the server might be down, we will retry it a couple times. - for(int i = 1; i <= MAX_ATTEMPTS; i++) - { + for (int i = 1; i <= MAX_ATTEMPTS; i++) { Logcat.d("attempt #%d to register", i); - try - { + try { post(requestUrl, params); // TODO: use post or get Preferences preferences = new Preferences(); @@ -108,22 +91,17 @@ public static void register(final Context context, final String registrationId) Logcat.d("server successfully registered device"); return; - } - catch(IOException e) - { + } catch (IOException e) { // Here we are simplifying and retrying on any error. // In a real application, it should retry only on unrecoverable errors (like HTTP error code 503). Logcat.e("server failed to register on attempt #%d / exception " + e.getMessage(), i); - if(i == MAX_ATTEMPTS) break; + if (i == MAX_ATTEMPTS) break; - try - { + try { Logcat.d("sleeping for %d ms before retry", backoff); Thread.sleep(backoff); - } - catch(InterruptedException interruptedException) - { + } catch (InterruptedException interruptedException) { // activity finished before we complete Logcat.d("thread interrupted so abort remaining retries"); Thread.currentThread().interrupt(); @@ -138,10 +116,8 @@ public static void register(final Context context, final String registrationId) Logcat.d("could not register device on server after %d attempts", MAX_ATTEMPTS); } - // unregister this account/device pair within the server - public static void unregister(final Context context, final String registrationId) - { + public static void unregister(final Context context, final String registrationId) { Logcat.d("unregistering device with registration id = %s", registrationId); // request url @@ -152,8 +128,7 @@ public static void unregister(final Context context, final String registrationId builder.appendQueryParameter("regId", registrationId); String params = builder.build().toString().substring(1); - try - { + try { post(requestUrl, params); // TODO: use post or get Preferences preferences = new Preferences(); @@ -161,9 +136,7 @@ public static void unregister(final Context context, final String registrationId preferences.setGcmVersionCode(-1); Logcat.d("server successfully unregistered device"); - } - catch(IOException e) - { + } catch (IOException e) { // At this point the device is unregistered from GCM, but still registered on the server. // We could try to unregister again, but it is not necessary: if the server tries to send a message to the device, // it will get a "NotRegistered" error message and should unregister the device. @@ -171,18 +144,13 @@ public static void unregister(final Context context, final String registrationId } } - // send a POST request to the server - private static void post(String requestUrl, String params) throws IOException - { + private static void post(String requestUrl, String params) throws IOException { // create new URL URL url; - try - { + try { url = new URL(requestUrl); - } - catch(MalformedURLException e) - { + } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid url " + requestUrl); } @@ -193,8 +161,7 @@ private static void post(String requestUrl, String params) throws IOException // URL connection HttpURLConnection connection = null; - try - { + try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); @@ -210,26 +177,20 @@ private static void post(String requestUrl, String params) throws IOException // handle the response int status = connection.getResponseCode(); - if(status != 200) - { + if (status != 200) { throw new IOException("POST failed with error code " + status); } - } - finally - { - if(connection != null) connection.disconnect(); + } finally { + if (connection != null) connection.disconnect(); } } - // send a GET request to the server - private static void get(String baseUrl, String params) throws IOException - { + private static void get(String baseUrl, String params) throws IOException { // request URL StringBuilder builder = new StringBuilder(); builder.append(baseUrl); - if(params != null && !params.equals("")) - { + if (params != null && !params.equals("")) { builder.append("?"); builder.append(params); } @@ -237,12 +198,9 @@ private static void get(String baseUrl, String params) throws IOException // create new URL URL url; - try - { + try { url = new URL(requestUrl); - } - catch(MalformedURLException e) - { + } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid url " + requestUrl); } @@ -250,8 +208,7 @@ private static void get(String baseUrl, String params) throws IOException // URL connection HttpURLConnection connection = null; - try - { + try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); @@ -260,14 +217,11 @@ private static void get(String baseUrl, String params) throws IOException // handle the response int status = connection.getResponseCode(); - if(status != 200) - { + if (status != 200) { throw new IOException("GET failed with error code " + status); } - } - finally - { - if(connection != null) connection.disconnect(); + } finally { + if (connection != null) connection.disconnect(); } } } diff --git a/Deprecated/Src-Geolocation/java/fragment/ExampleFragment.java b/Deprecated/Src-Geolocation/java/fragment/ExampleFragment.java index 32f70d4..3a9e5b9 100644 --- a/Deprecated/Src-Geolocation/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-Geolocation/java/fragment/ExampleFragment.java @@ -16,54 +16,41 @@ import java.util.Date; - -public class ExampleFragment extends TaskFragment implements GeolocationListener -{ +public class ExampleFragment extends TaskFragment implements GeolocationListener { private View mRootView; private Geolocation mGeolocation = null; private Location mLocation = null; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // start geolocation - if(mLocation == null) - { + if (mLocation == null) { mGeolocation = null; mGeolocation = new Geolocation((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE), this); } } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop geolocation - if(mGeolocation != null) mGeolocation.stop(); + if (mGeolocation != null) mGeolocation.stop(); } - @Override - public void onGeolocationRespond(Geolocation geolocation, final Location location) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onGeolocationRespond(Geolocation geolocation, final Location location) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed Logcat.d("onGeolocationRespond() = " + location.getProvider() + " / " + location.getLatitude() + " / " + location.getLongitude() + " / " + new Date(location.getTime()).toString()); mLocation = new Location(location); @@ -73,15 +60,11 @@ public void run() }); } - @Override - public void onGeolocationFail(Geolocation geolocation) - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onGeolocationFail(Geolocation geolocation) { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed Logcat.d("onGeolocationFail()"); diff --git a/Deprecated/Src-Geolocation/java/geolocation/Geolocation.java b/Deprecated/Src-Geolocation/java/geolocation/Geolocation.java index acd912c..10dd91a 100644 --- a/Deprecated/Src-Geolocation/java/geolocation/Geolocation.java +++ b/Deprecated/Src-Geolocation/java/geolocation/Geolocation.java @@ -13,9 +13,7 @@ import java.util.Timer; import java.util.TimerTask; - -public class Geolocation implements LocationListener -{ +public class Geolocation implements LocationListener { private static final int LOCATION_AGE = 60000 * 30; // milliseconds private static final int LOCATION_TIMEOUT = 30000; // milliseconds @@ -24,25 +22,20 @@ public class Geolocation implements LocationListener private Location mCurrentLocation; private Timer mTimer; - - public Geolocation(LocationManager locationManager, GeolocationListener listener) - { + public Geolocation(LocationManager locationManager, GeolocationListener listener) { mLocationManager = locationManager; // (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mListener = new WeakReference<>(listener); mTimer = new Timer(); init(); } - @Override - public void onLocationChanged(Location location) - { + public void onLocationChanged(Location location) { Logcat.d(location.getProvider() + " / " + location.getLatitude() + " / " + location.getLongitude() + " / " + new Date(location.getTime()).toString()); // check location age long timeDelta = System.currentTimeMillis() - location.getTime(); - if(timeDelta > LOCATION_AGE) - { + if (timeDelta > LOCATION_AGE) { Logcat.d("gotten location is too old"); // gotten location is too old return; @@ -52,30 +45,23 @@ public void onLocationChanged(Location location) mCurrentLocation = new Location(location); stop(); GeolocationListener listener = mListener.get(); - if(listener != null && location != null) listener.onGeolocationRespond(Geolocation.this, mCurrentLocation); + if (listener != null && location != null) listener.onGeolocationRespond(Geolocation.this, mCurrentLocation); } - @Override - public void onProviderDisabled(String provider) - { + public void onProviderDisabled(String provider) { Logcat.d(provider); } - @Override - public void onProviderEnabled(String provider) - { + public void onProviderEnabled(String provider) { Logcat.d(provider); } - @Override - public void onStatusChanged(String provider, int status, Bundle extras) - { + public void onStatusChanged(String provider, int status, Bundle extras) { Logcat.d(provider); - switch(status) - { + switch (status) { case LocationProvider.OUT_OF_SERVICE: Logcat.d("status OUT_OF_SERVICE"); break; @@ -88,72 +74,54 @@ public void onStatusChanged(String provider, int status, Bundle extras) } } - - public void stop() - { + public void stop() { Logcat.d(""); - if(mTimer != null) mTimer.cancel(); - if(mLocationManager != null) - { + if (mTimer != null) mTimer.cancel(); + if (mLocationManager != null) { mLocationManager.removeUpdates(this); mLocationManager = null; } } - - private void init() - { + private void init() { // get last known location Location lastKnownLocation = getLastKnownLocation(mLocationManager); // try to listen last known location - if(lastKnownLocation != null) - { + if (lastKnownLocation != null) { onLocationChanged(lastKnownLocation); } - if(mCurrentLocation == null) - { + if (mCurrentLocation == null) { // start timer to check timeout - TimerTask task = new TimerTask() - { - public void run() - { - if(mCurrentLocation == null) - { + TimerTask task = new TimerTask() { + public void run() { + if (mCurrentLocation == null) { Logcat.d("timeout"); stop(); GeolocationListener listener = mListener.get(); - if(listener != null) listener.onGeolocationFail(Geolocation.this); + if (listener != null) listener.onGeolocationFail(Geolocation.this); } } }; mTimer.schedule(task, LOCATION_TIMEOUT); // register location updates - try - { + try { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, this); - } - catch(IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { e.printStackTrace(); } - try - { + try { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, this); - } - catch(IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { e.printStackTrace(); } } } - // returns last known freshest location from network or GPS - private Location getLastKnownLocation(LocationManager locationManager) - { + private Location getLastKnownLocation(LocationManager locationManager) { Logcat.d(""); Location locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); @@ -162,17 +130,15 @@ private Location getLastKnownLocation(LocationManager locationManager) long timeNet = 0L; long timeGps = 0L; - if(locationNet != null) - { + if (locationNet != null) { timeNet = locationNet.getTime(); } - if(locationGps != null) - { + if (locationGps != null) { timeGps = locationGps.getTime(); } - if(timeNet > timeGps) return locationNet; + if (timeNet > timeGps) return locationNet; else return locationGps; } } diff --git a/Deprecated/Src-Geolocation/java/geolocation/GeolocationListener.java b/Deprecated/Src-Geolocation/java/geolocation/GeolocationListener.java index e9f5113..5f82972 100644 --- a/Deprecated/Src-Geolocation/java/geolocation/GeolocationListener.java +++ b/Deprecated/Src-Geolocation/java/geolocation/GeolocationListener.java @@ -2,9 +2,7 @@ import android.location.Location; - -public interface GeolocationListener -{ +public interface GeolocationListener { void onGeolocationRespond(Geolocation geolocation, Location location); void onGeolocationFail(Geolocation geolocation); } diff --git a/Deprecated/Src-Image-Loader/java/ExampleApplication.java b/Deprecated/Src-Image-Loader/java/ExampleApplication.java index 2c95e03..50947cb 100644 --- a/Deprecated/Src-Image-Loader/java/ExampleApplication.java +++ b/Deprecated/Src-Image-Loader/java/ExampleApplication.java @@ -14,35 +14,26 @@ import java.io.File; import java.io.IOException; - -public class ExampleApplication extends Application -{ +public class ExampleApplication extends Application { private static ExampleApplication sInstance; - - public ExampleApplication() - { + public ExampleApplication() { sInstance = this; } - - public static Context getContext() - { + public static Context getContext() { return sInstance; } - @Override - public void onCreate() - { + public void onCreate() { super.onCreate(); // init image caching File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext()); cacheDir.mkdirs(); // requires android.permission.WRITE_EXTERNAL_STORAGE - try - { + try { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPoolSize(3) .threadPriority(Thread.NORM_PRIORITY - 2) @@ -52,9 +43,7 @@ public void onCreate() .build(); ImageLoader.getInstance().init(config); - } - catch(IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } diff --git a/Deprecated/Src-Image-Loader/java/fragment/ExampleFragment.java b/Deprecated/Src-Image-Loader/java/fragment/ExampleFragment.java index 59f61fd..6442bff 100644 --- a/Deprecated/Src-Image-Loader/java/fragment/ExampleFragment.java +++ b/Deprecated/Src-Image-Loader/java/fragment/ExampleFragment.java @@ -14,33 +14,25 @@ import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private ImageLoader mImageLoader = ImageLoader.getInstance(); private DisplayImageOptions mDisplayImageOptions; private ImageLoadingListener mImageLoadingListener; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupImageLoader(); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void setupImageLoader() - { + private void setupImageLoader() { mDisplayImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(android.R.color.transparent) .showImageForEmptyUri(R.drawable.placeholder_photo) @@ -52,9 +44,7 @@ private void setupImageLoader() mImageLoadingListener = new AnimateImageLoadingListener(); } - - private void setupView() - { + private void setupView() { // reference ImageView photoImageView = mRootView.findViewById(R.id.example_photo); diff --git a/Deprecated/Src-Image-Loader/java/graphics/FadeInBitmapDisplayer.java b/Deprecated/Src-Image-Loader/java/graphics/FadeInBitmapDisplayer.java index 02e7836..c5c808d 100644 --- a/Deprecated/Src-Image-Loader/java/graphics/FadeInBitmapDisplayer.java +++ b/Deprecated/Src-Image-Loader/java/graphics/FadeInBitmapDisplayer.java @@ -12,38 +12,27 @@ import com.nostra13.universalimageloader.core.display.BitmapDisplayer; import com.nostra13.universalimageloader.core.imageaware.ImageAware; - -public class FadeInBitmapDisplayer implements BitmapDisplayer -{ +public class FadeInBitmapDisplayer implements BitmapDisplayer { private int mDurationMillis; - - public FadeInBitmapDisplayer(int durationMillis) - { + public FadeInBitmapDisplayer(int durationMillis) { mDurationMillis = durationMillis; } - @Override - public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) - { + public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) { setImageBitmapWithFade(bitmap, imageAware.getWrappedView()); } - - private void setImageBitmapWithFade(final Bitmap bitmap, final View view) - { + private void setImageBitmapWithFade(final Bitmap bitmap, final View view) { Resources resources = view.getResources(); BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap); setImageDrawableWithFade(bitmapDrawable, (ImageView) view); } - - private void setImageDrawableWithFade(final Drawable drawable, final ImageView imageView) - { + private void setImageDrawableWithFade(final Drawable drawable, final ImageView imageView) { Drawable currentDrawable = imageView.getDrawable(); - if(currentDrawable != null) - { + if (currentDrawable != null) { Drawable[] drawableArray = new Drawable[2]; drawableArray[0] = currentDrawable; drawableArray[1] = drawable; @@ -51,9 +40,7 @@ private void setImageDrawableWithFade(final Drawable drawable, final ImageView i transitionDrawable.setCrossFadeEnabled(true); imageView.setImageDrawable(transitionDrawable); transitionDrawable.startTransition(mDurationMillis); - } - else - { + } else { imageView.setImageDrawable(drawable); } } diff --git a/Deprecated/Src-Image-Loader/java/listener/AnimateImageLoadingListener.java b/Deprecated/Src-Image-Loader/java/listener/AnimateImageLoadingListener.java index 8951225..6fa7531 100644 --- a/Deprecated/Src-Image-Loader/java/listener/AnimateImageLoadingListener.java +++ b/Deprecated/Src-Image-Loader/java/listener/AnimateImageLoadingListener.java @@ -11,21 +11,15 @@ import java.util.LinkedList; import java.util.List; - -public class AnimateImageLoadingListener extends SimpleImageLoadingListener -{ +public class AnimateImageLoadingListener extends SimpleImageLoadingListener { private final List mDisplayedImageList = Collections.synchronizedList(new LinkedList()); - @Override - public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) - { - if(loadedImage != null) - { + public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { + if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !mDisplayedImageList.contains(imageUri); - if(firstDisplay) - { + if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 500); mDisplayedImageList.add(imageUri); } diff --git a/Res-Theme/drawable/selector_selectable_item_bg.xml b/Res-Theme/drawable/selector_selectable_item_bg.xml index 9ab3e56..e15bf12 100644 --- a/Res-Theme/drawable/selector_selectable_item_bg.xml +++ b/Res-Theme/drawable/selector_selectable_item_bg.xml @@ -1,5 +1,8 @@ - - + + diff --git a/Src-ActionBar-Done-Bar/java/activity/ExampleActivity.java b/Src-ActionBar-Done-Bar/java/activity/ExampleActivity.java index ccf6912..c1a3ec8 100644 --- a/Src-ActionBar-Done-Bar/java/activity/ExampleActivity.java +++ b/Src-ActionBar-Done-Bar/java/activity/ExampleActivity.java @@ -10,20 +10,15 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupActionBar(); } - - private void setupActionBar() - { + private void setupActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setContentInsetsRelative(0, 0); setSupportActionBar(toolbar); @@ -33,19 +28,15 @@ private void setupActionBar() // custom view LayoutInflater inflater = (LayoutInflater) bar.getThemedContext().getSystemService(LAYOUT_INFLATER_SERVICE); View customView = inflater.inflate(R.layout.ab_donebar, null); - customView.findViewById(R.id.ab_donebar_done).setOnClickListener(new View.OnClickListener() - { + customView.findViewById(R.id.ab_donebar_done).setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { // TODO } }); - customView.findViewById(R.id.ab_donebar_cancel).setOnClickListener(new View.OnClickListener() - { + customView.findViewById(R.id.ab_donebar_cancel).setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { // TODO } }); diff --git a/Src-ActionBar-List-Navigation/java/activity/ExampleActivity.java b/Src-ActionBar-List-Navigation/java/activity/ExampleActivity.java index d13ef92..ac87949 100644 --- a/Src-ActionBar-List-Navigation/java/activity/ExampleActivity.java +++ b/Src-ActionBar-List-Navigation/java/activity/ExampleActivity.java @@ -10,12 +10,9 @@ import com.example.R; import com.example.adapter.ActionBarListNavigationAdapter; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); @@ -25,9 +22,7 @@ public void onCreate(Bundle savedInstanceState) setupActionBarNavigation(items, subtitle, 0); } - - private void setupActionBarNavigation(CharSequence[] items, String subtitle, int selectedItem) - { + private void setupActionBarNavigation(CharSequence[] items, String subtitle, int selectedItem) { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); @@ -41,15 +36,13 @@ private void setupActionBarNavigation(CharSequence[] items, String subtitle, int // action bar navigation bar.setDisplayShowTitleEnabled(false); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); - bar.setListNavigationCallbacks(adapter, new OnNavigationListener() - { + bar.setListNavigationCallbacks(adapter, new OnNavigationListener() { @Override - public boolean onNavigationItemSelected(int itemPosition, long itemId) - { + public boolean onNavigationItemSelected(int itemPosition, long itemId) { // TODO return true; } }); - if(selectedItem < items.length) bar.setSelectedNavigationItem(selectedItem); + if (selectedItem < items.length) bar.setSelectedNavigationItem(selectedItem); } } diff --git a/Src-ActionBar-List-Navigation/java/adapter/ActionBarListNavigationAdapter.java b/Src-ActionBar-List-Navigation/java/adapter/ActionBarListNavigationAdapter.java index 19921a0..10edde5 100644 --- a/Src-ActionBar-List-Navigation/java/adapter/ActionBarListNavigationAdapter.java +++ b/Src-ActionBar-List-Navigation/java/adapter/ActionBarListNavigationAdapter.java @@ -9,27 +9,20 @@ import com.example.R; - -public class ActionBarListNavigationAdapter extends ArrayAdapter -{ +public class ActionBarListNavigationAdapter extends ArrayAdapter { private Context mContext; private String mSubtitle; - - public ActionBarListNavigationAdapter(Context context, int resource, T[] objects, String subtitle) - { + public ActionBarListNavigationAdapter(Context context, int resource, T[] objects, String subtitle) { super(context, resource, objects); mContext = context; mSubtitle = subtitle; } - @Override - public View getView(final int position, View convertView, ViewGroup parent) - { + public View getView(final int position, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.ab_list_navigation, parent, false); @@ -42,8 +35,7 @@ public View getView(final int position, View convertView, ViewGroup parent) // entity T item = getItem(position); - if(item != null) - { + if (item != null) { // view holder ViewHolder holder = (ViewHolder) convertView.getTag(); @@ -55,9 +47,7 @@ public View getView(final int position, View convertView, ViewGroup parent) return convertView; } - - static class ViewHolder - { + static class ViewHolder { TextView titleTextView; TextView subtitleTextView; } diff --git a/Src-ActionBar-Refresh/java/fragment/ExampleFragment.java b/Src-ActionBar-Refresh/java/fragment/ExampleFragment.java index 4bef5b9..613892d 100644 --- a/Src-ActionBar-Refresh/java/fragment/ExampleFragment.java +++ b/Src-ActionBar-Refresh/java/fragment/ExampleFragment.java @@ -13,24 +13,18 @@ import com.example.R; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private MenuItem mRefreshMenuItem; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); @@ -43,13 +37,10 @@ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) showProgress(isProgress()); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { // TODO case R.id.menu_example_refresh: @@ -61,20 +52,14 @@ public boolean onOptionsItemSelected(MenuItem item) } } - - private void showProgress(boolean visible) - { + private void showProgress(boolean visible) { // show action view progress - if(mRefreshMenuItem != null) - { - if(visible) - { + if (mRefreshMenuItem != null) { + if (visible) { LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.ab_action_refresh, null); MenuItemCompat.setActionView(mRefreshMenuItem, view); - } - else - { + } else { MenuItemCompat.setActionView(mRefreshMenuItem, null); } } @@ -82,22 +67,16 @@ private void showProgress(boolean visible) setProgress(visible); } - - private void refreshData() - { + private void refreshData() { // TODO } - - private boolean isProgress() - { + private boolean isProgress() { // TODO return false; } - - private void setProgress(boolean progress) - { + private void setProgress(boolean progress) { // TODO } } diff --git a/Src-ActionBar-Search/java/activity/ExampleActivity.java b/Src-ActionBar-Search/java/activity/ExampleActivity.java index 99e4a98..242e911 100644 --- a/Src-ActionBar-Search/java/activity/ExampleActivity.java +++ b/Src-ActionBar-Search/java/activity/ExampleActivity.java @@ -20,26 +20,20 @@ import com.example.R; import com.example.adapter.SearchSuggestionAdapter; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { private final String[] SEARCH_SUGGESTION_CURSOR_COLUMNS = {BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2}; private SearchView mSearchView; private SearchSuggestionAdapter mSearchSuggestionAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); } - @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { // action bar menu MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.activity_example, menu); @@ -57,9 +51,7 @@ public boolean onCreateOptionsMenu(Menu menu) return super.onCreateOptionsMenu(menu); } - - private void setupSearchView(SearchView searchView) - { + private void setupSearchView(SearchView searchView) { // search hint searchView.setQueryHint(getString(R.string.menu_example_search_hint)); @@ -69,40 +61,31 @@ private void setupSearchView(SearchView searchView) searchText.setHintTextColor(ContextCompat.getColor(this, R.color.global_text_secondary_inverse)); // suggestion listeners - searchView.setOnQueryTextListener(new OnQueryTextListener() - { + searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override - public boolean onQueryTextSubmit(String query) - { + public boolean onQueryTextSubmit(String query) { // TODO Toast.makeText(ExampleActivity.this, "search: " + query, Toast.LENGTH_SHORT).show(); return true; } - @Override - public boolean onQueryTextChange(String query) - { - if(query.length() > 2) - { + public boolean onQueryTextChange(String query) { + if (query.length() > 2) { updateSearchSuggestion(query); } return true; } }); - searchView.setOnSuggestionListener(new OnSuggestionListener() - { + searchView.setOnSuggestionListener(new OnSuggestionListener() { @Override - public boolean onSuggestionSelect(int position) - { + public boolean onSuggestionSelect(int position) { return false; } - @Override - public boolean onSuggestionClick(int position) - { + public boolean onSuggestionClick(int position) { Cursor cursor = (Cursor) mSearchSuggestionAdapter.getItem(position); String title = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1)); String subtitle = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2)); @@ -115,9 +98,7 @@ public boolean onSuggestionClick(int position) }); } - - private void updateSearchSuggestion(String query) - { + private void updateSearchSuggestion(String query) { // cursor // TODO MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGESTION_CURSOR_COLUMNS); @@ -126,16 +107,13 @@ private void updateSearchSuggestion(String query) cursor.addRow(new String[]{"3", query + "rap", "Dolor"}); // searchview content - if(mSearchSuggestionAdapter == null) - { + if (mSearchSuggestionAdapter == null) { // create adapter mSearchSuggestionAdapter = new SearchSuggestionAdapter(this, cursor); // set adapter mSearchView.setSuggestionsAdapter(mSearchSuggestionAdapter); - } - else - { + } else { // refill adapter mSearchSuggestionAdapter.refill(this, cursor); diff --git a/Src-ActionBar-Search/java/adapter/SearchSuggestionAdapter.java b/Src-ActionBar-Search/java/adapter/SearchSuggestionAdapter.java index 5a8715d..b302268 100644 --- a/Src-ActionBar-Search/java/adapter/SearchSuggestionAdapter.java +++ b/Src-ActionBar-Search/java/adapter/SearchSuggestionAdapter.java @@ -12,26 +12,19 @@ import com.example.R; - -public class SearchSuggestionAdapter extends CursorAdapter -{ - public SearchSuggestionAdapter(Context context, Cursor cursor) - { +public class SearchSuggestionAdapter extends CursorAdapter { + public SearchSuggestionAdapter(Context context, Cursor cursor) { super(context, cursor, 0); } - @Override - public View newView(Context context, Cursor cursor, ViewGroup parent) - { + public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); return inflater.inflate(R.layout.search_suggestion_item, parent, false); } - @Override - public void bindView(View view, Context context, Cursor cursor) - { + public void bindView(View view, Context context, Cursor cursor) { // reference LinearLayout root = (LinearLayout) view; TextView titleTextView = root.findViewById(R.id.search_suggestion_item_title); @@ -44,9 +37,7 @@ public void bindView(View view, Context context, Cursor cursor) subtitleTextView.setText(cursor.getString(index2)); } - - public void refill(Context context, Cursor cursor) - { + public void refill(Context context, Cursor cursor) { changeCursor(cursor); } } diff --git a/Src-Activity-Result/java/activity/ExampleActivity.java b/Src-Activity-Result/java/activity/ExampleActivity.java index 25fda1e..9f9e4c0 100644 --- a/Src-Activity-Result/java/activity/ExampleActivity.java +++ b/Src-Activity-Result/java/activity/ExampleActivity.java @@ -9,41 +9,29 @@ import org.alfonz.utility.Logcat; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { public static final int REQUEST_PICK_ITEM = 1; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) - { + protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if(requestCode == REQUEST_PICK_ITEM) - { - if(resultCode == Activity.RESULT_OK) - { + if (requestCode == REQUEST_PICK_ITEM) { + if (resultCode == Activity.RESULT_OK) { Logcat.d("ok"); - } - else if(resultCode == Activity.RESULT_CANCELED) - { + } else if (resultCode == Activity.RESULT_CANCELED) { Logcat.d("canceled"); } } } - - private void startPickerActivity() - { + private void startPickerActivity() { Intent intent = PickerActivity.newIntent(this); startActivityForResult(intent, REQUEST_PICK_ITEM); } diff --git a/Src-Activity-Result/java/activity/PickerActivity.java b/Src-Activity-Result/java/activity/PickerActivity.java index bacaeda..957c9cc 100644 --- a/Src-Activity-Result/java/activity/PickerActivity.java +++ b/Src-Activity-Result/java/activity/PickerActivity.java @@ -8,36 +8,27 @@ import com.example.R; - -public class PickerActivity extends AppCompatActivity -{ - public static Intent newIntent(Context context) - { +public class PickerActivity extends AppCompatActivity { + public static Intent newIntent(Context context) { Intent intent = new Intent(context, PickerActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_picker); } - - private void finishOk() - { + private void finishOk() { Intent intent = new Intent(); intent.putExtra("data", 123); // TODO setResult(Activity.RESULT_OK, intent); finish(); } - - private void finishCanceled() - { + private void finishCanceled() { Intent intent = new Intent(); setResult(Activity.RESULT_CANCELED, intent); finish(); diff --git a/Src-Activity-Result/java/fragment/ExampleFragment.java b/Src-Activity-Result/java/fragment/ExampleFragment.java index a0f8435..59fadaa 100644 --- a/Src-Activity-Result/java/fragment/ExampleFragment.java +++ b/Src-Activity-Result/java/fragment/ExampleFragment.java @@ -14,41 +14,29 @@ import org.alfonz.utility.Logcat; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_simple, container, false); return mRootView; } - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) - { + public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if(requestCode == ExampleActivity.REQUEST_PICK_ITEM) - { - if(resultCode == Activity.RESULT_OK) - { + if (requestCode == ExampleActivity.REQUEST_PICK_ITEM) { + if (resultCode == Activity.RESULT_OK) { Logcat.d("ok"); - } - else if(resultCode == Activity.RESULT_CANCELED) - { + } else if (resultCode == Activity.RESULT_CANCELED) { Logcat.d("canceled"); } } } - - private void startPickerActivity() - { + private void startPickerActivity() { Intent intent = PickerActivity.newIntent(getActivity()); startActivityForResult(intent, ExampleActivity.REQUEST_PICK_ITEM); } diff --git a/Src-AlarmManager/java/alarm/ExampleAlarm.java b/Src-AlarmManager/java/alarm/ExampleAlarm.java index 0dc3691..a5d4533 100644 --- a/Src-AlarmManager/java/alarm/ExampleAlarm.java +++ b/Src-AlarmManager/java/alarm/ExampleAlarm.java @@ -9,52 +9,38 @@ import java.util.Calendar; - -public class ExampleAlarm -{ +public class ExampleAlarm { private static final int ALARM_ID = 0; private static final long ALARM_INTERVAL = AlarmManager.INTERVAL_HOUR; // in milliseconds private Context mContext; - - public ExampleAlarm(Context context) - { + public ExampleAlarm(Context context) { mContext = context; } - - public void startAlarm() - { + public void startAlarm() { AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC, getStartTime(), ALARM_INTERVAL, getPendingIntent()); // TODO: use AlarmManager.RTC or AlarmManager.RTC_WAKEUP } - - public void stopAlarm() - { + public void stopAlarm() { AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(getPendingIntent()); } - - public boolean isRunning() - { + public boolean isRunning() { Intent alarmIntent = new Intent(mContext, ExampleAlarmReceiver.class); return PendingIntent.getBroadcast(mContext, ALARM_ID, alarmIntent, PendingIntent.FLAG_NO_CREATE) != null; } - - private long getStartTime() - { + private long getStartTime() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MILLISECOND, (int) ALARM_INTERVAL); return calendar.getTimeInMillis(); } - - private PendingIntent getPendingIntent() - { + private PendingIntent getPendingIntent() { Intent alarmIntent = new Intent(mContext, ExampleAlarmReceiver.class); return PendingIntent.getBroadcast(mContext, ALARM_ID, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); } diff --git a/Src-AlarmManager/java/receiver/ExampleAlarmReceiver.java b/Src-AlarmManager/java/receiver/ExampleAlarmReceiver.java index 85fe6c8..233d5a8 100644 --- a/Src-AlarmManager/java/receiver/ExampleAlarmReceiver.java +++ b/Src-AlarmManager/java/receiver/ExampleAlarmReceiver.java @@ -6,12 +6,9 @@ import org.alfonz.utility.Logcat; - -public class ExampleAlarmReceiver extends BroadcastReceiver -{ +public class ExampleAlarmReceiver extends BroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) - { + public void onReceive(Context context, Intent intent) { Logcat.d(""); // TODO: do something diff --git a/Src-Animation-Activity-Options/java/fragment/ExampleFragment.java b/Src-Animation-Activity-Options/java/fragment/ExampleFragment.java index b510ccb..cb7883f 100644 --- a/Src-Animation-Activity-Options/java/fragment/ExampleFragment.java +++ b/Src-Animation-Activity-Options/java/fragment/ExampleFragment.java @@ -11,30 +11,22 @@ import com.example.R; import com.example.activity.ExampleActivity; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void startExampleActivity() - { + private void startExampleActivity() { Intent intent = ExampleActivity.newIntent(getActivity()); ActivityOptions options = ActivityOptions.makeCustomAnimation(getActivity(), R.anim.push_right_enter, R.anim.push_right_exit); getActivity().startActivity(intent, options.toBundle()); } - - private void startExampleActivity(View view) - { + private void startExampleActivity(View view) { Intent intent = ExampleActivity.newIntent(getActivity()); ActivityOptions options = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()); getActivity().startActivity(intent, options.toBundle()); diff --git a/Src-Animation-Activity-Transition/java/activity/TransitionFirstActivity.java b/Src-Animation-Activity-Transition/java/activity/TransitionFirstActivity.java index 4b52381..aa18708 100644 --- a/Src-Animation-Activity-Transition/java/activity/TransitionFirstActivity.java +++ b/Src-Animation-Activity-Transition/java/activity/TransitionFirstActivity.java @@ -10,41 +10,31 @@ import com.example.R; - -public class TransitionFirstActivity extends AppCompatActivity -{ - public static Intent newIntent(Context context) - { +public class TransitionFirstActivity extends AppCompatActivity { + public static Intent newIntent(Context context) { Intent intent = new Intent(context, TransitionFirstActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transition_first); } - @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { // action bar menu MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.activity_transition_first, menu); return super.onCreateOptionsMenu(menu); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case R.id.menu_transition_first_second: Intent intent = TransitionSecondActivity.newIntent(this); startActivity(intent); diff --git a/Src-Animation-Activity-Transition/java/activity/TransitionSecondActivity.java b/Src-Animation-Activity-Transition/java/activity/TransitionSecondActivity.java index c0d0dd9..563f267 100644 --- a/Src-Animation-Activity-Transition/java/activity/TransitionSecondActivity.java +++ b/Src-Animation-Activity-Transition/java/activity/TransitionSecondActivity.java @@ -10,40 +10,30 @@ import com.example.R; - -public class TransitionSecondActivity extends AppCompatActivity -{ - public static Intent newIntent(Context context) - { +public class TransitionSecondActivity extends AppCompatActivity { + public static Intent newIntent(Context context) { Intent intent = new Intent(context, TransitionSecondActivity.class); return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transition_second); } - @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { // action bar menu MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.activity_transition_second, menu); return super.onCreateOptionsMenu(menu); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case R.id.menu_transition_second_first: Intent intent = TransitionFirstActivity.newIntent(this); startActivity(intent); @@ -55,10 +45,8 @@ public boolean onOptionsItemSelected(MenuItem item) } } - @Override - public void onBackPressed() - { + public void onBackPressed() { // back button super.onBackPressed(); setResult(RESULT_CANCELED); diff --git a/Src-Animation-Layout-Transition/java/fragment/ExampleFragment.java b/Src-Animation-Layout-Transition/java/fragment/ExampleFragment.java index f9573b0..845ee9a 100644 --- a/Src-Animation-Layout-Transition/java/fragment/ExampleFragment.java +++ b/Src-Animation-Layout-Transition/java/fragment/ExampleFragment.java @@ -9,25 +9,18 @@ import com.example.R; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void setupLayoutTransition(ViewGroup layout) - { + private void setupLayoutTransition(ViewGroup layout) { LayoutTransition transition = layout.getLayoutTransition(); - if(transition == null) - { + if (transition == null) { transition = new LayoutTransition(); layout.setLayoutTransition(transition); } diff --git a/Src-Animation-Page-Transformer/java/animation/DepthPageTransformer.java b/Src-Animation-Page-Transformer/java/animation/DepthPageTransformer.java index 657f1a1..b87ae7f 100644 --- a/Src-Animation-Page-Transformer/java/animation/DepthPageTransformer.java +++ b/Src-Animation-Page-Transformer/java/animation/DepthPageTransformer.java @@ -3,34 +3,25 @@ import android.support.v4.view.ViewPager; import android.view.View; - -public class DepthPageTransformer implements ViewPager.PageTransformer -{ +public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75F; - @Override - public void transformPage(View view, float position) - { + public void transformPage(View view, float position) { int pageWidth = view.getWidth(); - if(position < -1) - { + if (position < -1) { // [-Infinity,-1) // this page is way off-screen to the left view.setAlpha(0); - } - else if(position <= 0) - { + } else if (position <= 0) { // [-1,0] // use the default slide transition when moving to the left page view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); - } - else if(position <= 1) - { + } else if (position <= 1) { // (0,1] // fade the page out view.setAlpha(1 - position); @@ -42,9 +33,7 @@ else if(position <= 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); - } - else - { + } else { // (1,+Infinity] // this page is way off-screen to the right view.setAlpha(0); diff --git a/Src-Animation-Page-Transformer/java/animation/ScaleRotationPageTransformer.java b/Src-Animation-Page-Transformer/java/animation/ScaleRotationPageTransformer.java index d038ae2..1276194 100644 --- a/Src-Animation-Page-Transformer/java/animation/ScaleRotationPageTransformer.java +++ b/Src-Animation-Page-Transformer/java/animation/ScaleRotationPageTransformer.java @@ -3,16 +3,12 @@ import android.support.v4.view.ViewPager; import android.view.View; - -public class ScaleRotationPageTransformer implements ViewPager.PageTransformer -{ +public class ScaleRotationPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75F; private static final float ANGLE = 20F; - @Override - public void transformPage(View view, float position) - { + public void transformPage(View view, float position) { float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); diff --git a/Src-Animation-Page-Transformer/java/animation/ZoomOutPageTransformer.java b/Src-Animation-Page-Transformer/java/animation/ZoomOutPageTransformer.java index 7f8ba8e..19e1173 100644 --- a/Src-Animation-Page-Transformer/java/animation/ZoomOutPageTransformer.java +++ b/Src-Animation-Page-Transformer/java/animation/ZoomOutPageTransformer.java @@ -3,38 +3,28 @@ import android.support.v4.view.ViewPager; import android.view.View; - -public class ZoomOutPageTransformer implements ViewPager.PageTransformer -{ +public class ZoomOutPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.85F; private static final float MIN_ALPHA = 0.5F; - @Override - public void transformPage(View view, float position) - { + public void transformPage(View view, float position) { int pageWidth = view.getWidth(); int pageHeight = view.getHeight(); - if(position < -1) - { + if (position < -1) { // [-Infinity,-1) // this page is way off-screen to the left view.setAlpha(0); - } - else if(position <= 1) - { + } else if (position <= 1) { // [-1,1] // modify the default slide transition to shrink the page as well float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)); float vertMargin = pageHeight * (1 - scaleFactor) / 2; float horzMargin = pageWidth * (1 - scaleFactor) / 2; - if(position < 0) - { + if (position < 0) { view.setTranslationX(horzMargin - vertMargin / 2); - } - else - { + } else { view.setTranslationX(-horzMargin + vertMargin / 2); } @@ -44,9 +34,7 @@ else if(position <= 1) // fade the page relative to its size view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); - } - else - { + } else { // (1,+Infinity] // this page is way off-screen to the right view.setAlpha(0); diff --git a/Src-Animation-Property/java/fragment/ExampleFragment.java b/Src-Animation-Property/java/fragment/ExampleFragment.java index ec3ebe9..abaf4e1 100644 --- a/Src-Animation-Property/java/fragment/ExampleFragment.java +++ b/Src-Animation-Property/java/fragment/ExampleFragment.java @@ -20,22 +20,16 @@ import org.alfonz.utility.Logcat; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void animateView1(View view) - { + private void animateView1(View view) { PropertyValuesHolder holderX = PropertyValuesHolder.ofFloat(View.TRANSLATION_X, 0F, 400F); PropertyValuesHolder holderY = PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, 0F, 200F); PropertyValuesHolder holderSX = PropertyValuesHolder.ofFloat(View.SCALE_X, 1F, 2F); @@ -48,32 +42,24 @@ private void animateView1(View view) animator1.setRepeatMode(ObjectAnimator.REVERSE); animator1.setInterpolator(new AccelerateDecelerateInterpolator()); animator1.setEvaluator(new FloatEvaluator()); - animator1.addListener(new AnimatorListenerAdapter() - { + animator1.addListener(new AnimatorListenerAdapter() { @Override - public void onAnimationStart(Animator animator) - { + public void onAnimationStart(Animator animator) { Logcat.d(""); } - @Override - public void onAnimationRepeat(Animator animator) - { + public void onAnimationRepeat(Animator animator) { Logcat.d(""); } - @Override - public void onAnimationCancel(Animator animator) - { + public void onAnimationCancel(Animator animator) { Logcat.d(""); } - @Override - public void onAnimationEnd(Animator animator) - { + public void onAnimationEnd(Animator animator) { Logcat.d(""); } }); @@ -90,9 +76,7 @@ public void onAnimationEnd(Animator animator) animatorSet.start(); } - - private void animateView2(final View view) - { + private void animateView2(final View view) { Integer colorFrom = ContextCompat.getColor(getActivity(), android.R.color.holo_orange_light); Integer colorTo = ContextCompat.getColor(getActivity(), android.R.color.holo_green_light); ValueAnimator animator = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo, colorFrom); @@ -100,11 +84,9 @@ private void animateView2(final View view) animator.setRepeatCount(ValueAnimator.INFINITE); animator.setRepeatMode(ValueAnimator.REVERSE); animator.setInterpolator(new AccelerateDecelerateInterpolator()); - animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() - { + animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override - public void onAnimationUpdate(ValueAnimator animator) - { + public void onAnimationUpdate(ValueAnimator animator) { view.setBackgroundColor((Integer) animator.getAnimatedValue()); } }); diff --git a/Src-Application-Class/java/ExampleApplication.java b/Src-Application-Class/java/ExampleApplication.java index 40a23d8..a3cf6c8 100644 --- a/Src-Application-Class/java/ExampleApplication.java +++ b/Src-Application-Class/java/ExampleApplication.java @@ -3,27 +3,19 @@ import android.app.Application; import android.content.Context; - -public class ExampleApplication extends Application -{ +public class ExampleApplication extends Application { private static ExampleApplication sInstance; - - public ExampleApplication() - { + public ExampleApplication() { sInstance = this; } - - public static Context getContext() - { + public static Context getContext() { return sInstance; } - @Override - public void onCreate() - { + public void onCreate() { super.onCreate(); // TODO } diff --git a/Src-Broadcast/java/broadcast/ExampleBroadcast.java b/Src-Broadcast/java/broadcast/ExampleBroadcast.java index 8e716b1..13ec533 100644 --- a/Src-Broadcast/java/broadcast/ExampleBroadcast.java +++ b/Src-Broadcast/java/broadcast/ExampleBroadcast.java @@ -4,24 +4,18 @@ import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; - -public class ExampleBroadcast -{ +public class ExampleBroadcast { public static final String ACTION_EXAMPLE = "com.example.EXAMPLE"; public static final String EXTRA_ARG = "arg"; - - public static void sendBroadcast(Context context, String arg) - { + public static void sendBroadcast(Context context, String arg) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_EXAMPLE); broadcastIntent.putExtra(EXTRA_ARG, arg); context.sendBroadcast(broadcastIntent); } - - public static void sendLocalBroadcast(Context context, String arg) - { + public static void sendLocalBroadcast(Context context, String arg) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ACTION_EXAMPLE); broadcastIntent.putExtra(EXTRA_ARG, arg); diff --git a/Src-Broadcast/java/fragment/ExampleFragment.java b/Src-Broadcast/java/fragment/ExampleFragment.java index e10a22a..8e43799 100644 --- a/Src-Broadcast/java/fragment/ExampleFragment.java +++ b/Src-Broadcast/java/fragment/ExampleFragment.java @@ -16,35 +16,27 @@ import org.alfonz.utility.Logcat; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private IntentFilter mExampleIntentFilter; private BroadcastReceiver mExampleBroadcastReceiver; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // init receiver initReceiver(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); // register receiver @@ -54,10 +46,8 @@ public void onResume() LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mExampleBroadcastReceiver, mExampleIntentFilter); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // unregister receiver @@ -67,21 +57,16 @@ public void onPause() LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mExampleBroadcastReceiver); } - - private void initReceiver() - { + private void initReceiver() { // create intent filter mExampleIntentFilter = new IntentFilter(); mExampleIntentFilter.addAction(ExampleBroadcast.ACTION_EXAMPLE); // create broadcast receiver - mExampleBroadcastReceiver = new BroadcastReceiver() - { + mExampleBroadcastReceiver = new BroadcastReceiver() { @Override - public void onReceive(Context context, Intent intent) - { - if(intent.getAction().equals(ExampleBroadcast.ACTION_EXAMPLE)) - { + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals(ExampleBroadcast.ACTION_EXAMPLE)) { String arg = intent.getExtras().getString(ExampleBroadcast.EXTRA_ARG); Logcat.d(arg); } diff --git a/Src-Bundle/java/activity/ExampleActivity.java b/Src-Bundle/java/activity/ExampleActivity.java index 532f587..7c4242d 100644 --- a/Src-Bundle/java/activity/ExampleActivity.java +++ b/Src-Bundle/java/activity/ExampleActivity.java @@ -7,17 +7,13 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { public static final String EXTRA_PRODUCT_ID = "product_id"; public static final String EXTRA_PRODUCT_TITLE = "product_title"; private static final String SAVED_PAGER_POSITION = "pager_position"; - - public static Intent newIntent(Context context, String productId, String productTitle) - { + public static Intent newIntent(Context context, String productId, String productTitle) { Intent intent = new Intent(context, ExampleActivity.class); // extras @@ -27,59 +23,46 @@ public static Intent newIntent(Context context, String productId, String product return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } // handle intent extras Bundle extras = getIntent().getExtras(); - if(extras != null) - { + if (extras != null) { handleExtras(extras); } } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); // TODO } - @Override - public void onRestoreInstanceState(Bundle savedInstanceState) - { + public void onRestoreInstanceState(Bundle savedInstanceState) { // restore saved state super.onRestoreInstanceState(savedInstanceState); - if(savedInstanceState != null) - { + if (savedInstanceState != null) { // TODO } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { // TODO } - - private void handleExtras(Bundle extras) - { + private void handleExtras(Bundle extras) { // TODO } } diff --git a/Src-Bundle/java/fragment/ExampleFragment.java b/Src-Bundle/java/fragment/ExampleFragment.java index 2404d8e..1c3a36f 100644 --- a/Src-Bundle/java/fragment/ExampleFragment.java +++ b/Src-Bundle/java/fragment/ExampleFragment.java @@ -3,15 +3,11 @@ import android.os.Bundle; import android.support.v4.app.Fragment; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private static final String ARGUMENT_PRODUCT_ID = "product_id"; private static final String SAVED_LIST_POSITION = "list_position"; - - public static ExampleFragment newInstance(String productId) - { + public static ExampleFragment newInstance(String productId) { ExampleFragment fragment = new ExampleFragment(); // arguments @@ -22,37 +18,30 @@ public static ExampleFragment newInstance(String productId) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } // handle intent extras Bundle extras = getActivity().getIntent().getExtras(); - if(extras != null) - { + if (extras != null) { handleExtras(extras); } } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); @@ -60,21 +49,15 @@ public void onSaveInstanceState(Bundle outState) // TODO } - - private void handleArguments(Bundle arguments) - { + private void handleArguments(Bundle arguments) { // TODO } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { // TODO } - - private void handleExtras(Bundle extras) - { + private void handleExtras(Bundle extras) { // TODO } } diff --git a/Src-Config/java/ExampleConfig.java b/Src-Config/java/ExampleConfig.java index 1faa090..fd099c0 100644 --- a/Src-Config/java/ExampleConfig.java +++ b/Src-Config/java/ExampleConfig.java @@ -1,8 +1,6 @@ package com.example; - -public class ExampleConfig -{ +public class ExampleConfig { public static final boolean LOGS = BuildConfig.LOGS; public static final boolean DEV_ENVIRONMENT = BuildConfig.DEV_ENVIRONMENT; diff --git a/Src-CoordinatorLayout/java/fragment/BottomSheetFragment.java b/Src-CoordinatorLayout/java/fragment/BottomSheetFragment.java index a790dcf..32858a0 100644 --- a/Src-CoordinatorLayout/java/fragment/BottomSheetFragment.java +++ b/Src-CoordinatorLayout/java/fragment/BottomSheetFragment.java @@ -10,40 +10,30 @@ import com.example.R; - -public class BottomSheetFragment extends Fragment -{ +public class BottomSheetFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_bottom_sheet, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupBottomSheet(); } - - private void setupBottomSheet() - { + private void setupBottomSheet() { // reference final FloatingActionButton fab = mRootView.findViewById(R.id.fab); final View bottomSheet = mRootView.findViewById(R.id.bottom_sheet); // fab - fab.setOnClickListener(new View.OnClickListener() - { + fab.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View view) - { + public void onClick(View view) { BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } diff --git a/Src-CoordinatorLayout/java/fragment/OverlapFragment.java b/Src-CoordinatorLayout/java/fragment/OverlapFragment.java index b5d322d..86aa427 100644 --- a/Src-CoordinatorLayout/java/fragment/OverlapFragment.java +++ b/Src-CoordinatorLayout/java/fragment/OverlapFragment.java @@ -11,9 +11,7 @@ import com.example.R; - -public class OverlapFragment extends Fragment implements AppBarLayout.OnOffsetChangedListener -{ +public class OverlapFragment extends Fragment implements AppBarLayout.OnOffsetChangedListener { private static final int PERCENTAGE_TO_SHOW_IMAGE = 20; private View mRootView; @@ -21,62 +19,48 @@ public class OverlapFragment extends Fragment implements AppBarLayout.OnOffsetCh private int mMaxScrollSize; private boolean mIsImageHidden; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_overlap, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupAppBar(); } - @Override - public void onOffsetChanged(AppBarLayout appBarLayout, int i) - { - if(mMaxScrollSize == 0) mMaxScrollSize = appBarLayout.getTotalScrollRange(); + public void onOffsetChanged(AppBarLayout appBarLayout, int i) { + if (mMaxScrollSize == 0) mMaxScrollSize = appBarLayout.getTotalScrollRange(); int currentScrollPercentage = (Math.abs(i)) * 100 / mMaxScrollSize; - if(currentScrollPercentage >= PERCENTAGE_TO_SHOW_IMAGE) - { - if(!mIsImageHidden) - { + if (currentScrollPercentage >= PERCENTAGE_TO_SHOW_IMAGE) { + if (!mIsImageHidden) { mIsImageHidden = true; ViewCompat.animate(mFab).scaleY(0).scaleX(0).start(); } } - if(currentScrollPercentage < PERCENTAGE_TO_SHOW_IMAGE) - { - if(mIsImageHidden) - { + if (currentScrollPercentage < PERCENTAGE_TO_SHOW_IMAGE) { + if (mIsImageHidden) { mIsImageHidden = false; ViewCompat.animate(mFab).scaleY(1).scaleX(1).start(); } } } - - private void setupAppBar() - { + private void setupAppBar() { // appbar AppBarLayout appBar = mRootView.findViewById(R.id.appbar); appBar.addOnOffsetChangedListener(this); // toolbar Toolbar toolbar = mRootView.findViewById(R.id.toolbar); - toolbar.setNavigationOnClickListener(new View.OnClickListener() - { + toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { // TODO } }); diff --git a/Src-CoordinatorLayout/java/widget/ExampleBehavior.java b/Src-CoordinatorLayout/java/widget/ExampleBehavior.java index 789e8d5..c117151 100644 --- a/Src-CoordinatorLayout/java/widget/ExampleBehavior.java +++ b/Src-CoordinatorLayout/java/widget/ExampleBehavior.java @@ -7,25 +7,18 @@ import android.util.AttributeSet; import android.view.View; - -public class ExampleBehavior extends CoordinatorLayout.Behavior -{ - public ExampleBehavior(Context context, AttributeSet attrs) - { +public class ExampleBehavior extends CoordinatorLayout.Behavior { + public ExampleBehavior(Context context, AttributeSet attrs) { super(context, attrs); } - @Override - public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { + public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) { return dependency instanceof AppBarLayout; } - @Override - public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { + public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) { // TODO return false; } diff --git a/Src-CoordinatorLayout/java/widget/QuickReturnFooterBehavior.java b/Src-CoordinatorLayout/java/widget/QuickReturnFooterBehavior.java index 4b9103b..14a04cc 100644 --- a/Src-CoordinatorLayout/java/widget/QuickReturnFooterBehavior.java +++ b/Src-CoordinatorLayout/java/widget/QuickReturnFooterBehavior.java @@ -10,7 +10,6 @@ import android.view.ViewPropertyAnimator; import android.view.animation.Interpolator; - /** * CoordinatorLayout Behavior for a quick return footer *

@@ -22,33 +21,25 @@ * @author bherbst */ @SuppressWarnings("unused") -public class QuickReturnFooterBehavior extends CoordinatorLayout.Behavior -{ +public class QuickReturnFooterBehavior extends CoordinatorLayout.Behavior { private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator(); private int mDySinceDirectionChange; private boolean mIsShowing; private boolean mIsHiding; - - public QuickReturnFooterBehavior(Context context, AttributeSet attrs) - { + public QuickReturnFooterBehavior(Context context, AttributeSet attrs) { super(context, attrs); } - @Override - public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) - { + public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, View child, View directTargetChild, View target, int nestedScrollAxes) { return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; } - @Override - public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) - { - if(dy > 0 && mDySinceDirectionChange < 0 || dy < 0 && mDySinceDirectionChange > 0) - { + public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) { + if (dy > 0 && mDySinceDirectionChange < 0 || dy < 0 && mDySinceDirectionChange > 0) { // We detected a direction change- cancel existing animations and reset our cumulative delta Y child.animate().cancel(); mDySinceDirectionChange = 0; @@ -56,17 +47,13 @@ public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, V mDySinceDirectionChange += dy; - if(mDySinceDirectionChange > child.getHeight() && child.getVisibility() == View.VISIBLE && !mIsHiding) - { + if (mDySinceDirectionChange > child.getHeight() && child.getVisibility() == View.VISIBLE && !mIsHiding) { hide(child); - } - else if(mDySinceDirectionChange < 0 && child.getVisibility() == View.GONE && !mIsShowing) - { + } else if (mDySinceDirectionChange < 0 && child.getVisibility() == View.GONE && !mIsShowing) { show(child); } } - /** * Hide the quick return view. *

@@ -75,41 +62,33 @@ else if(mDySinceDirectionChange < 0 && child.getVisibility() == View.GONE && !mI * * @param view The quick return view */ - private void hide(final View view) - { + private void hide(final View view) { mIsHiding = true; ViewPropertyAnimator animator = view.animate() .translationY(view.getHeight()) .setInterpolator(INTERPOLATOR) .setDuration(200); - animator.setListener(new Animator.AnimatorListener() - { + animator.setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) {} - @Override - public void onAnimationEnd(Animator animator) - { + public void onAnimationEnd(Animator animator) { // Prevent drawing the View after it is gone mIsHiding = false; view.setVisibility(View.GONE); } - @Override - public void onAnimationCancel(Animator animator) - { + public void onAnimationCancel(Animator animator) { // Canceling a hide should show the view mIsHiding = false; - if(!mIsShowing) - { + if (!mIsShowing) { show(view); } } - @Override public void onAnimationRepeat(Animator animator) {} }); @@ -117,7 +96,6 @@ public void onAnimationRepeat(Animator animator) {} animator.start(); } - /** * Show the quick return view. *

@@ -126,42 +104,33 @@ public void onAnimationRepeat(Animator animator) {} * * @param view The quick return view */ - private void show(final View view) - { + private void show(final View view) { mIsShowing = true; ViewPropertyAnimator animator = view.animate() .translationY(0) .setInterpolator(INTERPOLATOR) .setDuration(200); - animator.setListener(new Animator.AnimatorListener() - { + animator.setListener(new Animator.AnimatorListener() { @Override - public void onAnimationStart(Animator animator) - { + public void onAnimationStart(Animator animator) { view.setVisibility(View.VISIBLE); } - @Override - public void onAnimationEnd(Animator animator) - { + public void onAnimationEnd(Animator animator) { mIsShowing = false; } - @Override - public void onAnimationCancel(Animator animator) - { + public void onAnimationCancel(Animator animator) { // Canceling a show should hide the view mIsShowing = false; - if(!mIsHiding) - { + if (!mIsHiding) { hide(view); } } - @Override public void onAnimationRepeat(Animator animator) {} }); diff --git a/Src-CoordinatorLayout/java/widget/ScalingFloatingActionButtonBehavior.java b/Src-CoordinatorLayout/java/widget/ScalingFloatingActionButtonBehavior.java index ca96636..24776e4 100644 --- a/Src-CoordinatorLayout/java/widget/ScalingFloatingActionButtonBehavior.java +++ b/Src-CoordinatorLayout/java/widget/ScalingFloatingActionButtonBehavior.java @@ -9,53 +9,38 @@ import org.alfonz.utility.ResourcesUtility; - -public class ScalingFloatingActionButtonBehavior extends FloatingActionButton.Behavior -{ +public class ScalingFloatingActionButtonBehavior extends FloatingActionButton.Behavior { private int mActionBarSize; - - public ScalingFloatingActionButtonBehavior(Context context, AttributeSet attrs) - { + public ScalingFloatingActionButtonBehavior(Context context, AttributeSet attrs) { super(context, attrs); mActionBarSize = ResourcesUtility.getDimensionPixelSizeValueOfAttribute(context, android.R.attr.actionBarSize); } - @Override - public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { + public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) { return super.layoutDependsOn(parent, child, dependency) || dependency instanceof AppBarLayout; } - @Override - public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { - if(dependency instanceof AppBarLayout) - { + public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) { + if (dependency instanceof AppBarLayout) { return updateFab(child, dependency); - } - else - { + } else { return super.onDependentViewChanged(parent, child, dependency); } } - - private boolean updateFab(FloatingActionButton child, View dependency) - { + private boolean updateFab(FloatingActionButton child, View dependency) { float toolbarPosition = dependency.getY(); // toolbar is gone - if(toolbarPosition + mActionBarSize == 0) - { + if (toolbarPosition + mActionBarSize == 0) { child.hide(); } // toolbar is visible - else - { + else { child.show(); } diff --git a/Src-CoordinatorLayout/java/widget/SlidingFloatingActionButtonBehavior.java b/Src-CoordinatorLayout/java/widget/SlidingFloatingActionButtonBehavior.java index 55cd4f0..cd996e9 100644 --- a/Src-CoordinatorLayout/java/widget/SlidingFloatingActionButtonBehavior.java +++ b/Src-CoordinatorLayout/java/widget/SlidingFloatingActionButtonBehavior.java @@ -11,82 +11,61 @@ import org.alfonz.utility.ResourcesUtility; - -public class SlidingFloatingActionButtonBehavior extends FloatingActionButton.Behavior -{ +public class SlidingFloatingActionButtonBehavior extends FloatingActionButton.Behavior { private int mActionBarSize; private float mSnackbarTranslation = 0; - - public SlidingFloatingActionButtonBehavior(Context context, AttributeSet attrs) - { + public SlidingFloatingActionButtonBehavior(Context context, AttributeSet attrs) { super(context, attrs); mActionBarSize = ResourcesUtility.getDimensionPixelSizeValueOfAttribute(context, android.R.attr.actionBarSize); } - @Override - public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { + public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) { return super.layoutDependsOn(parent, child, dependency) || dependency instanceof Snackbar.SnackbarLayout || dependency instanceof AppBarLayout; } - @Override - public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) - { - if(dependency instanceof AppBarLayout) - { + public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) { + if (dependency instanceof AppBarLayout) { return updateFab(child, dependency); - } - else if(dependency instanceof Snackbar.SnackbarLayout) - { + } else if (dependency instanceof Snackbar.SnackbarLayout) { updateSnackbarTranslationField(dependency); return super.onDependentViewChanged(parent, child, dependency); - } - else - { + } else { return super.onDependentViewChanged(parent, child, dependency); } } - - private boolean updateFab(FloatingActionButton child, View dependency) - { + private boolean updateFab(FloatingActionButton child, View dependency) { float toolbarPosition = dependency.getY(); float fabTranslation = -(toolbarPosition * 2) - mSnackbarTranslation; // snackbar is visible - if(mSnackbarTranslation > 0) - { + if (mSnackbarTranslation > 0) { // toolbar is gone - if((-dependency.getY()) > dependency.getHeight() / 8) - { + if ((-dependency.getY()) > dependency.getHeight() / 8) { child.setVisibility(View.GONE); } // toolbar is visible - else - { + else { child.setVisibility(View.VISIBLE); } } // snackbar is gone - else - { + else { // toolbar is gone - if(toolbarPosition + mActionBarSize == 0) - { + if (toolbarPosition + mActionBarSize == 0) { child.setVisibility(View.GONE); } // toolbar is visible - else - { + else { child.setVisibility(View.VISIBLE); } } @@ -95,21 +74,17 @@ private boolean updateFab(FloatingActionButton child, View dependency) return fabTranslation != 0; } - - private void updateSnackbarTranslationField(View dependency) - { + private void updateSnackbarTranslationField(View dependency) { float snackbarTranslation = dependency.getHeight() - dependency.getTranslationY(); boolean isDismissed = dependency.getX() > 0 && dependency.getX() > dependency.getWidth() / 2; // is dismissed by swipe // snackbar is gone - if(snackbarTranslation < 1 || isDismissed || dependency.getVisibility() != View.VISIBLE) - { + if (snackbarTranslation < 1 || isDismissed || dependency.getVisibility() != View.VISIBLE) { mSnackbarTranslation = 0; } // snackbar is visible - else - { + else { mSnackbarTranslation = snackbarTranslation; } } diff --git a/Src-Copy-Constructors/java/entity/ExampleEntity.java b/Src-Copy-Constructors/java/entity/ExampleEntity.java index e0dc562..0351ced 100644 --- a/Src-Copy-Constructors/java/entity/ExampleEntity.java +++ b/Src-Copy-Constructors/java/entity/ExampleEntity.java @@ -6,9 +6,7 @@ import java.util.Iterator; import java.util.List; - -public class ExampleEntity -{ +public class ExampleEntity { private boolean booleanVar; private int intVar; private long longVar; @@ -18,132 +16,93 @@ public class ExampleEntity private MyEntity myEntity; private List stringList; - // empty constructor - public ExampleEntity() - { + public ExampleEntity() { } - // copy constructor - public ExampleEntity(ExampleEntity origin) - { + public ExampleEntity(ExampleEntity origin) { booleanVar = origin.booleanVar; intVar = origin.intVar; longVar = origin.longVar; - if(origin.stringVar != null) stringVar = new String(origin.stringVar); - if(origin.dateVar != null) dateVar = new Date(origin.dateVar.getTime()); - if(origin.calendarVar != null) - { + if (origin.stringVar != null) stringVar = new String(origin.stringVar); + if (origin.dateVar != null) dateVar = new Date(origin.dateVar.getTime()); + if (origin.calendarVar != null) { calendarVar = Calendar.getInstance(); calendarVar.setTime(origin.calendarVar.getTime()); } - if(origin.myEntity != null) myEntity = new MyEntity(origin.myEntity); - if(origin.stringList != null) - { + if (origin.myEntity != null) myEntity = new MyEntity(origin.myEntity); + if (origin.stringList != null) { stringList = new ArrayList<>(); Iterator iterator = origin.stringList.iterator(); - while(iterator.hasNext()) - { + while (iterator.hasNext()) { String s = iterator.next(); stringList.add(new String(s)); } } } - - public boolean isBooleanVar() - { + public boolean isBooleanVar() { return booleanVar; } - - public void setBooleanVar(boolean booleanVar) - { + public void setBooleanVar(boolean booleanVar) { this.booleanVar = booleanVar; } - - public int getIntVar() - { + public int getIntVar() { return intVar; } - - public void setIntVar(int intVar) - { + public void setIntVar(int intVar) { this.intVar = intVar; } - - public long getLongVar() - { + public long getLongVar() { return longVar; } - - public void setLongVar(long longVar) - { + public void setLongVar(long longVar) { this.longVar = longVar; } - - public String getStringVar() - { + public String getStringVar() { return stringVar; } - - public void setStringVar(String stringVar) - { + public void setStringVar(String stringVar) { this.stringVar = stringVar; } - - public Date getDateVar() - { + public Date getDateVar() { return dateVar; } - - public void setDateVar(Date dateVar) - { + public void setDateVar(Date dateVar) { this.dateVar = dateVar; } - - public Calendar getCalendarVar() - { + public Calendar getCalendarVar() { return calendarVar; } - - public void setCalendarVar(Calendar calendarVar) - { + public void setCalendarVar(Calendar calendarVar) { this.calendarVar = calendarVar; } - - public MyEntity getMyEntity() - { + public MyEntity getMyEntity() { return myEntity; } - - public void setMyEntity(MyEntity myEntity) - { + public void setMyEntity(MyEntity myEntity) { this.myEntity = myEntity; } - - public List getStringList() - { + public List getStringList() { return stringList; } - - public void setStringList(List stringList) - { + public void setStringList(List stringList) { this.stringList = stringList; } } diff --git a/Src-DialogFragment/java/dialog/CustomDialogFragment.java b/Src-DialogFragment/java/dialog/CustomDialogFragment.java index bbbb41e..8cd9439 100644 --- a/Src-DialogFragment/java/dialog/CustomDialogFragment.java +++ b/Src-DialogFragment/java/dialog/CustomDialogFragment.java @@ -14,9 +14,7 @@ import com.example.R; - -public class CustomDialogFragment extends DialogFragment -{ +public class CustomDialogFragment extends DialogFragment { private static final String ARGUMENT_EXAMPLE = "example"; private static final String SAVED_USERNAME = "username"; private static final String SAVED_PASSWORD = "password"; @@ -27,16 +25,12 @@ public class CustomDialogFragment extends DialogFragment private String mPassword = ""; private CustomDialogListener mListener; - - public interface CustomDialogListener - { + public interface CustomDialogListener { void onCustomDialogPositiveClick(DialogFragment dialog, String username, String password); void onCustomDialogNegativeClick(DialogFragment dialog); } - - public static CustomDialogFragment newInstance(String example) - { + public static CustomDialogFragment newInstance(String example) { CustomDialogFragment fragment = new CustomDialogFragment(); // arguments @@ -47,60 +41,47 @@ public static CustomDialogFragment newInstance(String example) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } - + // set callback listener - try - { + try { mListener = (CustomDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + CustomDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); mRootView = inflater.inflate(R.layout.dialog_custom, null); @@ -109,17 +90,13 @@ public Dialog onCreateDialog(Bundle savedInstanceState) .setTitle(mExample) .setIcon(R.mipmap.ic_launcher) .setView(mRootView) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { // overriden below } }) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onCustomDialogNegativeClick(CustomDialogFragment.this); } }); @@ -128,18 +105,14 @@ public void onClick(DialogInterface dialog, int id) final AppCompatDialog dialog = builder.create(); // override positive button - dialog.setOnShowListener(new DialogInterface.OnShowListener() - { + dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override - public void onShow(DialogInterface dialogInterface) - { + public void onShow(DialogInterface dialogInterface) { Button button = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE); button.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getActivity(), R.mipmap.ic_launcher), null, null, null); - button.setOnClickListener(new View.OnClickListener() - { + button.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { EditText usernameEditText = mRootView.findViewById(R.id.dialog_custom_username); EditText passwordEditText = mRootView.findViewById(R.id.dialog_custom_password); @@ -158,10 +131,8 @@ public void onClick(View v) return dialog; } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); @@ -172,28 +143,21 @@ public void onSaveInstanceState(Bundle outState) outState.putString(SAVED_PASSWORD, passwordEditText.getText().toString()); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_EXAMPLE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_EXAMPLE)) { mExample = (String) arguments.get(ARGUMENT_EXAMPLE); } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { EditText usernameEditText = mRootView.findViewById(R.id.dialog_custom_username); EditText passwordEditText = mRootView.findViewById(R.id.dialog_custom_password); - if(savedInstanceState.containsKey(SAVED_USERNAME)) - { + if (savedInstanceState.containsKey(SAVED_USERNAME)) { usernameEditText.setText((String) savedInstanceState.get(SAVED_USERNAME)); } - if(savedInstanceState.containsKey(SAVED_PASSWORD)) - { + if (savedInstanceState.containsKey(SAVED_PASSWORD)) { passwordEditText.setText((String) savedInstanceState.get(SAVED_PASSWORD)); } } diff --git a/Src-DialogFragment/java/dialog/DatePickerDialogFragment.java b/Src-DialogFragment/java/dialog/DatePickerDialogFragment.java index 20cd5a1..195b17e 100644 --- a/Src-DialogFragment/java/dialog/DatePickerDialogFragment.java +++ b/Src-DialogFragment/java/dialog/DatePickerDialogFragment.java @@ -8,23 +8,17 @@ import java.util.Calendar; - -public class DatePickerDialogFragment extends DialogFragment implements FixedDatePickerDialog.OnDateSetListener -{ +public class DatePickerDialogFragment extends DialogFragment implements FixedDatePickerDialog.OnDateSetListener { private static final String ARGUMENT_DATE = "date"; private long mDate = -1L; private DatePickerDialogListener mListener; - - public interface DatePickerDialogListener - { + public interface DatePickerDialogListener { void onDatePickerDialogPositiveClick(DialogFragment dialog, int year, int month, int day); } - - public static DatePickerDialogFragment newInstance(Calendar calendar) - { + public static DatePickerDialogFragment newInstance(Calendar calendar) { DatePickerDialogFragment fragment = new DatePickerDialogFragment(); // arguments @@ -35,48 +29,37 @@ public static DatePickerDialogFragment newInstance(Calendar calendar) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // set callback listener - try - { + try { mListener = (DatePickerDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + DatePickerDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar calendar = Calendar.getInstance(); - if(mDate != -1L) - { + if (mDate != -1L) { calendar.setTimeInMillis(mDate); } @@ -84,24 +67,17 @@ public Dialog onCreateDialog(Bundle savedInstanceState) return new FixedDatePickerDialog(calendar, context, this); } - @Override - public void onDateSet(DatePicker view, int year, int month, int day) - { + public void onDateSet(DatePicker view, int year, int month, int day) { mListener.onDatePickerDialogPositiveClick(DatePickerDialogFragment.this, year, month, day); } - - private int getTheme(boolean light) - { + private int getTheme(boolean light) { return light ? android.R.style.Theme_DeviceDefault_Light_Dialog : android.R.style.Theme_DeviceDefault_Dialog; } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_DATE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_DATE)) { mDate = (Long) arguments.get(ARGUMENT_DATE); } } diff --git a/Src-DialogFragment/java/dialog/FixedDatePickerDialog.java b/Src-DialogFragment/java/dialog/FixedDatePickerDialog.java index 57c3cad..da9a7af 100644 --- a/Src-DialogFragment/java/dialog/FixedDatePickerDialog.java +++ b/Src-DialogFragment/java/dialog/FixedDatePickerDialog.java @@ -7,46 +7,34 @@ import java.util.Calendar; - // source: http://stackoverflow.com/questions/11444238/jelly-bean-datepickerdialog-is-there-a-way-to-cancel -public class FixedDatePickerDialog extends DatePickerDialog -{ - public FixedDatePickerDialog(Calendar dateToShow, Context context, OnDateSetListener callBack) - { +public class FixedDatePickerDialog extends DatePickerDialog { + public FixedDatePickerDialog(Calendar dateToShow, Context context, OnDateSetListener callBack) { super(context, null, dateToShow.get(Calendar.YEAR), dateToShow.get(Calendar.MONTH), dateToShow.get(Calendar.DAY_OF_MONTH)); initializePicker(callBack); } - - public FixedDatePickerDialog(Calendar dateToShow, Context context, int theme, OnDateSetListener callBack) - { + public FixedDatePickerDialog(Calendar dateToShow, Context context, int theme, OnDateSetListener callBack) { super(context, theme, null, dateToShow.get(Calendar.YEAR), dateToShow.get(Calendar.MONTH), dateToShow.get(Calendar.DAY_OF_MONTH)); initializePicker(callBack); } - - private void initializePicker(final OnDateSetListener callback) - { - try - { + private void initializePicker(final OnDateSetListener callback) { + try { // if you're only using Honeycomb+ then you can just call getDatePicker() instead of using reflection java.lang.reflect.Field pickerField = DatePickerDialog.class.getDeclaredField("mDatePicker"); pickerField.setAccessible(true); final DatePicker picker = (DatePicker) pickerField.get(this); this.setCancelable(true); this.setButton(DialogInterface.BUTTON_NEGATIVE, getContext().getText(android.R.string.cancel), (OnClickListener) null); - this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok), new DialogInterface.OnClickListener() - { + this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok), new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { picker.clearFocus(); // focus must be cleared so the value change listener is called callback.onDateSet(picker, picker.getYear(), picker.getMonth(), picker.getDayOfMonth()); } }); - } - catch(Exception e) - { + } catch (Exception e) { // reflection probably failed } } diff --git a/Src-DialogFragment/java/dialog/FixedTimePickerDialog.java b/Src-DialogFragment/java/dialog/FixedTimePickerDialog.java index ffda923..7ebeaa5 100644 --- a/Src-DialogFragment/java/dialog/FixedTimePickerDialog.java +++ b/Src-DialogFragment/java/dialog/FixedTimePickerDialog.java @@ -8,46 +8,34 @@ import java.util.Calendar; - // source: http://stackoverflow.com/questions/11444238/jelly-bean-datepickerdialog-is-there-a-way-to-cancel -public class FixedTimePickerDialog extends TimePickerDialog -{ - public FixedTimePickerDialog(Calendar timeToShow, Context context, OnTimeSetListener callBack) - { +public class FixedTimePickerDialog extends TimePickerDialog { + public FixedTimePickerDialog(Calendar timeToShow, Context context, OnTimeSetListener callBack) { super(context, null, timeToShow.get(Calendar.HOUR_OF_DAY), timeToShow.get(Calendar.MINUTE), DateFormat.is24HourFormat(context)); initializePicker(callBack); } - - public FixedTimePickerDialog(Calendar timeToShow, Context context, int theme, OnTimeSetListener callBack) - { + public FixedTimePickerDialog(Calendar timeToShow, Context context, int theme, OnTimeSetListener callBack) { super(context, theme, null, timeToShow.get(Calendar.HOUR_OF_DAY), timeToShow.get(Calendar.MINUTE), DateFormat.is24HourFormat(context)); initializePicker(callBack); } - - private void initializePicker(final OnTimeSetListener callback) - { - try - { + private void initializePicker(final OnTimeSetListener callback) { + try { // if you're only using Honeycomb+ then you can just call getTimePicker() instead of using reflection java.lang.reflect.Field pickerField = TimePickerDialog.class.getDeclaredField("mTimePicker"); pickerField.setAccessible(true); final TimePicker picker = (TimePicker) pickerField.get(this); this.setCancelable(true); this.setButton(DialogInterface.BUTTON_NEGATIVE, getContext().getText(android.R.string.cancel), (OnClickListener) null); - this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok), new DialogInterface.OnClickListener() - { + this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok), new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { picker.clearFocus(); // focus must be cleared so the value change listener is called callback.onTimeSet(picker, picker.getCurrentHour(), picker.getCurrentMinute()); } }); - } - catch(Exception e) - { + } catch (Exception e) { // reflection probably failed } } diff --git a/Src-DialogFragment/java/dialog/ItemsDialogFragment.java b/Src-DialogFragment/java/dialog/ItemsDialogFragment.java index 149cdf6..95b0044 100644 --- a/Src-DialogFragment/java/dialog/ItemsDialogFragment.java +++ b/Src-DialogFragment/java/dialog/ItemsDialogFragment.java @@ -8,25 +8,19 @@ import com.example.R; - -public class ItemsDialogFragment extends DialogFragment -{ +public class ItemsDialogFragment extends DialogFragment { private static final String ARGUMENT_EXAMPLE = "example"; private String mExample; private ItemsDialogListener mListener; - - public interface ItemsDialogListener - { + public interface ItemsDialogListener { void onItemsDialogItemClick(DialogFragment dialog, int which); void onItemsDialogPositiveClick(DialogFragment dialog); void onItemsDialogNegativeClick(DialogFragment dialog); } - - public static ItemsDialogFragment newInstance(String example) - { + public static ItemsDialogFragment newInstance(String example) { ItemsDialogFragment fragment = new ItemsDialogFragment(); // arguments @@ -37,54 +31,42 @@ public static ItemsDialogFragment newInstance(String example) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // set callback listener - try - { + try { mListener = (ItemsDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + ItemsDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { final CharSequence items[] = { "item1", "item2", @@ -96,25 +78,19 @@ public Dialog onCreateDialog(Bundle savedInstanceState) builder .setTitle(mExample) .setIcon(R.mipmap.ic_launcher) - .setItems(items, new DialogInterface.OnClickListener() - { + .setItems(items, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { mListener.onItemsDialogItemClick(ItemsDialogFragment.this, which); } }) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onItemsDialogPositiveClick(ItemsDialogFragment.this); } }) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onItemsDialogNegativeClick(ItemsDialogFragment.this); } }); @@ -122,11 +98,8 @@ public void onClick(DialogInterface dialog, int id) return builder.create(); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_EXAMPLE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_EXAMPLE)) { mExample = (String) arguments.get(ARGUMENT_EXAMPLE); } } diff --git a/Src-DialogFragment/java/dialog/MultiChoiceItemsDialogFragment.java b/Src-DialogFragment/java/dialog/MultiChoiceItemsDialogFragment.java index 67a62df..e739e0f 100644 --- a/Src-DialogFragment/java/dialog/MultiChoiceItemsDialogFragment.java +++ b/Src-DialogFragment/java/dialog/MultiChoiceItemsDialogFragment.java @@ -9,25 +9,19 @@ import com.example.R; - -public class MultiChoiceItemsDialogFragment extends DialogFragment -{ +public class MultiChoiceItemsDialogFragment extends DialogFragment { private static final String ARGUMENT_CHECKED_ITEMS = "checked_items"; private static final String SAVED_CHECKED_ITEMS = "checked_items"; private boolean mCheckedItems[] = null; private MultiChoiceItemsDialogListener mListener; - - public interface MultiChoiceItemsDialogListener - { + public interface MultiChoiceItemsDialogListener { void onMultiChoiceItemsDialogPositiveClick(DialogFragment dialog, boolean checkedItems[]); void onMultiChoiceItemsDialogNegativeClick(DialogFragment dialog); } - - public static MultiChoiceItemsDialogFragment newInstance(boolean checkedItems[]) - { + public static MultiChoiceItemsDialogFragment newInstance(boolean checkedItems[]) { MultiChoiceItemsDialogFragment fragment = new MultiChoiceItemsDialogFragment(); // arguments @@ -38,60 +32,47 @@ public static MultiChoiceItemsDialogFragment newInstance(boolean checkedItems[]) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } // set callback listener - try - { + try { mListener = (MultiChoiceItemsDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + MultiChoiceItemsDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { final CharSequence items[] = { "item1", "item2", @@ -103,25 +84,19 @@ public Dialog onCreateDialog(Bundle savedInstanceState) builder .setTitle("title") .setIcon(R.mipmap.ic_launcher) - .setMultiChoiceItems(items, mCheckedItems, new OnMultiChoiceClickListener() - { + .setMultiChoiceItems(items, mCheckedItems, new OnMultiChoiceClickListener() { @Override - public void onClick(DialogInterface dialog, int which, boolean isChecked) - { + public void onClick(DialogInterface dialog, int which, boolean isChecked) { mCheckedItems[which] = isChecked; } }) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onMultiChoiceItemsDialogPositiveClick(MultiChoiceItemsDialogFragment.this, mCheckedItems); } }) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onMultiChoiceItemsDialogNegativeClick(MultiChoiceItemsDialogFragment.this); } }); @@ -129,28 +104,20 @@ public void onClick(DialogInterface dialog, int id) return builder.create(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBooleanArray(SAVED_CHECKED_ITEMS, mCheckedItems); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_CHECKED_ITEMS)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_CHECKED_ITEMS)) { mCheckedItems = (boolean[]) arguments.get(ARGUMENT_CHECKED_ITEMS); } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { - if(savedInstanceState.containsKey(SAVED_CHECKED_ITEMS)) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { + if (savedInstanceState.containsKey(SAVED_CHECKED_ITEMS)) { mCheckedItems = (boolean[]) savedInstanceState.get(SAVED_CHECKED_ITEMS); } } diff --git a/Src-DialogFragment/java/dialog/ProgressDialogFragment.java b/Src-DialogFragment/java/dialog/ProgressDialogFragment.java index 6f5c099..bebc154 100644 --- a/Src-DialogFragment/java/dialog/ProgressDialogFragment.java +++ b/Src-DialogFragment/java/dialog/ProgressDialogFragment.java @@ -6,36 +6,27 @@ import android.support.v4.app.DialogFragment; import android.view.ContextThemeWrapper; - -public class ProgressDialogFragment extends DialogFragment -{ - public static ProgressDialogFragment newInstance() - { +public class ProgressDialogFragment extends DialogFragment { + public static ProgressDialogFragment newInstance() { ProgressDialogFragment fragment = new ProgressDialogFragment(); return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(false); } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { ContextThemeWrapper context = new ContextThemeWrapper(getActivity(), getTheme(true)); ProgressDialog dialog = new ProgressDialog(context); dialog.setMessage("progress"); @@ -44,15 +35,11 @@ public Dialog onCreateDialog(Bundle savedInstanceState) return dialog; } - - public void dismiss() - { + public void dismiss() { getDialog().dismiss(); } - - private int getTheme(boolean light) - { + private int getTheme(boolean light) { return light ? android.R.style.Theme_DeviceDefault_Light_Dialog : android.R.style.Theme_DeviceDefault_Dialog; } } diff --git a/Src-DialogFragment/java/dialog/SheetDialogFragment.java b/Src-DialogFragment/java/dialog/SheetDialogFragment.java index 3ccd721..8f70e3c 100644 --- a/Src-DialogFragment/java/dialog/SheetDialogFragment.java +++ b/Src-DialogFragment/java/dialog/SheetDialogFragment.java @@ -14,9 +14,7 @@ import com.example.R; - -public class SheetDialogFragment extends BottomSheetDialogFragment -{ +public class SheetDialogFragment extends BottomSheetDialogFragment { private static final String ARGUMENT_EXAMPLE = "example"; private static final String SAVED_USERNAME = "username"; private static final String SAVED_PASSWORD = "password"; @@ -28,16 +26,12 @@ public class SheetDialogFragment extends BottomSheetDialogFragment private String mPassword = ""; private SheetDialogListener mListener; - - public interface SheetDialogListener - { + public interface SheetDialogListener { void onSheetDialogStateChanged(DialogFragment dialog, int newState, String username, String password); void onSheetDialogDismiss(DialogFragment dialog, String username, String password); } - - public static SheetDialogFragment newInstance(String example) - { + public static SheetDialogFragment newInstance(String example) { SheetDialogFragment fragment = new SheetDialogFragment(); // arguments @@ -48,60 +42,47 @@ public static SheetDialogFragment newInstance(String example) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // set callback listener - try - { + try { mListener = (SheetDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + SheetDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { // inflate layout LayoutInflater inflater = getActivity().getLayoutInflater(); mRootView = inflater.inflate(R.layout.dialog_custom, null); @@ -116,11 +97,9 @@ public Dialog onCreateDialog(Bundle savedInstanceState) // setup behavior mBehavior = BottomSheetBehavior.from((View) mRootView.getParent()); - mBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() - { + mBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override - public void onStateChanged(@NonNull View bottomSheet, int newState) - { + public void onStateChanged(@NonNull View bottomSheet, int newState) { EditText usernameEditText = mRootView.findViewById(R.id.dialog_custom_username); EditText passwordEditText = mRootView.findViewById(R.id.dialog_custom_password); @@ -130,13 +109,11 @@ public void onStateChanged(@NonNull View bottomSheet, int newState) // TODO: data validation mListener.onSheetDialogStateChanged(SheetDialogFragment.this, newState, username, password); - if(newState == BottomSheetBehavior.STATE_HIDDEN) dialog.dismiss(); + if (newState == BottomSheetBehavior.STATE_HIDDEN) dialog.dismiss(); } - @Override - public void onSlide(@NonNull View bottomSheet, float slideOffset) - { + public void onSlide(@NonNull View bottomSheet, float slideOffset) { // do nothing } }); @@ -144,10 +121,8 @@ public void onSlide(@NonNull View bottomSheet, float slideOffset) return dialog; } - @Override - public void onDismiss(DialogInterface dialog) - { + public void onDismiss(DialogInterface dialog) { EditText usernameEditText = mRootView.findViewById(R.id.dialog_custom_username); EditText passwordEditText = mRootView.findViewById(R.id.dialog_custom_password); @@ -159,16 +134,13 @@ public void onDismiss(DialogInterface dialog) mListener.onSheetDialogDismiss(SheetDialogFragment.this, username, password); // destroy dialog fragment - if(getFragmentManager() != null) - { + if (getFragmentManager() != null) { getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss(); } } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); @@ -179,28 +151,21 @@ public void onSaveInstanceState(Bundle outState) outState.putString(SAVED_PASSWORD, passwordEditText.getText().toString()); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_EXAMPLE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_EXAMPLE)) { mExample = (String) arguments.get(ARGUMENT_EXAMPLE); } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { EditText usernameEditText = mRootView.findViewById(R.id.dialog_custom_username); EditText passwordEditText = mRootView.findViewById(R.id.dialog_custom_password); - if(savedInstanceState.containsKey(SAVED_USERNAME)) - { + if (savedInstanceState.containsKey(SAVED_USERNAME)) { usernameEditText.setText((String) savedInstanceState.get(SAVED_USERNAME)); } - if(savedInstanceState.containsKey(SAVED_PASSWORD)) - { + if (savedInstanceState.containsKey(SAVED_PASSWORD)) { passwordEditText.setText((String) savedInstanceState.get(SAVED_PASSWORD)); } } diff --git a/Src-DialogFragment/java/dialog/SimpleDialogFragment.java b/Src-DialogFragment/java/dialog/SimpleDialogFragment.java index 1faa55c..46fccff 100644 --- a/Src-DialogFragment/java/dialog/SimpleDialogFragment.java +++ b/Src-DialogFragment/java/dialog/SimpleDialogFragment.java @@ -8,24 +8,18 @@ import com.example.R; - -public class SimpleDialogFragment extends DialogFragment -{ +public class SimpleDialogFragment extends DialogFragment { private static final String ARGUMENT_EXAMPLE = "example"; private String mExample; private SimpleDialogListener mListener; - - public interface SimpleDialogListener - { + public interface SimpleDialogListener { void onSimpleDialogPositiveClick(DialogFragment dialog); void onSimpleDialogNegativeClick(DialogFragment dialog); } - - public static SimpleDialogFragment newInstance(String example) - { + public static SimpleDialogFragment newInstance(String example) { SimpleDialogFragment fragment = new SimpleDialogFragment(); // arguments @@ -36,71 +30,55 @@ public static SimpleDialogFragment newInstance(String example) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // set callback listener - try - { + try { mListener = (SimpleDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + SimpleDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder .setTitle("title") .setIcon(R.mipmap.ic_launcher) .setMessage(mExample) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onSimpleDialogPositiveClick(SimpleDialogFragment.this); } }) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onSimpleDialogNegativeClick(SimpleDialogFragment.this); } }); @@ -108,11 +86,8 @@ public void onClick(DialogInterface dialog, int id) return builder.create(); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_EXAMPLE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_EXAMPLE)) { mExample = (String) arguments.get(ARGUMENT_EXAMPLE); } } diff --git a/Src-DialogFragment/java/dialog/SingleChoiceItemsDialogFragment.java b/Src-DialogFragment/java/dialog/SingleChoiceItemsDialogFragment.java index f8675a1..6477450 100644 --- a/Src-DialogFragment/java/dialog/SingleChoiceItemsDialogFragment.java +++ b/Src-DialogFragment/java/dialog/SingleChoiceItemsDialogFragment.java @@ -8,25 +8,19 @@ import com.example.R; - -public class SingleChoiceItemsDialogFragment extends DialogFragment -{ +public class SingleChoiceItemsDialogFragment extends DialogFragment { private static final String ARGUMENT_CHECKED_ITEM = "checked_item"; private static final String SAVED_CHECKED_ITEM = "checked_item"; private int mCheckedItem = -1; private SingleChoiceItemsDialogListener mListener; - - public interface SingleChoiceItemsDialogListener - { + public interface SingleChoiceItemsDialogListener { void onSingleChoiceItemsDialogPositiveClick(DialogFragment dialog, int checkedItem); void onSingleChoiceItemsDialogNegativeClick(DialogFragment dialog); } - - public static SingleChoiceItemsDialogFragment newInstance(int checkedItem) - { + public static SingleChoiceItemsDialogFragment newInstance(int checkedItem) { SingleChoiceItemsDialogFragment fragment = new SingleChoiceItemsDialogFragment(); // arguments @@ -37,60 +31,47 @@ public static SingleChoiceItemsDialogFragment newInstance(int checkedItem) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } // set callback listener - try - { + try { mListener = (SingleChoiceItemsDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + SingleChoiceItemsDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public void onDestroyView() - { + public void onDestroyView() { // http://code.google.com/p/android/issues/detail?id=17423 - if(getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); + if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { final CharSequence items[] = { "item1", "item2", @@ -102,25 +83,19 @@ public Dialog onCreateDialog(Bundle savedInstanceState) builder .setTitle("title") .setIcon(R.mipmap.ic_launcher) - .setSingleChoiceItems(items, mCheckedItem, new DialogInterface.OnClickListener() - { + .setSingleChoiceItems(items, mCheckedItem, new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) - { + public void onClick(DialogInterface dialog, int which) { mCheckedItem = which; } }) - .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onSingleChoiceItemsDialogPositiveClick(SingleChoiceItemsDialogFragment.this, mCheckedItem); } }) - .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { mListener.onSingleChoiceItemsDialogNegativeClick(SingleChoiceItemsDialogFragment.this); } }); @@ -128,28 +103,20 @@ public void onClick(DialogInterface dialog, int id) return builder.create(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(ARGUMENT_CHECKED_ITEM, mCheckedItem); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_CHECKED_ITEM)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_CHECKED_ITEM)) { mCheckedItem = (Integer) arguments.get(ARGUMENT_CHECKED_ITEM); } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { - if(savedInstanceState.containsKey(SAVED_CHECKED_ITEM)) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { + if (savedInstanceState.containsKey(SAVED_CHECKED_ITEM)) { mCheckedItem = (Integer) savedInstanceState.get(SAVED_CHECKED_ITEM); } } diff --git a/Src-DialogFragment/java/dialog/TimePickerDialogFragment.java b/Src-DialogFragment/java/dialog/TimePickerDialogFragment.java index 02709fe..31182cc 100644 --- a/Src-DialogFragment/java/dialog/TimePickerDialogFragment.java +++ b/Src-DialogFragment/java/dialog/TimePickerDialogFragment.java @@ -8,23 +8,17 @@ import java.util.Calendar; - -public class TimePickerDialogFragment extends DialogFragment implements FixedTimePickerDialog.OnTimeSetListener -{ +public class TimePickerDialogFragment extends DialogFragment implements FixedTimePickerDialog.OnTimeSetListener { private static final String ARGUMENT_TIME = "time"; private long mTime = -1L; private TimePickerDialogListener mListener; - - public interface TimePickerDialogListener - { + public interface TimePickerDialogListener { void onTimePickerDialogPositiveClick(DialogFragment dialog, int hour, int minute); } - - public static TimePickerDialogFragment newInstance(Calendar calendar) - { + public static TimePickerDialogFragment newInstance(Calendar calendar) { TimePickerDialogFragment fragment = new TimePickerDialogFragment(); // arguments @@ -35,48 +29,37 @@ public static TimePickerDialogFragment newInstance(Calendar calendar) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCancelable(true); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // set callback listener - try - { + try { mListener = (TimePickerDialogListener) getTargetFragment(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getTargetFragment().toString() + " must implement " + TimePickerDialogListener.class.getName()); } } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // cancelable on touch outside - if(getDialog() != null) getDialog().setCanceledOnTouchOutside(true); + if (getDialog() != null) getDialog().setCanceledOnTouchOutside(true); } - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) - { + public Dialog onCreateDialog(Bundle savedInstanceState) { Calendar calendar = Calendar.getInstance(); - if(mTime != -1L) - { + if (mTime != -1L) { calendar.setTimeInMillis(mTime); } @@ -84,24 +67,17 @@ public Dialog onCreateDialog(Bundle savedInstanceState) return new FixedTimePickerDialog(calendar, context, this); } - @Override - public void onTimeSet(TimePicker view, int hour, int minute) - { + public void onTimeSet(TimePicker view, int hour, int minute) { mListener.onTimePickerDialogPositiveClick(TimePickerDialogFragment.this, hour, minute); } - - private int getTheme(boolean light) - { + private int getTheme(boolean light) { return light ? android.R.style.Theme_DeviceDefault_Light_Dialog : android.R.style.Theme_DeviceDefault_Dialog; } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_TIME)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_TIME)) { mTime = (Long) arguments.get(ARGUMENT_TIME); } } diff --git a/Src-DialogFragment/java/fragment/ExampleFragment.java b/Src-DialogFragment/java/fragment/ExampleFragment.java index aff7235..38e1b6f 100644 --- a/Src-DialogFragment/java/fragment/ExampleFragment.java +++ b/Src-DialogFragment/java/fragment/ExampleFragment.java @@ -24,7 +24,6 @@ import java.util.Calendar; - public class ExampleFragment extends Fragment implements SimpleDialogFragment.SimpleDialogListener, ItemsDialogFragment.ItemsDialogListener, @@ -33,8 +32,7 @@ public class ExampleFragment extends Fragment implements CustomDialogFragment.CustomDialogListener, TimePickerDialogFragment.TimePickerDialogListener, DatePickerDialogFragment.DatePickerDialogListener, - SheetDialogFragment.SheetDialogListener -{ + SheetDialogFragment.SheetDialogListener { private static final String DIALOG_SIMPLE = "simple"; private static final String DIALOG_ITEMS = "items"; private static final String DIALOG_SINGLE_CHOICE_ITEMS = "single_choice_items"; @@ -47,136 +45,99 @@ public class ExampleFragment extends Fragment implements private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupView(); } - @Override - public void onSimpleDialogPositiveClick(final DialogFragment dialog) - { + public void onSimpleDialogPositiveClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onSimpleDialogNegativeClick(final DialogFragment dialog) - { + public void onSimpleDialogNegativeClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onItemsDialogItemClick(final DialogFragment dialog, final int which) - { + public void onItemsDialogItemClick(final DialogFragment dialog, final int which) { Logcat.d(Integer.toString(which)); } - @Override - public void onItemsDialogPositiveClick(final DialogFragment dialog) - { + public void onItemsDialogPositiveClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onItemsDialogNegativeClick(final DialogFragment dialog) - { + public void onItemsDialogNegativeClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onSingleChoiceItemsDialogPositiveClick(final DialogFragment dialog, final int checkedItem) - { + public void onSingleChoiceItemsDialogPositiveClick(final DialogFragment dialog, final int checkedItem) { Logcat.d(Integer.toString(checkedItem)); } - @Override - public void onSingleChoiceItemsDialogNegativeClick(final DialogFragment dialog) - { + public void onSingleChoiceItemsDialogNegativeClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onMultiChoiceItemsDialogPositiveClick(final DialogFragment dialog, final boolean[] checkedItems) - { + public void onMultiChoiceItemsDialogPositiveClick(final DialogFragment dialog, final boolean[] checkedItems) { StringBuilder builder = new StringBuilder(); - for(int i = 0; i < checkedItems.length; i++) - { + for (int i = 0; i < checkedItems.length; i++) { builder.append(checkedItems[i]); builder.append(" "); } Logcat.d(builder.toString()); } - @Override - public void onMultiChoiceItemsDialogNegativeClick(final DialogFragment dialog) - { + public void onMultiChoiceItemsDialogNegativeClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onCustomDialogPositiveClick(final DialogFragment dialog, final String username, final String password) - { + public void onCustomDialogPositiveClick(final DialogFragment dialog, final String username, final String password) { Logcat.d(username + " / " + password); } - @Override - public void onCustomDialogNegativeClick(final DialogFragment dialog) - { + public void onCustomDialogNegativeClick(final DialogFragment dialog) { Logcat.d(""); } - @Override - public void onTimePickerDialogPositiveClick(final DialogFragment dialog, final int hour, final int minute) - { + public void onTimePickerDialogPositiveClick(final DialogFragment dialog, final int hour, final int minute) { Logcat.d(hour + ":" + minute); } - @Override - public void onDatePickerDialogPositiveClick(final DialogFragment dialog, final int year, final int month, final int day) - { + public void onDatePickerDialogPositiveClick(final DialogFragment dialog, final int year, final int month, final int day) { Logcat.d(day + "." + (month + 1) + "." + year); } - @Override - public void onSheetDialogStateChanged(final DialogFragment dialog, final int newState, final String username, final String password) - { + public void onSheetDialogStateChanged(final DialogFragment dialog, final int newState, final String username, final String password) { Logcat.d(newState + " / " + username + " / " + password); } - @Override - public void onSheetDialogDismiss(final DialogFragment dialog, final String username, final String password) - { + public void onSheetDialogDismiss(final DialogFragment dialog, final String username, final String password) { Logcat.d(username + " / " + password); } - - private void setupView() - { + private void setupView() { // reference Button button1 = mRootView.findViewById(R.id.example_button1); Button button2 = mRootView.findViewById(R.id.example_button2); @@ -189,35 +150,27 @@ private void setupView() Button button9 = mRootView.findViewById(R.id.example_button9); // content - button1.setOnClickListener(new OnClickListener() - { + button1.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showSimpleDialog("hello"); } }); - button2.setOnClickListener(new OnClickListener() - { + button2.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showItemsDialog("hello"); } }); - button3.setOnClickListener(new OnClickListener() - { + button3.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showSingleChoiceItemsDialog(-1); } }); - button4.setOnClickListener(new OnClickListener() - { + button4.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { final boolean[] checkedItems = { true, false, @@ -226,123 +179,93 @@ public void onClick(View v) showMultiChoiceItemsDialog(checkedItems); } }); - button5.setOnClickListener(new OnClickListener() - { + button5.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showCustomDialog("hello"); } }); - button6.setOnClickListener(new OnClickListener() - { + button6.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showTimePickerDialog(Calendar.getInstance()); } }); - button7.setOnClickListener(new OnClickListener() - { + button7.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showDatePickerDialog(Calendar.getInstance()); } }); - button8.setOnClickListener(new OnClickListener() - { + button8.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showProgressDialog(); } }); - button9.setOnClickListener(new OnClickListener() - { + button9.setOnClickListener(new OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { showSheetDialog("hello"); } }); } - - private void showSimpleDialog(String arg) - { + private void showSimpleDialog(String arg) { DialogFragment fragment = SimpleDialogFragment.newInstance(arg); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_SIMPLE); } - - private void showItemsDialog(String arg) - { + private void showItemsDialog(String arg) { DialogFragment fragment = ItemsDialogFragment.newInstance(arg); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_ITEMS); } - - private void showSingleChoiceItemsDialog(int checkedItem) - { + private void showSingleChoiceItemsDialog(int checkedItem) { DialogFragment fragment = SingleChoiceItemsDialogFragment.newInstance(checkedItem); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_SINGLE_CHOICE_ITEMS); } - - private void showMultiChoiceItemsDialog(boolean checkedItems[]) - { + private void showMultiChoiceItemsDialog(boolean checkedItems[]) { DialogFragment fragment = MultiChoiceItemsDialogFragment.newInstance(checkedItems); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_MULTI_CHOICE_ITEMS); } - - private void showCustomDialog(String arg) - { + private void showCustomDialog(String arg) { DialogFragment fragment = CustomDialogFragment.newInstance(arg); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_CUSTOM); } - - private void showTimePickerDialog(Calendar time) - { + private void showTimePickerDialog(Calendar time) { DialogFragment fragment = TimePickerDialogFragment.newInstance(time); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_TIME_PICKER); } - - private void showDatePickerDialog(Calendar date) - { + private void showDatePickerDialog(Calendar date) { DialogFragment fragment = DatePickerDialogFragment.newInstance(date); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_DATE_PICKER); } - - private void showProgressDialog() - { + private void showProgressDialog() { DialogFragment fragment = ProgressDialogFragment.newInstance(); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_PROGRESS); } - - private void hideProgressDialog() - { + private void hideProgressDialog() { getFragmentManager().executePendingTransactions(); DialogFragment fragment = (DialogFragment) getFragmentManager().findFragmentByTag(DIALOG_PROGRESS); - if(fragment != null) fragment.dismiss(); + if (fragment != null) fragment.dismiss(); } - - private void showSheetDialog(String arg) - { + private void showSheetDialog(String arg) { DialogFragment fragment = SheetDialogFragment.newInstance(arg); fragment.setTargetFragment(this, 0); fragment.show(getFragmentManager(), DIALOG_SHEET); diff --git a/Src-Dual-Pane/java/activity/ListingActivity.java b/Src-Dual-Pane/java/activity/ListingActivity.java index e58d47f..b31c8b9 100644 --- a/Src-Dual-Pane/java/activity/ListingActivity.java +++ b/Src-Dual-Pane/java/activity/ListingActivity.java @@ -11,9 +11,7 @@ import com.example.fragment.SimpleFragment; import com.example.listener.OnDualPaneShowListener; - -public class ListingActivity extends AppCompatActivity implements OnDualPaneShowListener -{ +public class ListingActivity extends AppCompatActivity implements OnDualPaneShowListener { private static final String SAVED_DUAL_PANE_FRAGMENT = "dual_pane_fragment"; private static final String SAVED_DUAL_PANE_INDEX = "dual_pane_index"; @@ -21,16 +19,13 @@ public class ListingActivity extends AppCompatActivity implements OnDualPaneShow private Class mDualPaneFragment = null; private int mDualPaneIndex = -1; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listing); // restore saved state - if(savedInstanceState != null) - { + if (savedInstanceState != null) { handleSavedInstanceState(savedInstanceState); } @@ -38,86 +33,67 @@ public void onCreate(Bundle savedInstanceState) handleDualPane(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); - if(mDualPaneFragment != null) outState.putString(SAVED_DUAL_PANE_FRAGMENT, mDualPaneFragment.getName()); - if(mDualPaneIndex != -1) outState.putInt(SAVED_DUAL_PANE_INDEX, mDualPaneIndex); + if (mDualPaneFragment != null) outState.putString(SAVED_DUAL_PANE_FRAGMENT, mDualPaneFragment.getName()); + if (mDualPaneIndex != -1) outState.putInt(SAVED_DUAL_PANE_INDEX, mDualPaneIndex); } - @Override - public void onDualPaneShow(Class targetFragment, int index) - { + public void onDualPaneShow(Class targetFragment, int index) { mDualPaneFragment = targetFragment; mDualPaneIndex = index; - if(mDualPane) - { + if (mDualPane) { Fragment fragment = null; String tag = null; // type of fragment to be replaced - if(targetFragment.equals(SimpleFragment.class)) - { + if (targetFragment.equals(SimpleFragment.class)) { fragment = SimpleFragment.newInstance(index); tag = SimpleFragment.class.getSimpleName(); } // replace fragment - if(fragment != null) - { + if (fragment != null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.container_dual_pane, fragment, tag); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.commit(); } - } - else - { + } else { Intent intent = null; // type of activity to be started - if(targetFragment.equals(SimpleFragment.class)) - { + if (targetFragment.equals(SimpleFragment.class)) { intent = SimpleActivity.newIntent(this, index); } // start activity - if(intent != null) - { + if (intent != null) { startActivity(intent); } } } - - private void handleSavedInstanceState(Bundle savedInstanceState) - { + private void handleSavedInstanceState(Bundle savedInstanceState) { String dualPaneFragmentString = savedInstanceState.getString(SAVED_DUAL_PANE_FRAGMENT); - try - { - if(dualPaneFragmentString != null) mDualPaneFragment = Class.forName(dualPaneFragmentString); - } - catch(ClassNotFoundException e) - { + try { + if (dualPaneFragmentString != null) mDualPaneFragment = Class.forName(dualPaneFragmentString); + } catch (ClassNotFoundException e) { e.printStackTrace(); } mDualPaneIndex = savedInstanceState.getInt(SAVED_DUAL_PANE_INDEX, -1); } - - private void handleDualPane() - { + private void handleDualPane() { // activity has dual pane layout View dualPaneContainer = findViewById(R.id.container_dual_pane); mDualPane = dualPaneContainer != null && dualPaneContainer.getVisibility() == View.VISIBLE; - if(mDualPane && mDualPaneFragment != null && mDualPaneIndex != -1) - { + if (mDualPane && mDualPaneFragment != null && mDualPaneIndex != -1) { onDualPaneShow(mDualPaneFragment, mDualPaneIndex); } } diff --git a/Src-Dual-Pane/java/activity/SimpleActivity.java b/Src-Dual-Pane/java/activity/SimpleActivity.java index 60a2318..3b779a5 100644 --- a/Src-Dual-Pane/java/activity/SimpleActivity.java +++ b/Src-Dual-Pane/java/activity/SimpleActivity.java @@ -7,14 +7,10 @@ import com.example.R; - -public class SimpleActivity extends AppCompatActivity -{ +public class SimpleActivity extends AppCompatActivity { public static final String EXTRA_PRODUCT_ID = "product_id"; - - public static Intent newIntent(Context context, int productId) - { + public static Intent newIntent(Context context, int productId) { Intent intent = new Intent(context, SimpleActivity.class); // extras @@ -23,15 +19,12 @@ public static Intent newIntent(Context context, int productId) return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // if activity has dual pane layout, we don't need this activity - if(getResources().getBoolean(R.bool.dual_pane)) - { + if (getResources().getBoolean(R.bool.dual_pane)) { finish(); return; } diff --git a/Src-Dual-Pane/java/fragment/ListingFragment.java b/Src-Dual-Pane/java/fragment/ListingFragment.java index b63141d..b5c37b0 100644 --- a/Src-Dual-Pane/java/fragment/ListingFragment.java +++ b/Src-Dual-Pane/java/fragment/ListingFragment.java @@ -18,50 +18,37 @@ import java.util.ArrayList; import java.util.List; - -public class ListingFragment extends Fragment -{ +public class ListingFragment extends Fragment { private View mRootView; private ListingAdapter mAdapter; private OnDualPaneShowListener mDualPaneShowListener; private List mProductList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); // set dual pane listener - try - { + try { mDualPaneShowListener = (OnDualPaneShowListener) getActivity(); - } - catch(ClassCastException e) - { + } catch (ClassCastException e) { throw new ClassCastException(getActivity().getClass().getName() + " must implement " + OnDualPaneShowListener.class.getName()); } } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupView(); } - - private void setupView() - { + private void setupView() { boolean init = false; // reference @@ -69,8 +56,7 @@ private void setupView() ViewGroup emptyView = mRootView.findViewById(android.R.id.empty); // testing data - for(int i = 0; i < 32; i++) - { + for (int i = 0; i < 32; i++) { ProductEntity p = new ProductEntity(); p.setName("Product " + (i)); mProductList.add(p); @@ -81,20 +67,16 @@ private void setupView() boolean dualPane = dualPaneContainer != null && dualPaneContainer.getVisibility() == View.VISIBLE; // listview content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new ListingAdapter(getActivity(), mProductList, dualPane); // initial fragment in second pane - if(dualPane && mProductList != null && mProductList.size() > 0) - { + if (dualPane && mProductList != null && mProductList.size() > 0) { mDualPaneShowListener.onDualPaneShow(SimpleFragment.class, 0); init = true; } - } - else - { + } else { // refill adapter mAdapter.refill(getActivity(), mProductList, dualPane); } @@ -106,14 +88,12 @@ private void setupView() listView.setEmptyView(emptyView); // set first item checked - if(init) listView.setItemChecked(0, true); + if (init) listView.setItemChecked(0, true); // listview item onclick - listView.setOnItemClickListener(new OnItemClickListener() - { + listView.setOnItemClickListener(new OnItemClickListener() { @Override - public void onItemClick(AdapterView parent, View view, int position, long id) - { + public void onItemClick(AdapterView parent, View view, int position, long id) { // list position int listPosition = getListPosition(position); diff --git a/Src-Dual-Pane/java/fragment/SimpleFragment.java b/Src-Dual-Pane/java/fragment/SimpleFragment.java index 60fe7ed..60ceaac 100644 --- a/Src-Dual-Pane/java/fragment/SimpleFragment.java +++ b/Src-Dual-Pane/java/fragment/SimpleFragment.java @@ -10,17 +10,13 @@ import com.example.R; import com.example.activity.SimpleActivity; - -public class SimpleFragment extends Fragment -{ +public class SimpleFragment extends Fragment { private static final String ARGUMENT_PRODUCT_ID = "product_id"; private View mRootView; private int mId = -1; - - public static SimpleFragment newInstance(int productId) - { + public static SimpleFragment newInstance(int productId) { SimpleFragment fragment = new SimpleFragment(); // arguments @@ -31,64 +27,48 @@ public static SimpleFragment newInstance(int productId) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } // handle intent extras Bundle extras = getActivity().getIntent().getExtras(); - if(extras != null) - { + if (extras != null) { handleExtras(extras); } } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_simple, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupView(); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_PRODUCT_ID)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_PRODUCT_ID)) { mId = arguments.getInt(ARGUMENT_PRODUCT_ID); } } - - private void handleExtras(Bundle extras) - { - if(extras.containsKey(SimpleActivity.EXTRA_PRODUCT_ID)) - { + private void handleExtras(Bundle extras) { + if (extras.containsKey(SimpleActivity.EXTRA_PRODUCT_ID)) { mId = extras.getInt(SimpleActivity.EXTRA_PRODUCT_ID); } } - - private void setupView() - { + private void setupView() { // reference TextView nameTextView = mRootView.findViewById(R.id.simple_name); diff --git a/Src-Dual-Pane/java/listener/OnDualPaneShowListener.java b/Src-Dual-Pane/java/listener/OnDualPaneShowListener.java index 7097224..d03b5d9 100644 --- a/Src-Dual-Pane/java/listener/OnDualPaneShowListener.java +++ b/Src-Dual-Pane/java/listener/OnDualPaneShowListener.java @@ -1,7 +1,5 @@ package com.example.listener; - -public interface OnDualPaneShowListener -{ +public interface OnDualPaneShowListener { void onDualPaneShow(Class targetFragment, int index); } diff --git a/Src-Enum/java/entity/IntegerEnum.java b/Src-Enum/java/entity/IntegerEnum.java index 0fefebd..5bcde56 100644 --- a/Src-Enum/java/entity/IntegerEnum.java +++ b/Src-Enum/java/entity/IntegerEnum.java @@ -1,28 +1,20 @@ package com.example.entity; - -public enum IntegerEnum -{ +public enum IntegerEnum { UNDEFINED(0), GRAY_SCALE(1), RGB(2), CMYK(3); private final int mValue; - - private IntegerEnum(int value) - { + private IntegerEnum(int value) { mValue = value; } - - public static IntegerEnum valueToIntegerEnum(int value) - { + public static IntegerEnum valueToIntegerEnum(int value) { IntegerEnum[] values = IntegerEnum.values(); return values[value]; } - - public int getValue() - { + public int getValue() { return mValue; } } diff --git a/Src-Enum/java/entity/StringEnum.java b/Src-Enum/java/entity/StringEnum.java index d690650..02b445e 100644 --- a/Src-Enum/java/entity/StringEnum.java +++ b/Src-Enum/java/entity/StringEnum.java @@ -1,22 +1,16 @@ package com.example.entity; - -public enum StringEnum -{ +public enum StringEnum { GET("GET"), POST("POST"), OPTIONS("OPTIONS"), HEAD("HEAD"), PUT("PUT"), DELETE("DELETE"), TRACE("TRACE"); private final String mValue; - - private StringEnum(String value) - { + private StringEnum(String value) { mValue = value; } - @Override - public String toString() - { + public String toString() { return mValue; } } diff --git a/Src-File-Content-Observer/java/service/ExampleContentObserverService.java b/Src-File-Content-Observer/java/service/ExampleContentObserverService.java index 05d119a..d84b81a 100644 --- a/Src-File-Content-Observer/java/service/ExampleContentObserverService.java +++ b/Src-File-Content-Observer/java/service/ExampleContentObserverService.java @@ -9,18 +9,13 @@ import org.alfonz.utility.Logcat; - -public class ExampleContentObserverService extends Service -{ +public class ExampleContentObserverService extends Service { private ExampleContentObserver mExampleContentObserver; - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { + public int onStartCommand(Intent intent, int flags, int startId) { // start content observer - if(mExampleContentObserver == null) - { + if (mExampleContentObserver == null) { Logcat.d("start content observer"); mExampleContentObserver = new ExampleContentObserver(new Handler()); @@ -28,29 +23,22 @@ public int onStartCommand(Intent intent, int flags, int startId) android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, mExampleContentObserver); - } - else - { + } else { Logcat.d("content observer already running"); } return START_STICKY; } - @Override - public IBinder onBind(Intent intent) - { + public IBinder onBind(Intent intent) { return null; } - @Override - public void onDestroy() - { + public void onDestroy() { // stop content observer - if(mExampleContentObserver != null) - { + if (mExampleContentObserver != null) { getContentResolver().unregisterContentObserver(mExampleContentObserver); mExampleContentObserver = null; } diff --git a/Src-File-Content-Observer/java/service/ExampleFileObserverService.java b/Src-File-Content-Observer/java/service/ExampleFileObserverService.java index 056ffb2..4d234b8 100644 --- a/Src-File-Content-Observer/java/service/ExampleFileObserverService.java +++ b/Src-File-Content-Observer/java/service/ExampleFileObserverService.java @@ -13,60 +13,44 @@ import java.util.ArrayList; import java.util.List; - -public class ExampleFileObserverService extends Service -{ +public class ExampleFileObserverService extends Service { private List mExampleFileObserverList; - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { + public int onStartCommand(Intent intent, int flags, int startId) { // start file observers - if(mExampleFileObserverList == null) - { + if (mExampleFileObserverList == null) { Logcat.d("start file observers"); startFileObservers(); - } - else - { + } else { Logcat.d("file observers already running"); } return START_STICKY; } - @Override - public IBinder onBind(Intent intent) - { + public IBinder onBind(Intent intent) { return null; } - @Override - public void onDestroy() - { + public void onDestroy() { // stop file observers - if(mExampleFileObserverList != null) stopFileObservers(); + if (mExampleFileObserverList != null) stopFileObservers(); } - - private void startFileObservers() - { - if(StorageUtility.isAvailable()) - { + private void startFileObservers() { + if (StorageUtility.isAvailable()) { // create list mExampleFileObserverList = new ArrayList<>(); // watch directories List directoryList = getObservedDirectories(); - for(int i = 0; i < directoryList.size(); i++) - { + for (int i = 0; i < directoryList.size(); i++) { File directory = directoryList.get(i); - if(directory.exists() && directory.isDirectory()) - { + if (directory.exists() && directory.isDirectory()) { ExampleFileObserver observer = new ExampleFileObserver(directory.getAbsolutePath()); observer.startWatching(); mExampleFileObserverList.add(observer); @@ -75,14 +59,10 @@ private void startFileObservers() } } - - private void stopFileObservers() - { - for(int i = 0; i < mExampleFileObserverList.size(); i++) - { + private void stopFileObservers() { + for (int i = 0; i < mExampleFileObserverList.size(); i++) { ExampleFileObserver observer = mExampleFileObserverList.get(i); - if(observer != null) - { + if (observer != null) { observer.stopWatching(); observer = null; } diff --git a/Src-File-Content-Observer/java/utility/ExampleContentObserver.java b/Src-File-Content-Observer/java/utility/ExampleContentObserver.java index ebc9a9a..f57ff8d 100644 --- a/Src-File-Content-Observer/java/utility/ExampleContentObserver.java +++ b/Src-File-Content-Observer/java/utility/ExampleContentObserver.java @@ -4,25 +4,18 @@ import android.net.Uri; import android.os.Handler; - -public class ExampleContentObserver extends ContentObserver -{ - public ExampleContentObserver(Handler handler) - { +public class ExampleContentObserver extends ContentObserver { + public ExampleContentObserver(Handler handler) { super(handler); } - @Override - public void onChange(boolean selfChange) - { + public void onChange(boolean selfChange) { this.onChange(selfChange, null); } - @Override - public void onChange(boolean selfChange, Uri uri) - { + public void onChange(boolean selfChange, Uri uri) { Logcat.d("" + uri); } } diff --git a/Src-File-Content-Observer/java/utility/ExampleFileObserver.java b/Src-File-Content-Observer/java/utility/ExampleFileObserver.java index fa57975..d5a8264 100644 --- a/Src-File-Content-Observer/java/utility/ExampleFileObserver.java +++ b/Src-File-Content-Observer/java/utility/ExampleFileObserver.java @@ -2,9 +2,7 @@ import android.os.FileObserver; - -public class ExampleFileObserver extends FileObserver -{ +public class ExampleFileObserver extends FileObserver { private static final int MASK = (FileObserver.CREATE | FileObserver.MODIFY | FileObserver.CLOSE_WRITE | @@ -16,92 +14,76 @@ public class ExampleFileObserver extends FileObserver public String mAbsolutePath; - - public ExampleFileObserver(String absolutePath) - { + public ExampleFileObserver(String absolutePath) { super(absolutePath, MASK); // or use FileObserver.ALL_EVENTS mAbsolutePath = absolutePath; Logcat.d(absolutePath); } - @Override - public void onEvent(int event, String path) - { - if(path == null) return; + public void onEvent(int event, String path) { + if (path == null) return; // a new file or subdirectory was created under the monitored directory - if((FileObserver.CREATE & event) != 0) - { + if ((FileObserver.CREATE & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is created"); } // a file or directory was opened - if((FileObserver.OPEN & event) != 0) - { + if ((FileObserver.OPEN & event) != 0) { Logcat.d(path + " is opened"); } // data was read from a file - if((FileObserver.ACCESS & event) != 0) - { + if ((FileObserver.ACCESS & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is accessed/read"); } // data was written to a file - if((FileObserver.MODIFY & event) != 0) - { + if ((FileObserver.MODIFY & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is modified"); } // someone has a file or directory open read-only, and closed it - if((FileObserver.CLOSE_NOWRITE & event) != 0) - { + if ((FileObserver.CLOSE_NOWRITE & event) != 0) { Logcat.d(path + " is closed"); } // someone has a file or directory open for writing, and closed it - if((FileObserver.CLOSE_WRITE & event) != 0) - { + if ((FileObserver.CLOSE_WRITE & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is written and closed"); } // a file was deleted from the monitored directory - if((FileObserver.DELETE & event) != 0) - { + if ((FileObserver.DELETE & event) != 0) { // for testing copy file // FileUtils.copyFile(mAbsolutePath + "/" + path); Logcat.d(mAbsolutePath + "/" + path + " is deleted"); } // the monitored file or directory was deleted, monitoring effectively stops - if((FileObserver.DELETE_SELF & event) != 0) - { + if ((FileObserver.DELETE_SELF & event) != 0) { Logcat.d(mAbsolutePath + "/" + " is deleted"); } // a file or subdirectory was moved from the monitored directory - if((FileObserver.MOVED_FROM & event) != 0) - { + if ((FileObserver.MOVED_FROM & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is moved to somewhere " + ""); } // a file or subdirectory was moved to the monitored directory - if((FileObserver.MOVED_TO & event) != 0) - { + if ((FileObserver.MOVED_TO & event) != 0) { Logcat.d("file is moved to " + mAbsolutePath + "/" + path); } // the monitored file or directory was moved; monitoring continues - if((FileObserver.MOVE_SELF & event) != 0) - { + if ((FileObserver.MOVE_SELF & event) != 0) { Logcat.d(path + " is moved"); } // metadata (permissions, owner, timestamp) was changed explicitly - if((FileObserver.ATTRIB & event) != 0) - { + if ((FileObserver.ATTRIB & event) != 0) { Logcat.d(mAbsolutePath + "/" + path + " is changed (permissions, owner, timestamp)"); } } diff --git a/Src-Fullscreen/java/activity/ExampleActivity.java b/Src-Fullscreen/java/activity/ExampleActivity.java index 3b7637f..9edab95 100644 --- a/Src-Fullscreen/java/activity/ExampleActivity.java +++ b/Src-Fullscreen/java/activity/ExampleActivity.java @@ -9,25 +9,19 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupFullscreen(); } - - private void setupFullscreen() - { + private void setupFullscreen() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | diff --git a/Src-Glide/java/utility/BindingUtility.java b/Src-Glide/java/utility/BindingUtility.java index 5aac535..6977e52 100644 --- a/Src-Glide/java/utility/BindingUtility.java +++ b/Src-Glide/java/utility/BindingUtility.java @@ -11,15 +11,11 @@ import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.example.R; - -public final class BindingUtility -{ +public final class BindingUtility { private BindingUtility() {} - @BindingAdapter({"imageUrl"}) - public static void setImageUrl(ImageView imageView, String url) - { + public static void setImageUrl(ImageView imageView, String url) { Glide .with(imageView.getContext()) .load(url) @@ -29,19 +25,14 @@ public static void setImageUrl(ImageView imageView, String url) .into(imageView); } - @BindingAdapter(value = {"imageUrl", "imageCircular", "imagePlaceholder", "imageError"}, requireAll = false) - public static void setImageUrl(ImageView imageView, String url, boolean circular, Drawable placeholder, Drawable error) - { + public static void setImageUrl(ImageView imageView, String url, boolean circular, Drawable placeholder, Drawable error) { RequestManager requestManager = Glide.with(imageView.getContext()); - if(!circular) - { + if (!circular) { DrawableTypeRequest builder = requestManager.load(url); GlideUtility.setupRequestBuilder(builder, placeholder, error); builder.into(imageView); - } - else - { + } else { BitmapTypeRequest builder = requestManager.load(url).asBitmap(); GlideUtility.setupRequestBuilder(builder, placeholder, error); builder.into(GlideUtility.createCircularTarget(imageView)); diff --git a/Src-Glide/java/utility/GlideUtility.java b/Src-Glide/java/utility/GlideUtility.java index 303cc55..b956f51 100644 --- a/Src-Glide/java/utility/GlideUtility.java +++ b/Src-Glide/java/utility/GlideUtility.java @@ -16,72 +16,52 @@ import org.alfonz.graphics.drawable.CircularDrawable; import org.alfonz.utility.Logcat; - -public final class GlideUtility -{ +public final class GlideUtility { private GlideUtility() {} - - public static void setupRequestBuilder(GenericRequestBuilder builder, Drawable placeholder, Drawable error) - { + public static void setupRequestBuilder(GenericRequestBuilder builder, Drawable placeholder, Drawable error) { builder.diskCacheStrategy(DiskCacheStrategy.RESULT); - if(builder instanceof DrawableRequestBuilder) - { + if (builder instanceof DrawableRequestBuilder) { ((DrawableRequestBuilder) builder).crossFade(); } - if(ExampleConfig.LOGS) - { + if (ExampleConfig.LOGS) { builder.listener(createLogRequestListener()); } - if(placeholder != null) - { + if (placeholder != null) { builder.placeholder(placeholder); } - if(error != null) - { + if (error != null) { builder.error(error); - } - else - { + } else { builder.error(R.drawable.placeholder); } } - - public static Target createCircularTarget(final ImageView imageView) - { - return new BitmapImageViewTarget(imageView) - { + public static Target createCircularTarget(final ImageView imageView) { + return new BitmapImageViewTarget(imageView) { @Override - protected void setResource(Bitmap resource) - { + protected void setResource(Bitmap resource) { CircularDrawable drawable = new CircularDrawable(resource); imageView.setImageDrawable(drawable); } }; } - - private static RequestListener createLogRequestListener() - { - return new RequestListener() - { + private static RequestListener createLogRequestListener() { + return new RequestListener() { @Override - public boolean onException(Exception exception, String model, Target target, boolean isFirstResource) - { + public boolean onException(Exception exception, String model, Target target, boolean isFirstResource) { Logcat.d("%s / %s / isFirstResource=%s", exception, model, isFirstResource); exception.printStackTrace(); return false; } - @Override - public boolean onResourceReady(Object resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) - { + public boolean onResourceReady(Object resource, String model, Target target, boolean isFromMemoryCache, boolean isFirstResource) { Logcat.d("%s / isFromMemoryCache=%s / isFirstResource=%s", model, isFromMemoryCache, isFirstResource); return false; } diff --git a/Src-Glide/res/layout/fragment_example.xml b/Src-Glide/res/layout/fragment_example.xml index 836b382..2fa362e 100644 --- a/Src-Glide/res/layout/fragment_example.xml +++ b/Src-Glide/res/layout/fragment_example.xml @@ -5,9 +5,11 @@ + name="view" + type="com.example.ui.ExampleView" /> + name="data" + type="com.example.viewmodel.ExampleViewModel" /> -{ +public class ExampleViewModel extends BaseViewModel { private static final String LOCATION_SETTINGS_CALL_TYPE = "location_settings"; private static final String LAST_LOCATION_CALL_TYPE = "last_location"; private static final String SINGLE_LOCATION_CALL_TYPE = "single_location"; @@ -40,88 +38,66 @@ public class ExampleViewModel extends BaseViewModel private Disposable mSingleLocationDisposable; private Disposable mSingleAddressDisposable; - @Override - public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) - { + public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) { super.onCreate(arguments, savedInstanceState); mRxLocation.setDefaultTimeout(30, TimeUnit.SECONDS); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); runContinuousLocationCall(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); mRxManager.disposeAll(); } - - private LocationRequest createSingleLocationRequest() - { + private LocationRequest createSingleLocationRequest() { return LocationRequest.create() .setNumUpdates(1) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } - - private LocationRequest createContinuousLocationRequest() - { + private LocationRequest createContinuousLocationRequest() { return LocationRequest.create() .setInterval(10000) .setFastestInterval(5000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } - - private void runLocationSettingsCall() - { - if(!mRxManager.isRunning(LOCATION_SETTINGS_CALL_TYPE)) - { + private void runLocationSettingsCall() { + if (!mRxManager.isRunning(LOCATION_SETTINGS_CALL_TYPE)) { Single rawSingle = mRxLocation.settings().checkAndHandleResolution(createSingleLocationRequest()); Single single = mRxManager.setupSingleWithSchedulers(rawSingle, LOCATION_SETTINGS_CALL_TYPE); single.subscribeWith(createLocationSettingsSingleObserver()); } } - @SuppressWarnings("MissingPermission") - private void runLastLocationCall() - { - if(!mRxManager.isRunning(LAST_LOCATION_CALL_TYPE)) - { + private void runLastLocationCall() { + if (!mRxManager.isRunning(LAST_LOCATION_CALL_TYPE)) { Maybe rawMaybe = mRxLocation.location().lastLocation(); Maybe maybe = mRxManager.setupMaybeWithSchedulers(rawMaybe, LAST_LOCATION_CALL_TYPE); maybe.subscribeWith(createLastLocationMaybeObserver()); } } - @SuppressWarnings("MissingPermission") - private void runSingleLocationCall() - { - if(!mRxManager.isRunning(SINGLE_LOCATION_CALL_TYPE)) - { + private void runSingleLocationCall() { + if (!mRxManager.isRunning(SINGLE_LOCATION_CALL_TYPE)) { Observable rawObservable = mRxLocation.location().updates(createSingleLocationRequest()); Observable observable = mRxManager.setupObservableWithSchedulers(rawObservable, SINGLE_LOCATION_CALL_TYPE); mSingleLocationDisposable = observable.subscribeWith(createSingleLocationObserver()); } } - @SuppressWarnings("MissingPermission") - private void runSingleAddressCall() - { - if(!mRxManager.isRunning(SINGLE_ADDRESS_CALL_TYPE)) - { + private void runSingleAddressCall() { + if (!mRxManager.isRunning(SINGLE_ADDRESS_CALL_TYPE)) { Observable

rawObservable = mRxLocation.location() .updates(createSingleLocationRequest()) .flatMap(location -> mRxLocation.geocoding().fromLocation(location).toObservable()); @@ -130,24 +106,18 @@ private void runSingleAddressCall() } } - @SuppressWarnings("MissingPermission") - private void runContinuousLocationCall() - { - if(!mRxManager.isRunning(CONTINUOUS_LOCATION_CALL_TYPE)) - { + private void runContinuousLocationCall() { + if (!mRxManager.isRunning(CONTINUOUS_LOCATION_CALL_TYPE)) { Observable rawObservable = mRxLocation.location().updates(createContinuousLocationRequest()); Observable observable = mRxManager.setupObservableWithSchedulers(rawObservable, CONTINUOUS_LOCATION_CALL_TYPE); observable.subscribeWith(createContinuousLocationObserver()); } } - @SuppressWarnings("MissingPermission") - private void runContinuousAddressCall() - { - if(!mRxManager.isRunning(CONTINUOUS_ADDRESS_CALL_TYPE)) - { + private void runContinuousAddressCall() { + if (!mRxManager.isRunning(CONTINUOUS_ADDRESS_CALL_TYPE)) { Observable
rawObservable = mRxLocation.location() .updates(createContinuousLocationRequest()) .flatMap(location -> mRxLocation.geocoding().fromLocation(location).toObservable()); @@ -156,9 +126,7 @@ private void runContinuousAddressCall() } } - - private DisposableSingleObserver createLocationSettingsSingleObserver() - { + private DisposableSingleObserver createLocationSettingsSingleObserver() { return AlfonzDisposableSingleObserver.newInstance( data -> { @@ -171,9 +139,7 @@ private DisposableSingleObserver createLocationSettingsSingleObserver() ); } - - private DisposableMaybeObserver createLastLocationMaybeObserver() - { + private DisposableMaybeObserver createLastLocationMaybeObserver() { return AlfonzDisposableMaybeObserver.newInstance( data -> { @@ -190,9 +156,7 @@ private DisposableMaybeObserver createLastLocationMaybeObserver() ); } - - private DisposableObserver createSingleLocationObserver() - { + private DisposableObserver createSingleLocationObserver() { return AlfonzDisposableObserver.newInstance( data -> { @@ -210,9 +174,7 @@ private DisposableObserver createSingleLocationObserver() ); } - - private DisposableObserver
createSingleAddressObserver() - { + private DisposableObserver
createSingleAddressObserver() { return AlfonzDisposableObserver.newInstance( data -> { @@ -230,9 +192,7 @@ private DisposableObserver
createSingleAddressObserver() ); } - - private DisposableObserver createContinuousLocationObserver() - { + private DisposableObserver createContinuousLocationObserver() { return AlfonzDisposableObserver.newInstance( data -> { @@ -249,9 +209,7 @@ private DisposableObserver createContinuousLocationObserver() ); } - - private DisposableObserver
createContinuousAddressObserver() - { + private DisposableObserver
createContinuousAddressObserver() { return AlfonzDisposableObserver.newInstance( data -> { diff --git a/Src-LocationUtility/java/utility/LocationUtility.java b/Src-LocationUtility/java/utility/LocationUtility.java index 2d7a9ea..3c14860 100644 --- a/Src-LocationUtility/java/utility/LocationUtility.java +++ b/Src-LocationUtility/java/utility/LocationUtility.java @@ -10,14 +10,10 @@ import java.util.List; import java.util.Locale; - -public final class LocationUtility -{ +public final class LocationUtility { private LocationUtility() {} - - public static int getDistance(LatLng l1, LatLng l2) - { + public static int getDistance(LatLng l1, LatLng l2) { Location location1 = new Location(LocationManager.PASSIVE_PROVIDER); location1.setLatitude(l1.latitude); location1.setLongitude(l1.longitude); @@ -29,40 +25,25 @@ public static int getDistance(LatLng l1, LatLng l2) return (int) location1.distanceTo(location2); } - - public static String getDistanceString(double distance, boolean useMetricSystem) - { + public static String getDistanceString(double distance, boolean useMetricSystem) { String result; - if(useMetricSystem) - { - if(distance < 1000.0) - { + if (useMetricSystem) { + if (distance < 1000.0) { result = String.format(Locale.US, "%d " + ExampleApplication.getContext().getString(R.string.unit_meter), (int) distance); - } - else if(distance < 5000.0) - { + } else if (distance < 5000.0) { result = String.format(Locale.US, "%.1f " + ExampleApplication.getContext().getString(R.string.unit_kilometer), distance / 1000); - } - else - { + } else { result = String.format(Locale.US, "%d " + ExampleApplication.getContext().getString(R.string.unit_kilometer), (int) distance / 1000); } - } - else - { + } else { double distanceMiles = distance * 0.000621371192; // distance in miles - if(distanceMiles < 0.1) - { + if (distanceMiles < 0.1) { result = String.format(Locale.US, "%.2f " + ExampleApplication.getContext().getString(R.string.unit_mile), distanceMiles); - } - else if(distanceMiles < 10.0) - { + } else if (distanceMiles < 10.0) { result = String.format(Locale.US, "%.1f " + ExampleApplication.getContext().getString(R.string.unit_mile), distanceMiles); - } - else - { + } else { result = String.format(Locale.US, "%d " + ExampleApplication.getContext().getString(R.string.unit_mile), (int) distanceMiles); } } @@ -70,70 +51,56 @@ else if(distanceMiles < 10.0) return result; } - - public static String getDistanceString(int distance, boolean useMetricSystem) - { + public static String getDistanceString(int distance, boolean useMetricSystem) { return getDistanceString((double) distance, useMetricSystem); } - - public static boolean isMetricSystem() - { + public static boolean isMetricSystem() { Locale locale = Locale.getDefault(); String countryCode = locale.getCountry(); return (!"US".equals(countryCode) && !"LR".equals(countryCode) && !"MM".equals(countryCode)); } - - public static int getZoom(int distance) - { - if(distance < 50) return 18; - else if(distance < 100) return 17; - else if(distance < 500) return 16; - else if(distance < 1000) return 15; - else if(distance < 2000) return 14; - else if(distance < 5000) return 13; - else if(distance < 10000) return 12; - else if(distance < 50000) return 11; + public static int getZoom(int distance) { + if (distance < 50) return 18; + else if (distance < 100) return 17; + else if (distance < 500) return 16; + else if (distance < 1000) return 15; + else if (distance < 2000) return 14; + else if (distance < 5000) return 13; + else if (distance < 10000) return 12; + else if (distance < 50000) return 11; else return 10; } - - public static boolean isPointInPolygon(LatLng location, List vertices) - { - if(location == null) return false; + public static boolean isPointInPolygon(LatLng location, List vertices) { + if (location == null) return false; LatLng lastPoint = vertices.get(vertices.size() - 1); boolean isInside = false; double x = location.longitude; - for(LatLng point : vertices) - { + for (LatLng point : vertices) { double x1 = lastPoint.longitude; double x2 = point.longitude; double dx = x2 - x1; - if(Math.abs(dx) > 180.0) - { - if(x > 0) - { - while(x1 < 0) x1 += 360; - while(x2 < 0) x2 += 360; - } - else - { - while(x1 > 0) x1 -= 360; - while(x2 > 0) x2 -= 360; + if (Math.abs(dx) > 180.0) { + if (x > 0) { + while (x1 < 0) x1 += 360; + while (x2 < 0) x2 += 360; + } else { + while (x1 > 0) x1 -= 360; + while (x2 > 0) x2 -= 360; } dx = x2 - x1; } - if((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) - { + if ((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) { double grad = (point.latitude - lastPoint.latitude) / dx; double intersectAtLat = lastPoint.latitude + ((x - x1) * grad); - if(intersectAtLat > location.latitude) isInside = !isInside; + if (intersectAtLat > location.latitude) isInside = !isInside; } lastPoint = point; diff --git a/Src-MVC-Activity/java/activity/ExampleActivity.java b/Src-MVC-Activity/java/activity/ExampleActivity.java index 4131aa8..c1398c7 100644 --- a/Src-MVC-Activity/java/activity/ExampleActivity.java +++ b/Src-MVC-Activity/java/activity/ExampleActivity.java @@ -12,77 +12,57 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity -{ - public static Intent newIntent(Context context) - { +public class ExampleActivity extends AppCompatActivity { + public static Intent newIntent(Context context) { Intent intent = new Intent(context, ExampleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupActionBar(); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); } - @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { // action bar menu MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.activity_example, menu); return super.onCreateOptionsMenu(menu); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case android.R.id.home: // TODO Intent intent = ExampleActivity.newIntent(this); @@ -98,9 +78,7 @@ public boolean onOptionsItemSelected(MenuItem item) } } - - private void setupActionBar() - { + private void setupActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); diff --git a/Src-MVC-ExpandableListView/java/adapter/ExpandableListingAdapter.java b/Src-MVC-ExpandableListView/java/adapter/ExpandableListingAdapter.java index 225c29e..0e280e4 100644 --- a/Src-MVC-ExpandableListView/java/adapter/ExpandableListingAdapter.java +++ b/Src-MVC-ExpandableListView/java/adapter/ExpandableListingAdapter.java @@ -12,30 +12,23 @@ import java.util.List; - -public class ExpandableListingAdapter extends BaseExpandableListAdapter -{ +public class ExpandableListingAdapter extends BaseExpandableListAdapter { private Context mContext; private List mGroupList; private List> mProductList; private int mSelectedGroupPosition = -1; private int mSelectedChildPosition = -1; - - public ExpandableListingAdapter(Context context, List groupList, List> productList) - { + public ExpandableListingAdapter(Context context, List groupList, List> productList) { mContext = context; mGroupList = groupList; mProductList = productList; } - @Override - public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) - { + public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_expandable_listing_item, parent, false); @@ -47,8 +40,7 @@ public View getChildView(int groupPosition, int childPosition, boolean isLastChi // entity ProductEntity product = (ProductEntity) getChild(groupPosition, childPosition); - if(product != null) - { + if (product != null) { // view holder ViewHolder holder = (ViewHolder) convertView.getTag(); @@ -56,12 +48,9 @@ public View getChildView(int groupPosition, int childPosition, boolean isLastChi holder.nameTextView.setText(product.getName()); // selected item - if(mSelectedGroupPosition == groupPosition && mSelectedChildPosition == childPosition) - { + if (mSelectedGroupPosition == groupPosition && mSelectedChildPosition == childPosition) { convertView.setBackgroundResource(R.color.global_color_control_activated); - } - else - { + } else { convertView.setBackgroundResource(R.drawable.selector_selectable_item_bg); } } @@ -69,36 +58,27 @@ public View getChildView(int groupPosition, int childPosition, boolean isLastChi return convertView; } - @Override - public int getChildrenCount(int groupPosition) - { - if(mProductList != null) return mProductList.get(groupPosition).size(); + public int getChildrenCount(int groupPosition) { + if (mProductList != null) return mProductList.get(groupPosition).size(); else return 0; } - @Override - public Object getChild(int groupPosition, int childPosition) - { - if(mProductList != null) return mProductList.get(groupPosition).get(childPosition); + public Object getChild(int groupPosition, int childPosition) { + if (mProductList != null) return mProductList.get(groupPosition).get(childPosition); else return null; } - @Override - public long getChildId(int groupPosition, int childPosition) - { + public long getChildId(int groupPosition, int childPosition) { return childPosition; } - @Override - public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) - { + public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_expandable_listing_group, parent, false); @@ -110,8 +90,7 @@ public View getGroupView(int groupPosition, boolean isExpanded, View convertView // entity String group = (String) getGroup(groupPosition); - if(group != null) - { + if (group != null) { // view holder ViewHolderGroup holder = (ViewHolderGroup) convertView.getTag(); @@ -122,87 +101,63 @@ public View getGroupView(int groupPosition, boolean isExpanded, View convertView return convertView; } - @Override - public int getGroupCount() - { - if(mGroupList != null) return mGroupList.size(); + public int getGroupCount() { + if (mGroupList != null) return mGroupList.size(); else return 0; } - @Override - public Object getGroup(int groupPosition) - { - if(mGroupList != null) return mGroupList.get(groupPosition); + public Object getGroup(int groupPosition) { + if (mGroupList != null) return mGroupList.get(groupPosition); else return null; } - @Override - public long getGroupId(int groupPosition) - { + public long getGroupId(int groupPosition) { return groupPosition; } - @Override - public boolean hasStableIds() - { + public boolean hasStableIds() { return true; } - @Override - public boolean isChildSelectable(int groupPosition, int childPosition) - { + public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } - - public void refill(Context context, List groupList, List> productList) - { + public void refill(Context context, List groupList, List> productList) { mContext = context; mGroupList = groupList; mProductList = productList; notifyDataSetChanged(); } - - public void stop() - { + public void stop() { // TODO: stop image loader } - - public void setSelectedPosition(int groupPosition, int childPosition) - { + public void setSelectedPosition(int groupPosition, int childPosition) { mSelectedGroupPosition = groupPosition; mSelectedChildPosition = childPosition; notifyDataSetChanged(); } - - public int getSelectedGroupPosition() - { + public int getSelectedGroupPosition() { return mSelectedGroupPosition; } - - public int getSelectedChildPosition() - { + public int getSelectedChildPosition() { return mSelectedChildPosition; } - - static class ViewHolder - { + static class ViewHolder { TextView nameTextView; } - - static class ViewHolderGroup - { + static class ViewHolderGroup { TextView nameTextView; } } diff --git a/Src-MVC-ExpandableListView/java/fragment/ExpandableListingFragment.java b/Src-MVC-ExpandableListView/java/fragment/ExpandableListingFragment.java index 81fa017..fdcb6bc 100644 --- a/Src-MVC-ExpandableListView/java/fragment/ExpandableListingFragment.java +++ b/Src-MVC-ExpandableListView/java/fragment/ExpandableListingFragment.java @@ -23,9 +23,7 @@ import java.util.ArrayList; import java.util.List; - -public class ExpandableListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener -{ +public class ExpandableListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener { private View mRootView; private StatefulLayout mStatefulLayout; private ExpandableListingAdapter mAdapter; @@ -33,150 +31,115 @@ public class ExpandableListingFragment extends TaskFragment implements LoadDataT private List mGroupList = new ArrayList<>(); private List> mProductList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_expandable_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mGroupList == null || mGroupList.isEmpty() || mProductList == null || mProductList.isEmpty()) - { + if (mGroupList == null || mGroupList.isEmpty() || mProductList == null || mProductList.isEmpty()) { loadData(); } } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data - for(int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { List group = new ArrayList<>(); - for(int j = 0; j < 10; j++) - { + for (int j = 0; j < 10; j++) { ProductEntity p = new ProductEntity(); p.setName("Product " + i + "/" + j); group.add(p); @@ -191,34 +154,26 @@ public void run() }); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void setupView() - { + private void setupView() { // reference ExpandableListView listView = mRootView.findViewById(android.R.id.list); ViewGroup emptyView = mRootView.findViewById(android.R.id.empty); // listview content - if(mAdapter == null) - { + if (mAdapter == null) { // adapter mAdapter = new ExpandableListingAdapter(getActivity(), mGroupList, mProductList); @@ -227,9 +182,7 @@ private void setupView() // expand first group listView.expandGroup(0); - } - else - { + } else { // refill adapter mAdapter.refill(getActivity(), mGroupList, mProductList); @@ -238,13 +191,11 @@ private void setupView() } // listview item onclick - listView.setOnChildClickListener(new OnChildClickListener() - { + listView.setOnChildClickListener(new OnChildClickListener() { @Override - public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) - { + public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) { // listview item onclick - if(mAdapter != null) mAdapter.setSelectedPosition(groupPosition, childPosition); + if (mAdapter != null) mAdapter.setSelectedPosition(groupPosition, childPosition); // TODO @@ -256,30 +207,22 @@ public boolean onChildClick(ExpandableListView parent, View view, int groupPosit listView.setEmptyView(emptyView); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { + if (state == StatefulLayout.CONTENT) { ExpandableListView listView = mRootView.findViewById(android.R.id.list); - if(listView.getAdapter() != null) - { + if (listView.getAdapter() != null) { mAdapter.notifyDataSetChanged(); - } - else - { - if(mGroupList != null && mProductList != null) setupView(); + } else { + if (mGroupList != null && mProductList != null) setupView(); } } } @@ -289,26 +232,20 @@ public void onStateChange(View view, @StatefulLayout.State int state) mStatefulLayout.restoreInstanceState(savedInstanceState); } - - private void expand() - { - if(mAdapter != null && mRootView != null) - { + private void expand() { + if (mAdapter != null && mRootView != null) { ExpandableListView listView = mRootView.findViewById(android.R.id.list); int count = mAdapter.getGroupCount(); - for(int i = 0; i < count; i++) listView.expandGroup(i); + for (int i = 0; i < count; i++) listView.expandGroup(i); mRootView.invalidate(); } } - - private void collapse() - { - if(mAdapter != null && mRootView != null) - { + private void collapse() { + if (mAdapter != null && mRootView != null) { ExpandableListView listView = mRootView.findViewById(android.R.id.list); int count = mAdapter.getGroupCount(); - for(int i = 0; i < count; i++) listView.collapseGroup(i); + for (int i = 0; i < count; i++) listView.collapseGroup(i); mRootView.invalidate(); } } diff --git a/Src-MVC-Fragment/java/entity/ProductEntity.java b/Src-MVC-Fragment/java/entity/ProductEntity.java index 679b21c..7a3452a 100644 --- a/Src-MVC-Fragment/java/entity/ProductEntity.java +++ b/Src-MVC-Fragment/java/entity/ProductEntity.java @@ -1,46 +1,32 @@ package com.example.entity; - -public class ProductEntity -{ +public class ProductEntity { private long id; private String name; - // empty constructor - public ProductEntity() - { + public ProductEntity() { } - // copy constructor - public ProductEntity(ProductEntity origin) - { + public ProductEntity(ProductEntity origin) { id = origin.id; - if(origin.name != null) name = new String(origin.name); + if (origin.name != null) name = new String(origin.name); } - - public long getId() - { + public long getId() { return id; } - - public void setId(long id) - { + public void setId(long id) { this.id = id; } - - public String getName() - { + public String getName() { return name; } - - public void setName(String name) - { + public void setName(String name) { this.name = name; } } diff --git a/Src-MVC-Fragment/java/fragment/SimpleFragment.java b/Src-MVC-Fragment/java/fragment/SimpleFragment.java index 2938857..70b6e10 100644 --- a/Src-MVC-Fragment/java/fragment/SimpleFragment.java +++ b/Src-MVC-Fragment/java/fragment/SimpleFragment.java @@ -18,178 +18,137 @@ import org.alfonz.utility.NetworkUtility; import org.alfonz.view.StatefulLayout; - -public class SimpleFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener -{ +public class SimpleFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener { private View mRootView; private StatefulLayout mStatefulLayout; private LoadDataTask mLoadDataTask; private ProductEntity mProduct; - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_simple, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProduct == null) loadData(); + if (mProduct == null) loadData(); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data mProduct = new ProductEntity(); mProduct.setName("Test Product"); // show content - if(mProduct != null) mStatefulLayout.showContent(); + if (mProduct != null) mStatefulLayout.showContent(); else mStatefulLayout.showEmpty(); } }); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void setupView() - { + private void setupView() { // reference TextView nameTextView = mRootView.findViewById(R.id.simple_name); @@ -197,23 +156,18 @@ private void setupView() nameTextView.setText(mProduct.getName()); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { - if(mProduct != null) setupView(); + if (state == StatefulLayout.CONTENT) { + if (mProduct != null) setupView(); } } }); diff --git a/Src-MVC-Fragment/java/fragment/TaskFragment.java b/Src-MVC-Fragment/java/fragment/TaskFragment.java index af5efeb..d296dd0 100644 --- a/Src-MVC-Fragment/java/fragment/TaskFragment.java +++ b/Src-MVC-Fragment/java/fragment/TaskFragment.java @@ -7,73 +7,53 @@ import java.util.LinkedList; import java.util.List; - -public class TaskFragment extends Fragment -{ +public class TaskFragment extends Fragment { private final Object mLock = new Object(); private Boolean mReady = false; private List mPendingCallbacks = new LinkedList<>(); - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - synchronized(mLock) - { + synchronized (mLock) { mReady = true; int pendingCallbacks = mPendingCallbacks.size(); - while(pendingCallbacks-- > 0) - { + while (pendingCallbacks-- > 0) { Runnable runnable = mPendingCallbacks.remove(0); runNow(runnable); } } } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); - synchronized(mLock) - { + synchronized (mLock) { mReady = false; } } - - protected void runTaskCallback(Runnable runnable) - { - if(mReady) runNow(runnable); + protected void runTaskCallback(Runnable runnable) { + if (mReady) runNow(runnable); else addPending(runnable); } - - protected void executeTask(AsyncTask task) - { + protected void executeTask(AsyncTask task) { // use AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - - private void runNow(Runnable runnable) - { + private void runNow(Runnable runnable) { getActivity().runOnUiThread(runnable); } - - private void addPending(Runnable runnable) - { - synchronized(mLock) - { + private void addPending(Runnable runnable) { + synchronized (mLock) { mPendingCallbacks.add(runnable); } } diff --git a/Src-MVC-Fragment/java/task/LoadDataTask.java b/Src-MVC-Fragment/java/task/LoadDataTask.java index 34b5c0c..010c22c 100644 --- a/Src-MVC-Fragment/java/task/LoadDataTask.java +++ b/Src-MVC-Fragment/java/task/LoadDataTask.java @@ -4,55 +4,39 @@ import java.lang.ref.WeakReference; - -public class LoadDataTask extends AsyncTask -{ +public class LoadDataTask extends AsyncTask { private WeakReference mOnLoadDataListener; - - public interface OnLoadDataListener - { + public interface OnLoadDataListener { void onLoadData(); } - - public LoadDataTask(OnLoadDataListener onLoadDataListener) - { + public LoadDataTask(OnLoadDataListener onLoadDataListener) { setListener(onLoadDataListener); } - @Override - protected String doInBackground(Void... params) - { - try - { + protected String doInBackground(Void... params) { + try { // TODO: do something Thread.sleep(2000); - } - catch(InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } return null; } - @Override - protected void onPostExecute(String result) - { - if(isCancelled()) return; + protected void onPostExecute(String result) { + if (isCancelled()) return; OnLoadDataListener listener = mOnLoadDataListener.get(); - if(listener != null) - { + if (listener != null) { listener.onLoadData(); } } - - public void setListener(OnLoadDataListener onLoadDataListener) - { + public void setListener(OnLoadDataListener onLoadDataListener) { mOnLoadDataListener = new WeakReference<>(onLoadDataListener); } } diff --git a/Src-MVC-ListView/java/adapter/ListingAdapter.java b/Src-MVC-ListView/java/adapter/ListingAdapter.java index c834961..c9b5cbe 100644 --- a/Src-MVC-ListView/java/adapter/ListingAdapter.java +++ b/Src-MVC-ListView/java/adapter/ListingAdapter.java @@ -12,26 +12,19 @@ import java.util.List; - -public class ListingAdapter extends BaseAdapter -{ +public class ListingAdapter extends BaseAdapter { private Context mContext; private List mProductList; - - public ListingAdapter(Context context, List productList) - { + public ListingAdapter(Context context, List productList) { mContext = context; mProductList = productList; } - @Override - public View getView(final int position, View convertView, ViewGroup parent) - { + public View getView(final int position, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_listing_item, parent, false); @@ -43,8 +36,7 @@ public View getView(final int position, View convertView, ViewGroup parent) // entity ProductEntity product = mProductList.get(position); - if(product != null) - { + if (product != null) { // view holder ViewHolder holder = (ViewHolder) convertView.getTag(); @@ -55,46 +47,34 @@ public View getView(final int position, View convertView, ViewGroup parent) return convertView; } - @Override - public int getCount() - { - if(mProductList != null) return mProductList.size(); + public int getCount() { + if (mProductList != null) return mProductList.size(); else return 0; } - @Override - public Object getItem(int position) - { - if(mProductList != null) return mProductList.get(position); + public Object getItem(int position) { + if (mProductList != null) return mProductList.get(position); else return null; } - @Override - public long getItemId(int position) - { + public long getItemId(int position) { return position; } - - public void refill(Context context, List productList) - { + public void refill(Context context, List productList) { mContext = context; mProductList = productList; notifyDataSetChanged(); } - - public void stop() - { + public void stop() { // TODO: stop image loader } - - static class ViewHolder - { + static class ViewHolder { TextView nameTextView; } } diff --git a/Src-MVC-ListView/java/fragment/ListingFragment.java b/Src-MVC-ListView/java/fragment/ListingFragment.java index 5a67430..e72d433 100644 --- a/Src-MVC-ListView/java/fragment/ListingFragment.java +++ b/Src-MVC-ListView/java/fragment/ListingFragment.java @@ -27,9 +27,7 @@ import java.util.ArrayList; import java.util.List; - -public class ListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener -{ +public class ListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener { private static final int LAZY_LOADING_TAKE = 16; private static final int LAZY_LOADING_OFFSET = 4; @@ -41,148 +39,115 @@ public class ListingFragment extends TaskFragment implements LoadDataTask.OnLoad private LoadDataTask mLoadDataTask; private List mProductList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProductList == null || mProductList.isEmpty()) loadData(); + if (mProductList == null || mProductList.isEmpty()) loadData(); // lazy loading progress - if(mLazyLoading) showLazyLoadingProgress(true); + if (mLazyLoading) showLazyLoadingProgress(true); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data final int size = mProductList.size(); - for(int i = 0; i < LAZY_LOADING_TAKE; i++) - { + for (int i = 0; i < LAZY_LOADING_TAKE; i++) { ProductEntity p = new ProductEntity(); p.setName("Product " + (size + i)); mProductList.add(p); @@ -195,29 +160,21 @@ public void run() }); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void lazyLoadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void lazyLoadData() { + if (NetworkUtility.isOnline(getActivity())) { // show lazy loading progress showLazyLoadingProgress(true); @@ -227,19 +184,14 @@ private void lazyLoadData() } } - - private void showLazyLoadingProgress(boolean visible) - { - if(visible) - { + private void showLazyLoadingProgress(boolean visible) { + if (visible) { mLazyLoading = true; // show footer ListView listView = getListView(); listView.addFooterView(mFooterView); - } - else - { + } else { // hide footer ListView listView = getListView(); listView.removeFooterView(mFooterView); @@ -248,21 +200,16 @@ private void showLazyLoadingProgress(boolean visible) } } - - private void setupView() - { + private void setupView() { // reference ListView listView = getListView(); ViewGroup emptyView = mRootView.findViewById(android.R.id.empty); // listview content - if(listView.getAdapter() == null) - { + if (listView.getAdapter() == null) { // create adapter mAdapter = new ListingAdapter(getActivity(), mProductList); - } - else - { + } else { // refill adapter mAdapter.refill(getActivity(), mProductList); } @@ -289,30 +236,23 @@ private void setupView() listView.setEmptyView(emptyView); // lazy loading - listView.setOnScrollListener(new OnScrollListener() - { + listView.setOnScrollListener(new OnScrollListener() { @Override - public void onScrollStateChanged(AbsListView view, int scrollState) - { + public void onScrollStateChanged(AbsListView view, int scrollState) { } - @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) - { - if(totalItemCount - (firstVisibleItem + visibleItemCount) <= LAZY_LOADING_OFFSET && mProductList.size() % LAZY_LOADING_TAKE == 0 && !mProductList.isEmpty()) - { - if(!mLazyLoading) lazyLoadData(); + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + if (totalItemCount - (firstVisibleItem + visibleItemCount) <= LAZY_LOADING_OFFSET && mProductList.size() % LAZY_LOADING_TAKE == 0 && !mProductList.isEmpty()) { + if (!mLazyLoading) lazyLoadData(); } } }); // listview item onclick - listView.setOnItemClickListener(new OnItemClickListener() - { + listView.setOnItemClickListener(new OnItemClickListener() { @Override - public void onItemClick(AdapterView parent, View view, int position, long id) - { + public void onItemClick(AdapterView parent, View view, int position, long id) { // list position int listPosition = getListPosition(position); @@ -321,11 +261,9 @@ public void onItemClick(AdapterView parent, View view, int position, long id) }); // listview item long onclick - listView.setOnItemLongClickListener(new OnItemLongClickListener() - { + listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) - { + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { // list position int listPosition = getListPosition(position); @@ -336,30 +274,22 @@ public boolean onItemLongClick(AdapterView parent, View view, int position, l }); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { + if (state == StatefulLayout.CONTENT) { ListView listView = getListView(); - if(mLazyLoading && listView.getAdapter() != null) - { + if (mLazyLoading && listView.getAdapter() != null) { mAdapter.notifyDataSetChanged(); - } - else - { - if(mProductList != null) setupView(); + } else { + if (mProductList != null) setupView(); } } } @@ -369,18 +299,14 @@ public void onStateChange(View view, @StatefulLayout.State int state) mStatefulLayout.restoreInstanceState(savedInstanceState); } - - private ListView getListView() - { + private ListView getListView() { return mRootView != null ? mRootView.findViewById(android.R.id.list) : null; } - - private int getListPosition(int globalPosition) - { + private int getListPosition(int globalPosition) { // list position without headers, should be used for getting data entities from collections int listPosition = globalPosition; - if(getListView() != null) listPosition = globalPosition - getListView().getHeaderViewsCount(); + if (getListView() != null) listPosition = globalPosition - getListView().getHeaderViewsCount(); return listPosition; } } diff --git a/Src-MVC-RecyclerView/java/adapter/MultiSelectorRecyclerAdapter.java b/Src-MVC-RecyclerView/java/adapter/MultiSelectorRecyclerAdapter.java index 8764943..c211155 100644 --- a/Src-MVC-RecyclerView/java/adapter/MultiSelectorRecyclerAdapter.java +++ b/Src-MVC-RecyclerView/java/adapter/MultiSelectorRecyclerAdapter.java @@ -11,28 +11,20 @@ import com.example.R; import com.example.entity.ProductEntity; - -public class MultiSelectorRecyclerAdapter extends RecyclerView.Adapter -{ +public class MultiSelectorRecyclerAdapter extends RecyclerView.Adapter { private MultiSelector mMultiSelector = new MultiSelector(); // TODO: use MultiSelector or SingleSelector - - public static final class ProductViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener - { + public static final class ProductViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener { private TextView mNameTextView; private OnItemClickListener mListener; private MultiSelector mMultiSelector; - - public interface OnItemClickListener - { + public interface OnItemClickListener { void onItemClick(View view, int position, long id, int viewType); void onItemLongClick(View view, int position, long id, int viewType); } - - public ProductViewHolder(View itemView, OnItemClickListener listener, MultiSelector multiSelector) - { + public ProductViewHolder(View itemView, OnItemClickListener listener, MultiSelector multiSelector) { super(itemView, multiSelector); mListener = listener; mMultiSelector = multiSelector; @@ -48,43 +40,31 @@ public ProductViewHolder(View itemView, OnItemClickListener listener, MultiSelec mNameTextView = itemView.findViewById(R.id.recycler_item_name); } - @Override - public void onClick(View view) - { - if(!mMultiSelector.tapSelection(this)) - { + public void onClick(View view) { + if (!mMultiSelector.tapSelection(this)) { int position = getAdapterPosition(); - if(position != RecyclerView.NO_POSITION) - { + if (position != RecyclerView.NO_POSITION) { mListener.onItemClick(view, position, getItemId(), getItemViewType()); } } } - @Override - public boolean onLongClick(View view) - { - if(!mMultiSelector.isSelectable()) - { + public boolean onLongClick(View view) { + if (!mMultiSelector.isSelectable()) { mMultiSelector.setSelectable(true); mMultiSelector.setSelected(this, true); - } - else - { + } else { int position = getAdapterPosition(); - if(position != RecyclerView.NO_POSITION) - { + if (position != RecyclerView.NO_POSITION) { mListener.onItemLongClick(view, position, getItemId(), getItemViewType()); } } return true; } - - public void bindData(ProductEntity product) - { + public void bindData(ProductEntity product) { mNameTextView.setText(product.getName()); } } diff --git a/Src-MVC-RecyclerView/java/adapter/RecyclerAdapter.java b/Src-MVC-RecyclerView/java/adapter/RecyclerAdapter.java index b73bfa7..5eda499 100644 --- a/Src-MVC-RecyclerView/java/adapter/RecyclerAdapter.java +++ b/Src-MVC-RecyclerView/java/adapter/RecyclerAdapter.java @@ -11,9 +11,7 @@ import java.util.List; - -public class RecyclerAdapter extends RecyclerView.Adapter -{ +public class RecyclerAdapter extends RecyclerView.Adapter { private static final int VIEW_TYPE_HEADER = 0; private static final int VIEW_TYPE_PRODUCT = 1; private static final int VIEW_TYPE_FOOTER = 2; @@ -23,167 +21,122 @@ public class RecyclerAdapter extends RecyclerView.Adapter mFooterList; private ProductViewHolder.OnItemClickListener mListener; - - public RecyclerAdapter(List headerList, List productList, List footerList, ProductViewHolder.OnItemClickListener listener) - { + public RecyclerAdapter(List headerList, List productList, List footerList, ProductViewHolder.OnItemClickListener listener) { mHeaderList = headerList; mProductList = productList; mFooterList = footerList; mListener = listener; } - @Override - public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) - { + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); // inflate view and create view holder - if(viewType == VIEW_TYPE_HEADER) - { + if (viewType == VIEW_TYPE_HEADER) { View view = inflater.inflate(R.layout.fragment_recycler_header, parent, false); return new HeaderViewHolder(view); - } - else if(viewType == VIEW_TYPE_PRODUCT) - { + } else if (viewType == VIEW_TYPE_PRODUCT) { View view = inflater.inflate(R.layout.fragment_recycler_item, parent, false); return new ProductViewHolder(view, mListener); - } - else if(viewType == VIEW_TYPE_FOOTER) - { + } else if (viewType == VIEW_TYPE_FOOTER) { View view = inflater.inflate(R.layout.fragment_recycler_footer, parent, false); return new FooterViewHolder(view); - } - else - { + } else { throw new RuntimeException("There is no view type that matches the type " + viewType); } } - @Override - public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) - { - if(viewHolder instanceof HeaderViewHolder) - { + public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { + if (viewHolder instanceof HeaderViewHolder) { // entity String string = mHeaderList.get(getHeaderPosition(position)); // bind data - if(string != null) - { + if (string != null) { ((HeaderViewHolder) viewHolder).bindData(string); } - } - else if(viewHolder instanceof ProductViewHolder) - { + } else if (viewHolder instanceof ProductViewHolder) { // entity ProductEntity product = mProductList.get(getProductPosition(position)); // bind data - if(product != null) - { + if (product != null) { ((ProductViewHolder) viewHolder).bindData(product); } - } - else if(viewHolder instanceof FooterViewHolder) - { + } else if (viewHolder instanceof FooterViewHolder) { // entity Object object = mFooterList.get(getFooterPosition(position)); // bind data - if(object != null) - { + if (object != null) { ((FooterViewHolder) viewHolder).bindData(object); } } } - @Override - public int getItemCount() - { + public int getItemCount() { int size = 0; - if(mHeaderList != null) size += mHeaderList.size(); - if(mProductList != null) size += mProductList.size(); - if(mFooterList != null) size += mFooterList.size(); + if (mHeaderList != null) size += mHeaderList.size(); + if (mProductList != null) size += mProductList.size(); + if (mFooterList != null) size += mFooterList.size(); return size; } - @Override - public int getItemViewType(int position) - { + public int getItemViewType(int position) { int headers = mHeaderList.size(); int products = mProductList.size(); int footers = mFooterList.size(); - if(position < headers) return VIEW_TYPE_HEADER; - else if(position < headers + products) return VIEW_TYPE_PRODUCT; - else if(position < headers + products + footers) return VIEW_TYPE_FOOTER; + if (position < headers) return VIEW_TYPE_HEADER; + else if (position < headers + products) return VIEW_TYPE_PRODUCT; + else if (position < headers + products + footers) return VIEW_TYPE_FOOTER; else return -1; } - - public int getHeaderCount() - { - if(mHeaderList != null) return mHeaderList.size(); + public int getHeaderCount() { + if (mHeaderList != null) return mHeaderList.size(); return 0; } - - public int getProductCount() - { - if(mProductList != null) return mProductList.size(); + public int getProductCount() { + if (mProductList != null) return mProductList.size(); return 0; } - - public int getFooterCount() - { - if(mFooterList != null) return mFooterList.size(); + public int getFooterCount() { + if (mFooterList != null) return mFooterList.size(); return 0; } - - public int getHeaderPosition(int recyclerPosition) - { + public int getHeaderPosition(int recyclerPosition) { return recyclerPosition; } - - public int getProductPosition(int recyclerPosition) - { + public int getProductPosition(int recyclerPosition) { return recyclerPosition - getHeaderCount(); } - - public int getFooterPosition(int recyclerPosition) - { + public int getFooterPosition(int recyclerPosition) { return recyclerPosition - getHeaderCount() - getProductCount(); } - - public int getRecyclerPositionByHeader(int headerPosition) - { + public int getRecyclerPositionByHeader(int headerPosition) { return headerPosition; } - - public int getRecyclerPositionByProduct(int productPosition) - { + public int getRecyclerPositionByProduct(int productPosition) { return productPosition + getHeaderCount(); } - - public int getRecyclerPositionByFooter(int footerPosition) - { + public int getRecyclerPositionByFooter(int footerPosition) { return footerPosition + getProductCount() + getHeaderCount(); } - - public void refill(List headerList, List productList, List footerList, ProductViewHolder.OnItemClickListener listener) - { + public void refill(List headerList, List productList, List footerList, ProductViewHolder.OnItemClickListener listener) { mHeaderList = headerList; mProductList = productList; mFooterList = footerList; @@ -191,49 +144,35 @@ public void refill(List headerList, List productList, Lis notifyDataSetChanged(); } - - public void stop() - { + public void stop() { // TODO: stop image loader } - - public static final class HeaderViewHolder extends RecyclerView.ViewHolder - { + public static final class HeaderViewHolder extends RecyclerView.ViewHolder { private TextView mNameTextView; - - public HeaderViewHolder(View itemView) - { + public HeaderViewHolder(View itemView) { super(itemView); // find views mNameTextView = itemView.findViewById(R.id.recycler_header_name); } - - public void bindData(String string) - { + public void bindData(String string) { mNameTextView.setText(string); } } - - public static final class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener - { + public static final class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { private TextView mNameTextView; private OnItemClickListener mListener; - - public interface OnItemClickListener - { + public interface OnItemClickListener { void onItemClick(View view, int position, long id, int viewType); void onItemLongClick(View view, int position, long id, int viewType); } - - public ProductViewHolder(View itemView, OnItemClickListener listener) - { + public ProductViewHolder(View itemView, OnItemClickListener listener) { super(itemView); mListener = listener; @@ -245,47 +184,34 @@ public ProductViewHolder(View itemView, OnItemClickListener listener) mNameTextView = itemView.findViewById(R.id.recycler_item_name); } - @Override - public void onClick(View view) - { + public void onClick(View view) { int position = getAdapterPosition(); - if(position != RecyclerView.NO_POSITION) - { + if (position != RecyclerView.NO_POSITION) { mListener.onItemClick(view, position, getItemId(), getItemViewType()); } } - @Override - public boolean onLongClick(View view) - { + public boolean onLongClick(View view) { int position = getAdapterPosition(); - if(position != RecyclerView.NO_POSITION) - { + if (position != RecyclerView.NO_POSITION) { mListener.onItemLongClick(view, position, getItemId(), getItemViewType()); } return true; } - - public void bindData(ProductEntity product) - { + public void bindData(ProductEntity product) { mNameTextView.setText(product.getName()); } } - - public static final class FooterViewHolder extends RecyclerView.ViewHolder - { - public FooterViewHolder(View itemView) - { + public static final class FooterViewHolder extends RecyclerView.ViewHolder { + public FooterViewHolder(View itemView) { super(itemView); } - - public void bindData(Object object) - { + public void bindData(Object object) { // do nothing } } diff --git a/Src-MVC-RecyclerView/java/fragment/RecyclerFragment.java b/Src-MVC-RecyclerView/java/fragment/RecyclerFragment.java index 535012b..91faddf 100644 --- a/Src-MVC-RecyclerView/java/fragment/RecyclerFragment.java +++ b/Src-MVC-RecyclerView/java/fragment/RecyclerFragment.java @@ -25,9 +25,7 @@ import java.util.ArrayList; import java.util.List; - -public class RecyclerFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener, RecyclerAdapter.ProductViewHolder.OnItemClickListener -{ +public class RecyclerFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener, RecyclerAdapter.ProductViewHolder.OnItemClickListener { private static final int LAZY_LOADING_TAKE = 16; private static final int LAZY_LOADING_OFFSET = 4; @@ -40,211 +38,165 @@ public class RecyclerFragment extends TaskFragment implements LoadDataTask.OnLoa private List mProductList = new ArrayList<>(); private List mFooterList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_recycler, container, false); setupRecyclerView(); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProductList == null || mProductList.isEmpty()) loadData(); + if (mProductList == null || mProductList.isEmpty()) loadData(); // lazy loading progress - if(mLazyLoading) showLazyLoadingProgress(true); + if (mLazyLoading) showLazyLoadingProgress(true); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onItemClick(View view, int position, long id, int viewType) - { + public void onItemClick(View view, int position, long id, int viewType) { // position int productPosition = mAdapter.getProductPosition(position); // TODO } - @Override - public void onItemLongClick(View view, int position, long id, int viewType) - { + public void onItemLongClick(View view, int position, long id, int viewType) { // position int productPosition = mAdapter.getProductPosition(position); // TODO } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data final int size = mProductList.size(); - for(int i = 0; i < LAZY_LOADING_TAKE; i++) - { + for (int i = 0; i < LAZY_LOADING_TAKE; i++) { ProductEntity p = new ProductEntity(); p.setName("Product " + (size + i)); mProductList.add(p); } - if(mHeaderList.size() == 0) - { + if (mHeaderList.size() == 0) { mHeaderList.add("One"); mHeaderList.add("Two"); mHeaderList.add("Three"); } // show content - if(mProductList != null && mProductList.size() > 0) mStatefulLayout.showContent(); + if (mProductList != null && mProductList.size() > 0) mStatefulLayout.showContent(); else mStatefulLayout.showEmpty(); showLazyLoadingProgress(false); } }); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void lazyLoadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void lazyLoadData() { + if (NetworkUtility.isOnline(getActivity())) { // show lazy loading progress showLazyLoadingProgress(true); @@ -254,25 +206,18 @@ private void lazyLoadData() } } - - private void showLazyLoadingProgress(boolean visible) - { - if(visible) - { + private void showLazyLoadingProgress(boolean visible) { + if (visible) { mLazyLoading = true; // show footer - if(mFooterList.size() <= 0) - { + if (mFooterList.size() <= 0) { mFooterList.add(new Object()); mAdapter.notifyItemInserted(mAdapter.getRecyclerPositionByFooter(0)); } - } - else - { + } else { // hide footer - if(mFooterList.size() > 0) - { + if (mFooterList.size() > 0) { mFooterList.remove(0); mAdapter.notifyItemRemoved(mAdapter.getRecyclerPositionByFooter(0)); } @@ -281,20 +226,15 @@ private void showLazyLoadingProgress(boolean visible) } } - - private void setupView() - { + private void setupView() { // reference RecyclerView recyclerView = getRecyclerView(); // content - if(recyclerView.getAdapter() == null) - { + if (recyclerView.getAdapter() == null) { // create adapter mAdapter = new RecyclerAdapter(mHeaderList, mProductList, mFooterList, this); - } - else - { + } else { // refill adapter mAdapter.refill(mHeaderList, mProductList, mFooterList, this); } @@ -313,18 +253,14 @@ private void setupView() recyclerView.setAdapter(mAdapter); // lazy loading - recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() - { + recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override - public void onScrollStateChanged(RecyclerView recyclerView, int newState) - { + public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } - @Override - public void onScrolled(RecyclerView recyclerView, int dx, int dy) - { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); @@ -333,38 +269,29 @@ public void onScrolled(RecyclerView recyclerView, int dx, int dy) int totalItemCount = layoutManager.getItemCount(); int lastVisibleItem = firstVisibleItem + visibleItemCount; - if(totalItemCount - lastVisibleItem <= LAZY_LOADING_OFFSET && mProductList.size() % LAZY_LOADING_TAKE == 0 && !mProductList.isEmpty()) - { - if(!mLazyLoading) lazyLoadData(); + if (totalItemCount - lastVisibleItem <= LAZY_LOADING_OFFSET && mProductList.size() % LAZY_LOADING_TAKE == 0 && !mProductList.isEmpty()) { + if (!mLazyLoading) lazyLoadData(); } } }); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { + if (state == StatefulLayout.CONTENT) { RecyclerView recyclerView = getRecyclerView(); - if(mLazyLoading && recyclerView.getAdapter() != null) - { + if (mLazyLoading && recyclerView.getAdapter() != null) { mAdapter.notifyDataSetChanged(); - } - else - { - if(mProductList != null) setupView(); + } else { + if (mProductList != null) setupView(); } } } @@ -374,15 +301,11 @@ public void onStateChange(View view, @StatefulLayout.State int state) mStatefulLayout.restoreInstanceState(savedInstanceState); } - - private RecyclerView getRecyclerView() - { + private RecyclerView getRecyclerView() { return mRootView != null ? mRootView.findViewById(R.id.recycler_recycler) : null; } - - private void setupRecyclerView() - { + private void setupRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); RecyclerView recyclerView = getRecyclerView(); diff --git a/Src-MVC-StickyListView/java/adapter/StickyListingAdapter.java b/Src-MVC-StickyListView/java/adapter/StickyListingAdapter.java index 0d5a48b..f4cc541 100644 --- a/Src-MVC-StickyListView/java/adapter/StickyListingAdapter.java +++ b/Src-MVC-StickyListView/java/adapter/StickyListingAdapter.java @@ -15,26 +15,19 @@ import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; - -public class StickyListingAdapter extends BaseAdapter implements StickyListHeadersAdapter -{ +public class StickyListingAdapter extends BaseAdapter implements StickyListHeadersAdapter { private Context mContext; private List mProductList; - - public StickyListingAdapter(Context context, List productList) - { + public StickyListingAdapter(Context context, List productList) { mContext = context; mProductList = productList; } - @Override - public View getView(int position, View convertView, ViewGroup parent) - { + public View getView(int position, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_sticky_listing_item, parent, false); @@ -46,8 +39,7 @@ public View getView(int position, View convertView, ViewGroup parent) // entity ProductEntity product = mProductList.get(position); - if(product != null) - { + if (product != null) { // view holder ViewHolder holder = (ViewHolder) convertView.getTag(); @@ -58,36 +50,27 @@ public View getView(int position, View convertView, ViewGroup parent) return convertView; } - @Override - public int getCount() - { - if(mProductList != null) return mProductList.size(); + public int getCount() { + if (mProductList != null) return mProductList.size(); else return 0; } - @Override - public Object getItem(int position) - { - if(mProductList != null) return mProductList.get(position); + public Object getItem(int position) { + if (mProductList != null) return mProductList.get(position); else return null; } - @Override - public long getItemId(int position) - { + public long getItemId(int position) { return position; } - @Override - public View getHeaderView(int position, View convertView, ViewGroup parent) - { + public View getHeaderView(int position, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_sticky_listing_group, parent, false); @@ -99,8 +82,7 @@ public View getHeaderView(int position, View convertView, ViewGroup parent) // entity GroupEntity group = mProductList.get(position).getGroup(); - if(group != null) - { + if (group != null) { // view holder ViewHolderGroup holder = (ViewHolderGroup) convertView.getTag(); @@ -111,37 +93,27 @@ public View getHeaderView(int position, View convertView, ViewGroup parent) return convertView; } - @Override - public long getHeaderId(int position) - { + public long getHeaderId(int position) { GroupEntity group = mProductList.get(position).getGroup(); return group.getId().hashCode(); } - - public void refill(Context context, List productList) - { + public void refill(Context context, List productList) { mContext = context; mProductList = productList; notifyDataSetChanged(); } - - public void stop() - { + public void stop() { // TODO: stop image loader } - - static class ViewHolder - { + static class ViewHolder { TextView nameTextView; } - - static class ViewHolderGroup - { + static class ViewHolderGroup { TextView nameTextView; } } diff --git a/Src-MVC-StickyListView/java/fragment/StickyListingFragment.java b/Src-MVC-StickyListView/java/fragment/StickyListingFragment.java index e08e608..20729fd 100644 --- a/Src-MVC-StickyListView/java/fragment/StickyListingFragment.java +++ b/Src-MVC-StickyListView/java/fragment/StickyListingFragment.java @@ -25,13 +25,11 @@ import se.emilsjolander.stickylistheaders.StickyListHeadersListView; - public class StickyListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, - StickyListHeadersListView.OnHeaderClickListener -{ + StickyListHeadersListView.OnHeaderClickListener { private View mRootView; private StatefulLayout mStatefulLayout; private StickyListingAdapter mAdapter; @@ -39,175 +37,136 @@ public class StickyListingFragment extends TaskFragment implements private int mListviewPosition = 0; private List mProductList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_sticky_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProductList == null || mProductList.isEmpty()) loadData(); + if (mProductList == null || mProductList.isEmpty()) loadData(); } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); // listview position - if(mRootView != null && mAdapter != null) - { + if (mRootView != null && mAdapter != null) { StickyListHeadersListView stickyListView = mRootView.findViewById(android.R.id.list); mListviewPosition = stickyListView.getFirstVisiblePosition(); } } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onItemClick(AdapterView parent, View clickedView, int position, long id) - { + public void onItemClick(AdapterView parent, View clickedView, int position, long id) { // listview item onclick // TODO } - @Override - public boolean onItemLongClick(AdapterView parent, View clickedView, int position, long id) - { + public boolean onItemLongClick(AdapterView parent, View clickedView, int position, long id) { // TODO return true; } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data - for(int i = 0; i < 8; i++) - { + for (int i = 0; i < 8; i++) { GroupEntity g = new GroupEntity(); g.setId(Integer.toString(i)); g.setName("Group " + i); - for(int j = 0; j < 4; j++) - { + for (int j = 0; j < 4; j++) { ProductEntity p = new ProductEntity(); p.setName("Product " + j); p.setGroup(g); @@ -221,46 +180,34 @@ public void run() }); } - @Override - public void onHeaderClick(StickyListHeadersListView listView, View headerView, int itemPosition, long headerId, boolean currentlySticky) - { + public void onHeaderClick(StickyListHeadersListView listView, View headerView, int itemPosition, long headerId, boolean currentlySticky) { // TODO } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void setupView() - { + private void setupView() { // reference StickyListHeadersListView stickyListView = mRootView.findViewById(android.R.id.list); ViewGroup emptyView = mRootView.findViewById(android.R.id.empty); // listview content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new StickyListingAdapter(getActivity(), mProductList); - } - else - { + } else { // refill adapter mAdapter.refill(getActivity(), mProductList); } @@ -280,30 +227,22 @@ private void setupView() stickyListView.setSelectionFromTop(mListviewPosition, 0); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { + if (state == StatefulLayout.CONTENT) { StickyListHeadersListView stickyListView = mRootView.findViewById(android.R.id.list); - if(stickyListView.getAdapter() != null) - { + if (stickyListView.getAdapter() != null) { mAdapter.notifyDataSetChanged(); - } - else - { - if(mProductList != null) setupView(); + } else { + if (mProductList != null) setupView(); } } } diff --git a/Src-MVC-TreeListView/java/adapter/TreeListingAdapter.java b/Src-MVC-TreeListView/java/adapter/TreeListingAdapter.java index c66e2e5..13b277c 100644 --- a/Src-MVC-TreeListView/java/adapter/TreeListingAdapter.java +++ b/Src-MVC-TreeListView/java/adapter/TreeListingAdapter.java @@ -20,24 +20,18 @@ import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; - -public class TreeListingAdapter extends AbstractTreeViewAdapter -{ +public class TreeListingAdapter extends AbstractTreeViewAdapter { private List mProductList; private Set mSelectedSet; - - public TreeListingAdapter(Activity activity, List productList, Set selectedSet, TreeStateManager treeStateManager, int treeviewDepth) - { + public TreeListingAdapter(Activity activity, List productList, Set selectedSet, TreeStateManager treeStateManager, int treeviewDepth) { super(activity, treeStateManager, treeviewDepth); mProductList = productList; mSelectedSet = selectedSet; } - @Override - public LinearLayout updateView(View view, TreeNodeInfo treeNodeInfo) - { + public LinearLayout updateView(View view, TreeNodeInfo treeNodeInfo) { // reference TextView nameTextView = view.findViewById(R.id.tree_listing_item_name); CheckBox checkBox = view.findViewById(R.id.tree_listing_item_checkbox); @@ -51,24 +45,19 @@ public LinearLayout updateView(View view, TreeNodeInfo treeNodeInfo) // checkbox listener checkBox.setTag(treeNodeInfo.getId()); - checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() - { + checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) - { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Long id = (Long) buttonView.getTag(); - if(isChecked) mSelectedSet.add(id); + if (isChecked) mSelectedSet.add(id); else mSelectedSet.remove(id); } }); // checkbox visibility - if(treeNodeInfo.isWithChildren()) - { + if (treeNodeInfo.isWithChildren()) { checkBox.setVisibility(View.GONE); - } - else - { + } else { checkBox.setVisibility(View.VISIBLE); checkBox.setChecked(mSelectedSet.contains(treeNodeInfo.getId())); } @@ -76,47 +65,34 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) return (LinearLayout) view; } - @Override - public View getNewChildView(TreeNodeInfo treeNodeInfo) - { + public View getNewChildView(TreeNodeInfo treeNodeInfo) { LinearLayout viewLayout = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.fragment_tree_listing_item, null); return updateView(viewLayout, treeNodeInfo); } - @Override - public Drawable getBackgroundDrawable(TreeNodeInfo treeNodeInfo) - { + public Drawable getBackgroundDrawable(TreeNodeInfo treeNodeInfo) { return ContextCompat.getDrawable(getActivity(), R.drawable.selector_selectable_item_bg); } - @Override - public void handleItemClick(View view, Object id) - { + public void handleItemClick(View view, Object id) { TreeNodeInfo treeNodeInfo = getManager().getNodeInfo((Long) id); - if(treeNodeInfo.isWithChildren()) - { + if (treeNodeInfo.isWithChildren()) { super.handleItemClick(view, id); - } - else - { + } else { CheckBox checkBox = view.findViewById(R.id.tree_listing_item_checkbox); checkBox.performClick(); } } - @Override - public long getItemId(int position) - { + public long getItemId(int position) { return getTreeId(position); } - - public void stop() - { + public void stop() { // TODO: stop image loader } } diff --git a/Src-MVC-TreeListView/java/fragment/TreeListingFragment.java b/Src-MVC-TreeListView/java/fragment/TreeListingFragment.java index 40c9373..a30324d 100644 --- a/Src-MVC-TreeListView/java/fragment/TreeListingFragment.java +++ b/Src-MVC-TreeListView/java/fragment/TreeListingFragment.java @@ -31,11 +31,9 @@ import pl.polidea.treeview.TreeStateManager; import pl.polidea.treeview.TreeViewList; - public class TreeListingFragment extends TaskFragment implements LoadDataTask.OnLoadDataListener, - AdapterView.OnItemClickListener -{ + AdapterView.OnItemClickListener { private static final int TREEVIEW_DEPTH = 4; private View mRootView; @@ -46,158 +44,121 @@ public class TreeListingFragment extends TaskFragment implements private LoadDataTask mLoadDataTask; private List mProductList = new ArrayList<>(); - @Override - public void onAttach(Context context) - { + public void onAttach(Context context) { super.onAttach(context); } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_tree_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // setup stateful layout setupStatefulLayout(savedInstanceState); // load data - if(mProductList == null || mProductList.isEmpty() || mTreeStateManager == null) - { + if (mProductList == null || mProductList.isEmpty() || mTreeStateManager == null) { loadData(); } } - @Override - public void onStart() - { + public void onStart() { super.onStart(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // stop adapter - if(mAdapter != null) mAdapter.stop(); + if (mAdapter != null) mAdapter.stop(); } - @Override - public void onStop() - { + public void onStop() { super.onStop(); } - @Override - public void onDestroyView() - { + public void onDestroyView() { super.onDestroyView(); mRootView = null; } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // cancel async tasks - if(mLoadDataTask != null) mLoadDataTask.cancel(true); + if (mLoadDataTask != null) mLoadDataTask.cancel(true); } - @Override - public void onDetach() - { + public void onDetach() { super.onDetach(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // stateful layout state - if(mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); + if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState); } - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) - { + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // action bar menu super.onCreateOptionsMenu(menu, inflater); // TODO } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior return super.onOptionsItemSelected(item); // TODO } - @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) - { + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { getActivity().getMenuInflater().inflate(R.menu.treeview, menu); AdapterView.AdapterContextMenuInfo adapterInfo = (AdapterView.AdapterContextMenuInfo) menuInfo; long id = adapterInfo.id; TreeNodeInfo nodeInfo = mTreeStateManager.getNodeInfo(id); - if(nodeInfo.isWithChildren()) - { - if(nodeInfo.isExpanded()) - { + if (nodeInfo.isWithChildren()) { + if (nodeInfo.isExpanded()) { menu.findItem(R.id.menu_treeview_expand).setVisible(false); menu.findItem(R.id.menu_treeview_expand_all).setVisible(false); - } - else - { + } else { menu.findItem(R.id.menu_treeview_collapse_all).setVisible(false); } - } - else - { + } else { menu.findItem(R.id.menu_treeview_expand).setVisible(false); menu.findItem(R.id.menu_treeview_expand_all).setVisible(false); menu.findItem(R.id.menu_treeview_collapse_all).setVisible(false); @@ -209,63 +170,45 @@ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMen super.onCreateContextMenu(menu, v, menuInfo); } - @Override - public boolean onContextItemSelected(MenuItem item) - { + public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); long id = menuInfo.id; - if(item.getItemId() == R.id.menu_treeview_collapse_all) - { + if (item.getItemId() == R.id.menu_treeview_collapse_all) { mTreeStateManager.collapseChildren(id); return true; - } - else if(item.getItemId() == R.id.menu_treeview_expand_all) - { + } else if (item.getItemId() == R.id.menu_treeview_expand_all) { mTreeStateManager.expandEverythingBelow(id); return true; - } - else if(item.getItemId() == R.id.menu_treeview_expand) - { + } else if (item.getItemId() == R.id.menu_treeview_expand) { mTreeStateManager.expandDirectChildren(id); return true; - } - else if(item.getItemId() == R.id.menu_treeview_delete) - { + } else if (item.getItemId() == R.id.menu_treeview_delete) { mTreeStateManager.removeNodeRecursively(id); return true; - } - else - { + } else { return super.onContextItemSelected(item); } } - @Override - public void onItemClick(AdapterView parent, View clickedView, int position, long id) - { + public void onItemClick(AdapterView parent, View clickedView, int position, long id) { // list position int listPosition = getListPosition((int) id); // TODO } - @Override - public void onLoadData() - { - runTaskCallback(new Runnable() - { - public void run() - { - if(mRootView == null) return; // view was destroyed + public void onLoadData() { + runTaskCallback(new Runnable() { + public void run() { + if (mRootView == null) return; // view was destroyed // get data final int size = mProductList.size(); final int[] nodes = new int[]{0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1}; - for(int i = 0; i < nodes.length; i++) - { + for (int i = 0; i < nodes.length; i++) { ProductEntity p = new ProductEntity(); p.setName("Product " + (size + i)); mProductList.add(p); @@ -274,8 +217,7 @@ public void run() // create tree manager mTreeStateManager = new InMemoryTreeStateManager<>(); TreeBuilder treeBuilder = new TreeBuilder<>(mTreeStateManager); - for(int i = 0; i < nodes.length; i++) - { + for (int i = 0; i < nodes.length; i++) { treeBuilder.sequentiallyAddNextNode((long) i, nodes[i]); } Logcat.d(mTreeStateManager.toString()); @@ -286,39 +228,29 @@ public void run() }); } - - private void loadData() - { - if(NetworkUtility.isOnline(getActivity())) - { + private void loadData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress mStatefulLayout.showProgress(); // run async task mLoadDataTask = new LoadDataTask(this); executeTask(mLoadDataTask); - } - else - { + } else { mStatefulLayout.showOffline(); } } - - private void setupView() - { + private void setupView() { // reference TreeViewList treeView = mRootView.findViewById(android.R.id.list); ViewGroup emptyView = mRootView.findViewById(android.R.id.empty); // treeview content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new TreeListingAdapter(getActivity(), mProductList, mSelectedSet, mTreeStateManager, TREEVIEW_DEPTH); - } - else - { + } else { // refresh adapter mAdapter.refresh(); mAdapter.notifyDataSetChanged(); @@ -336,31 +268,23 @@ private void setupView() registerForContextMenu(treeView); } - - private void setupStatefulLayout(Bundle savedInstanceState) - { + private void setupStatefulLayout(Bundle savedInstanceState) { // reference mStatefulLayout = (StatefulLayout) mRootView; // state change listener - mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() - { + mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() { @Override - public void onStateChange(View view, @StatefulLayout.State int state) - { + public void onStateChange(View view, @StatefulLayout.State int state) { Logcat.d(String.valueOf(state)); - if(state == StatefulLayout.CONTENT) - { + if (state == StatefulLayout.CONTENT) { TreeViewList treeView = mRootView.findViewById(android.R.id.list); - if(treeView.getAdapter() != null) - { + if (treeView.getAdapter() != null) { mAdapter.refresh(); mAdapter.notifyDataSetChanged(); - } - else - { - if(mProductList != null && mTreeStateManager != null) setupView(); + } else { + if (mProductList != null && mTreeStateManager != null) setupView(); } } } @@ -370,27 +294,21 @@ public void onStateChange(View view, @StatefulLayout.State int state) mStatefulLayout.restoreInstanceState(savedInstanceState); } - - private int getListPosition(int globalPosition) - { + private int getListPosition(int globalPosition) { // reference TreeViewList treeView = mRootView.findViewById(android.R.id.list); // list position without headers, should be used for getting data entities from collections int listPosition = globalPosition; - if(treeView != null) listPosition = globalPosition - treeView.getHeaderViewsCount(); + if (treeView != null) listPosition = globalPosition - treeView.getHeaderViewsCount(); return listPosition; } - - private void expandAll() - { - if(mTreeStateManager != null) mTreeStateManager.expandEverythingBelow(null); + private void expandAll() { + if (mTreeStateManager != null) mTreeStateManager.expandEverythingBelow(null); } - - private void collapseAll() - { - if(mTreeStateManager != null) mTreeStateManager.collapseChildren(null); + private void collapseAll() { + if (mTreeStateManager != null) mTreeStateManager.collapseChildren(null); } } diff --git a/Src-Map-Clustering/java/fragment/ExampleFragment.java b/Src-Map-Clustering/java/fragment/ExampleFragment.java index 83c2c8f..5238d36 100644 --- a/Src-Map-Clustering/java/fragment/ExampleFragment.java +++ b/Src-Map-Clustering/java/fragment/ExampleFragment.java @@ -7,7 +7,6 @@ import com.example.R; import com.example.entity.ProductEntity; import com.google.android.gms.maps.GoogleMap; -import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; @@ -16,35 +15,25 @@ import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.clustering.view.DefaultClusterRenderer; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private ClusterManager mClusterManager; - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupClusterManager(); bindData(); } - - private void setupClusterManager() - { - mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() - { + private void setupClusterManager() { + mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() { @Override - public void onMapReady(GoogleMap googleMap) - { + public void onMapReady(GoogleMap googleMap) { mClusterManager = new ClusterManager<>(getActivity(), googleMap); - mClusterManager.setRenderer(new DefaultClusterRenderer(getActivity(), googleMap, mClusterManager) - { + mClusterManager.setRenderer(new DefaultClusterRenderer(getActivity(), googleMap, mClusterManager) { @Override - protected void onBeforeClusterItemRendered(ProductEntity product, MarkerOptions markerOptions) - { + protected void onBeforeClusterItemRendered(ProductEntity product, MarkerOptions markerOptions) { BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED); markerOptions.title(product.getName()); markerOptions.icon(bitmapDescriptor); @@ -56,16 +45,11 @@ protected void onBeforeClusterItemRendered(ProductEntity product, MarkerOptions }); } - - private void bindData() - { - mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() - { + private void bindData() { + mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() { @Override - public void onMapReady(GoogleMap googleMap) - { - for(int i = 0; i < 16; i++) - { + public void onMapReady(GoogleMap googleMap) { + for (int i = 0; i < 16; i++) { ProductEntity product = new ProductEntity(); product.setName("Example " + i); product.setPosition(new LatLng(49.194696 + 0.1 * Math.sin(i * Math.PI / 8), 16.608595 + 0.1 * Math.cos(i * Math.PI / 8))); diff --git a/Src-Map/java/fragment/ExampleFragment.java b/Src-Map/java/fragment/ExampleFragment.java index a9ca4d8..e0257dc 100644 --- a/Src-Map/java/fragment/ExampleFragment.java +++ b/Src-Map/java/fragment/ExampleFragment.java @@ -22,16 +22,12 @@ import org.alfonz.utility.VersionUtility; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private MapView mMapView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); initMap(); mMapView = mRootView.findViewById(R.id.example_map); @@ -39,93 +35,71 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupMap(); bindData(); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); // map - if(mMapView != null) mMapView.onResume(); + if (mMapView != null) mMapView.onResume(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // map - if(mMapView != null) mMapView.onPause(); + if (mMapView != null) mMapView.onPause(); } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // map - if(mMapView != null) mMapView.onDestroy(); + if (mMapView != null) mMapView.onDestroy(); } - @Override - public void onLowMemory() - { + public void onLowMemory() { super.onLowMemory(); // map - if(mMapView != null) mMapView.onLowMemory(); + if (mMapView != null) mMapView.onLowMemory(); } - @Override - public void onSaveInstanceState(Bundle outState) - { + public void onSaveInstanceState(Bundle outState) { // save current instance state super.onSaveInstanceState(outState); setUserVisibleHint(true); // map - if(mMapView != null) mMapView.onSaveInstanceState(outState); + if (mMapView != null) mMapView.onSaveInstanceState(outState); } - - private void initMap() - { - if(!VersionUtility.isSupportedOpenGlEs2(getActivity())) - { + private void initMap() { + if (!VersionUtility.isSupportedOpenGlEs2(getActivity())) { Toast.makeText(getActivity(), R.string.global_map_fail_toast, Toast.LENGTH_LONG).show(); } - try - { + try { MapsInitializer.initialize(getActivity()); - } - catch(Exception e) - { + } catch (Exception e) { e.printStackTrace(); } } - - private void setupMap() - { - mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() - { + private void setupMap() { + mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() { @Override - public void onMapReady(GoogleMap googleMap) - { + public void onMapReady(GoogleMap googleMap) { googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); googleMap.setMyLocationEnabled(true); @@ -145,22 +119,17 @@ public void onMapReady(GoogleMap googleMap) }); } - - private void bindData() - { - mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() - { + private void bindData() { + mRootView.findViewById(R.id.example_map).getMapAsync(new OnMapReadyCallback() { @Override - public void onMapReady(GoogleMap googleMap) - { + public void onMapReady(GoogleMap googleMap) { BitmapDescriptor marker1 = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN); BitmapDescriptor marker2 = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW); BitmapDescriptor marker3 = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED); BitmapDescriptor marker4 = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher); BitmapDescriptor[] markers = {marker1, marker2, marker3, marker4}; - for(int i = 0; i < 16; i++) - { + for (int i = 0; i < 16; i++) { googleMap.addMarker(new MarkerOptions() .position(new LatLng(49.194696 + 0.1 * Math.sin(i * Math.PI / 8), 16.608595 + 0.1 * Math.cos(i * Math.PI / 8))) .title("Example " + i) diff --git a/Src-Navigation-Drawer/java/activity/ExampleActivity.java b/Src-Navigation-Drawer/java/activity/ExampleActivity.java index 8b0d83c..afb7d1f 100644 --- a/Src-Navigation-Drawer/java/activity/ExampleActivity.java +++ b/Src-Navigation-Drawer/java/activity/ExampleActivity.java @@ -22,9 +22,7 @@ import com.example.adapter.DrawerAdapter; import com.example.fragment.ExampleFragment; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private ListView mDrawerListView; @@ -32,43 +30,34 @@ public class ExampleActivity extends AppCompatActivity private CharSequence mDrawerTitle; private String[] mTitles; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupActionBar(); setupDrawer(savedInstanceState); } - @Override - public boolean onPrepareOptionsMenu(Menu menu) - { + public boolean onPrepareOptionsMenu(Menu menu) { // action bar menu visibility - if(menu != null) - { + if (menu != null) { boolean drawerOpened = mDrawerLayout.isDrawerOpen(mDrawerListView); MenuItem refresh = menu.findItem(R.id.menu_example_refresh); - if(refresh != null) refresh.setVisible(!drawerOpened); + if (refresh != null) refresh.setVisible(!drawerOpened); } return super.onPrepareOptionsMenu(menu); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // open or close the drawer if home button is pressed - if(mDrawerToggle.onOptionsItemSelected(item)) - { + if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case android.R.id.home: // TODO return true; @@ -82,47 +71,34 @@ public boolean onOptionsItemSelected(MenuItem item) } } - @Override - protected void onPostCreate(Bundle savedInstanceState) - { + protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } - @Override - public void onConfigurationChanged(Configuration newConfiguration) - { + public void onConfigurationChanged(Configuration newConfiguration) { super.onConfigurationChanged(newConfiguration); mDrawerToggle.onConfigurationChanged(newConfiguration); } - @Override - public void onBackPressed() - { - if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)) - { + public void onBackPressed() { + if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); - } - else - { + } else { super.onBackPressed(); } } - @Override - public void setTitle(CharSequence title) - { + public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } - - private void setupActionBar() - { + private void setupActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); @@ -134,9 +110,7 @@ private void setupActionBar() bar.setHomeButtonEnabled(true); } - - private void setupDrawer(Bundle savedInstanceState) - { + private void setupDrawer(Bundle savedInstanceState) { mTitle = getTitle(); mDrawerTitle = getTitle(); @@ -159,27 +133,21 @@ private void setupDrawer(Bundle savedInstanceState) // set drawer mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); mDrawerListView.setAdapter(new DrawerAdapter(this, mTitles, icons)); - mDrawerListView.setOnItemClickListener(new OnItemClickListener() - { + mDrawerListView.setOnItemClickListener(new OnItemClickListener() { @Override - public void onItemClick(AdapterView adapterView, View clickedView, int position, long id) - { + public void onItemClick(AdapterView adapterView, View clickedView, int position, long id) { selectDrawerItem(position); } }); - mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) - { + mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { @Override - public void onDrawerClosed(View view) - { + public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); supportInvalidateOptionsMenu(); } - @Override - public void onDrawerOpened(View drawerView) - { + public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); supportInvalidateOptionsMenu(); } @@ -187,20 +155,17 @@ public void onDrawerOpened(View drawerView) mDrawerLayout.addDrawerListener(mDrawerToggle); // show initial fragment - if(savedInstanceState == null) - { + if (savedInstanceState == null) { selectDrawerItem(0); } } - - private void selectDrawerItem(int position) - { + private void selectDrawerItem(int position) { Fragment fragment; - if(position == 0) fragment = ExampleFragment.newInstance(); - else if(position == 1) fragment = ExampleFragment.newInstance(); - else if(position == 2) fragment = ExampleFragment.newInstance(); - else if(position == 3) fragment = ExampleFragment.newInstance(); + if (position == 0) fragment = ExampleFragment.newInstance(); + else if (position == 1) fragment = ExampleFragment.newInstance(); + else if (position == 2) fragment = ExampleFragment.newInstance(); + else if (position == 3) fragment = ExampleFragment.newInstance(); else fragment = ExampleFragment.newInstance(); FragmentManager fragmentManager = getSupportFragmentManager(); diff --git a/Src-Navigation-Drawer/java/adapter/DrawerAdapter.java b/Src-Navigation-Drawer/java/adapter/DrawerAdapter.java index 9b17645..aff4101 100644 --- a/Src-Navigation-Drawer/java/adapter/DrawerAdapter.java +++ b/Src-Navigation-Drawer/java/adapter/DrawerAdapter.java @@ -10,28 +10,21 @@ import com.example.R; - -public class DrawerAdapter extends BaseAdapter -{ +public class DrawerAdapter extends BaseAdapter { private Context mContext; private String[] mTitleList; private Integer[] mIconList; - - public DrawerAdapter(Context context, String[] titleList, Integer[] iconList) - { + public DrawerAdapter(Context context, String[] titleList, Integer[] iconList) { mContext = context; mTitleList = titleList; mIconList = iconList; } - @Override - public View getView(final int position, View convertView, ViewGroup parent) - { + public View getView(final int position, View convertView, ViewGroup parent) { // inflate view - if(convertView == null) - { + if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.drawer_item, parent, false); @@ -45,8 +38,7 @@ public View getView(final int position, View convertView, ViewGroup parent) // entity String title = mTitleList[position]; Integer icon = mIconList[position]; - if(title != null && icon != null) - { + if (title != null && icon != null) { // view holder ViewHolder holder = (ViewHolder) convertView.getTag(); @@ -58,41 +50,31 @@ public View getView(final int position, View convertView, ViewGroup parent) return convertView; } - @Override - public int getCount() - { - if(mTitleList != null) return mTitleList.length; + public int getCount() { + if (mTitleList != null) return mTitleList.length; else return 0; } - @Override - public Object getItem(int position) - { - if(mTitleList != null) return mTitleList[position]; + public Object getItem(int position) { + if (mTitleList != null) return mTitleList[position]; else return null; } - @Override - public long getItemId(int position) - { + public long getItemId(int position) { return position; } - - public void refill(Context context, String[] titleList, Integer[] iconList) - { + public void refill(Context context, String[] titleList, Integer[] iconList) { mContext = context; mTitleList = titleList; mIconList = iconList; notifyDataSetChanged(); } - - static class ViewHolder - { + static class ViewHolder { TextView titleTextView; ImageView iconImageView; } diff --git a/Src-NavigationView/java/activity/ExampleActivity.java b/Src-NavigationView/java/activity/ExampleActivity.java index 89d403f..e8c9f47 100644 --- a/Src-NavigationView/java/activity/ExampleActivity.java +++ b/Src-NavigationView/java/activity/ExampleActivity.java @@ -20,17 +20,13 @@ import com.example.R; import com.example.fragment.ExampleFragment; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private ActionBarDrawerToggle mDrawerToggle; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupActionBar(); @@ -38,19 +34,15 @@ public void onCreate(Bundle savedInstanceState) setupHeader(); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // open or close the drawer if home button is pressed - if(mDrawerToggle.onOptionsItemSelected(item)) - { + if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case android.R.id.home: // TODO return true; @@ -60,39 +52,28 @@ public boolean onOptionsItemSelected(MenuItem item) } } - @Override - protected void onPostCreate(Bundle savedInstanceState) - { + protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } - @Override - public void onConfigurationChanged(Configuration newConfiguration) - { + public void onConfigurationChanged(Configuration newConfiguration) { super.onConfigurationChanged(newConfiguration); mDrawerToggle.onConfigurationChanged(newConfiguration); } - @Override - public void onBackPressed() - { - if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)) - { + public void onBackPressed() { + if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); - } - else - { + } else { super.onBackPressed(); } } - - private void setupActionBar() - { + private void setupActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); @@ -104,53 +85,42 @@ private void setupActionBar() bar.setHomeButtonEnabled(true); } - - private void setupDrawer(Bundle savedInstanceState) - { + private void setupDrawer(Bundle savedInstanceState) { // reference mDrawerLayout = findViewById(R.id.example_drawer_layout); mNavigationView = findViewById(R.id.example_drawer_navigation); // navigation - mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() - { + mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override - public boolean onNavigationItemSelected(@NonNull MenuItem item) - { + public boolean onNavigationItemSelected(@NonNull MenuItem item) { selectDrawerItem(item); return true; } }); // toggle - mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) - { + mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { @Override - public void onDrawerClosed(View view) - { + public void onDrawerClosed(View view) { supportInvalidateOptionsMenu(); } - @Override - public void onDrawerOpened(View drawerView) - { + public void onDrawerOpened(View drawerView) { supportInvalidateOptionsMenu(); } }; mDrawerLayout.addDrawerListener(mDrawerToggle); // show initial fragment - if(savedInstanceState == null) - { + if (savedInstanceState == null) { MenuItem item = mNavigationView.getMenu().findItem(R.id.menu_navigation_example1); selectDrawerItem(item); } } - - private void setupHeader() - { + private void setupHeader() { // reference TextView titleTextView = mNavigationView.getHeaderView(0).findViewById(R.id.navigation_header_title); @@ -158,14 +128,11 @@ private void setupHeader() titleTextView.setText("Hello world"); } - - private void selectDrawerItem(MenuItem item) - { + private void selectDrawerItem(MenuItem item) { Fragment fragment = null; Intent intent = null; - switch(item.getItemId()) - { + switch (item.getItemId()) { case R.id.menu_navigation_example1: case R.id.menu_navigation_example2: case R.id.menu_navigation_example3: @@ -180,8 +147,7 @@ private void selectDrawerItem(MenuItem item) break; } - if(fragment != null) - { + if (fragment != null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container_drawer_content, fragment).commitAllowingStateLoss(); @@ -189,8 +155,7 @@ private void selectDrawerItem(MenuItem item) getSupportActionBar().setTitle(item.getTitle()); } - if(intent != null) - { + if (intent != null) { startActivity(intent); } diff --git a/Src-Notification/java/fragment/ExampleFragment.java b/Src-Notification/java/fragment/ExampleFragment.java index 8d3dda6..2f01bb4 100644 --- a/Src-Notification/java/fragment/ExampleFragment.java +++ b/Src-Notification/java/fragment/ExampleFragment.java @@ -10,23 +10,17 @@ import com.example.activity.ExampleActivity; import com.example.notification.NotificationMessage; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private NotificationMessage mNotificationMessage; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void showNotification() - { + private void showNotification() { NotificationMessage.Builder builder = new NotificationMessage.Builder(getActivity().getApplicationContext(), NotificationMessage.Type.TYPE1); builder.setIntent(ExampleActivity.newIntent(getActivity().getApplicationContext())); // TODO: it is recommended to set FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK flags @@ -56,9 +50,7 @@ private void showNotification() mNotificationMessage.show(); } - - private void cancelNotification() - { - if(mNotificationMessage != null) mNotificationMessage.cancel(); + private void cancelNotification() { + if (mNotificationMessage != null) mNotificationMessage.cancel(); } } diff --git a/Src-Notification/java/notification/NotificationMessage.java b/Src-Notification/java/notification/NotificationMessage.java index 5ae4430..3a52b63 100644 --- a/Src-Notification/java/notification/NotificationMessage.java +++ b/Src-Notification/java/notification/NotificationMessage.java @@ -13,47 +13,35 @@ import java.util.List; - // requires android.permission.VIBRATE -public class NotificationMessage -{ +public class NotificationMessage { private Context mContext; private Type mType; private Notification mNotification; - - public enum Type - { + public enum Type { TYPE1, TYPE2, TYPE3 } - - private NotificationMessage(Context context, Type type, Notification notification) - { + private NotificationMessage(Context context, Type type, Notification notification) { mContext = context.getApplicationContext(); mType = type; mNotification = notification; } - - public void show() - { + public void show() { // show notification NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(mType.ordinal(), mNotification); } - - public void cancel() - { + public void cancel() { // cancel notification NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(mType.ordinal()); } - - public static class Builder - { + public static class Builder { private Context mContext; private Type mType; @@ -93,99 +81,70 @@ public static class Builder private CharSequence mInboxStyleSummaryText = null; private List mInboxStyleLines = null; - - public Builder(Context context, Type type) - { + public Builder(Context context, Type type) { mContext = context.getApplicationContext(); mType = type; } - - public void setIntent(Intent notificationIntent) - { + public void setIntent(Intent notificationIntent) { // pending intent mPendingIntent = PendingIntent.getActivity(mContext, mType.ordinal(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); } - - public void setText(String ticker, String title, String text) - { + public void setText(String ticker, String title, String text) { mTicker = ticker; mTitle = title; mText = text; } - - public void setExtraText(String subText, String contentInfo) - { + public void setExtraText(String subText, String contentInfo) { mSubText = subText; mContentInfo = contentInfo; } - - public void setNumber(int number) - { + public void setNumber(int number) { mNumber = number; } - - public void setTime(long when) - { + public void setTime(long when) { mWhen = when; } - - public void setIcon(int smallIcon, Bitmap largeIcon) - { + public void setIcon(int smallIcon, Bitmap largeIcon) { mSmallIcon = smallIcon; mLargeIcon = largeIcon; } - - public void setIcon(int smallIcon, int largeIcon) - { + public void setIcon(int smallIcon, int largeIcon) { mSmallIcon = smallIcon; mLargeIcon = BitmapFactory.decodeResource(mContext.getResources(), largeIcon); } - - public void setProgress(int max, int progress, boolean indeterminate) - { + public void setProgress(int max, int progress, boolean indeterminate) { // setProgress() does not work with setExtraText() method - if(indeterminate) - { + if (indeterminate) { mProgressMax = 0; mProgress = 0; - } - else - { + } else { mProgressMax = max; mProgress = progress; } mProgressIndeterminate = indeterminate; } - - public void setUsesChronometer(boolean usesChronometer) - { + public void setUsesChronometer(boolean usesChronometer) { mUsesChronometer = usesChronometer; } - - public void setOnlyAlertOnce(boolean onlyAlertOnce) - { + public void setOnlyAlertOnce(boolean onlyAlertOnce) { mOnlyAlertOnce = onlyAlertOnce; } - - public void setOngoing(boolean ongoing) - { + public void setOngoing(boolean ongoing) { mOnGoing = ongoing; } - - public void setAction1(int icon, CharSequence title, Intent actionIntent) - { + public void setAction1(int icon, CharSequence title, Intent actionIntent) { mAction1Icon = icon; mAction1Title = title; @@ -193,9 +152,7 @@ public void setAction1(int icon, CharSequence title, Intent actionIntent) mAction1PendingIntent = PendingIntent.getActivity(mContext, mType.ordinal(), actionIntent, PendingIntent.FLAG_UPDATE_CURRENT); } - - public void setAction2(int icon, CharSequence title, Intent actionIntent) - { + public void setAction2(int icon, CharSequence title, Intent actionIntent) { mAction2Icon = icon; mAction2Title = title; @@ -203,54 +160,44 @@ public void setAction2(int icon, CharSequence title, Intent actionIntent) mAction2PendingIntent = PendingIntent.getActivity(mContext, mType.ordinal(), actionIntent, PendingIntent.FLAG_UPDATE_CURRENT); } - - public void setBigTextStyle(CharSequence bigContentTitle, CharSequence summaryText, CharSequence bigText) - { + public void setBigTextStyle(CharSequence bigContentTitle, CharSequence summaryText, CharSequence bigText) { mBigTextStyleBigContentTitle = bigContentTitle; mBigTextStyleSummaryText = summaryText; mBigTextStyleBigText = bigText; } - - public void setBigPictureStyle(CharSequence bigContentTitle, CharSequence summaryText, Bitmap bigPicture) - { + public void setBigPictureStyle(CharSequence bigContentTitle, CharSequence summaryText, Bitmap bigPicture) { mBigPictureStyleBigContentTitle = bigContentTitle; mBigPictureStyleSummaryText = summaryText; mBigPictureStyleBigPicture = bigPicture; } - - public void setBigPictureStyle(CharSequence bigContentTitle, CharSequence summaryText, int bigPicture) - { + public void setBigPictureStyle(CharSequence bigContentTitle, CharSequence summaryText, int bigPicture) { mBigPictureStyleBigContentTitle = bigContentTitle; mBigPictureStyleSummaryText = summaryText; mBigPictureStyleBigPicture = BitmapFactory.decodeResource(mContext.getResources(), bigPicture); } - - public void setInboxStyle(CharSequence bigContentTitle, CharSequence summaryText, List lines) - { + public void setInboxStyle(CharSequence bigContentTitle, CharSequence summaryText, List lines) { mInboxStyleBigContentTitle = bigContentTitle; mInboxStyleSummaryText = summaryText; mInboxStyleLines = lines; } - - public NotificationMessage build() - { + public NotificationMessage build() { // notification builder NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext); - if(mPendingIntent != null) builder.setContentIntent(mPendingIntent); - if(mTicker != null) builder.setTicker(mTicker); - if(mTitle != null) builder.setContentTitle(mTitle); - if(mText != null) builder.setContentText(mText); - if(mSubText != null) builder.setSubText(mSubText); - if(mContentInfo != null) builder.setContentInfo(mContentInfo); - if(mNumber > 0) builder.setNumber(mNumber); - if(mWhen > 0L) builder.setWhen(mWhen); - if(mSmallIcon > 0) builder.setSmallIcon(mSmallIcon); - if(mLargeIcon != null) builder.setLargeIcon(mLargeIcon); - if(mProgressMax >= 0 && mProgress >= 0) + if (mPendingIntent != null) builder.setContentIntent(mPendingIntent); + if (mTicker != null) builder.setTicker(mTicker); + if (mTitle != null) builder.setContentTitle(mTitle); + if (mText != null) builder.setContentText(mText); + if (mSubText != null) builder.setSubText(mSubText); + if (mContentInfo != null) builder.setContentInfo(mContentInfo); + if (mNumber > 0) builder.setNumber(mNumber); + if (mWhen > 0L) builder.setWhen(mWhen); + if (mSmallIcon > 0) builder.setSmallIcon(mSmallIcon); + if (mLargeIcon != null) builder.setLargeIcon(mLargeIcon); + if (mProgressMax >= 0 && mProgress >= 0) builder.setProgress(mProgressMax, mProgress, mProgressIndeterminate); builder.setUsesChronometer(mUsesChronometer); builder.setOnlyAlertOnce(mOnlyAlertOnce); @@ -260,60 +207,49 @@ public NotificationMessage build() builder.setDefaults(Notification.DEFAULT_ALL); // notification actions - if(mAction1Icon > 0 || mAction1Title != null || mAction1PendingIntent != null) - { + if (mAction1Icon > 0 || mAction1Title != null || mAction1PendingIntent != null) { builder.addAction(mAction1Icon, mAction1Title, mAction1PendingIntent); } - if(mAction2Icon > 0 || mAction2Title != null || mAction2PendingIntent != null) - { + if (mAction2Icon > 0 || mAction2Title != null || mAction2PendingIntent != null) { builder.addAction(mAction2Icon, mAction2Title, mAction2PendingIntent); } // notification style Notification notification; - if(mBigTextStyleBigContentTitle != null || mBigTextStyleSummaryText != null || mBigTextStyleBigText != null) - { + if (mBigTextStyleBigContentTitle != null || mBigTextStyleSummaryText != null || mBigTextStyleBigText != null) { NotificationCompat.BigTextStyle notificationStyle = new NotificationCompat.BigTextStyle(); notificationStyle.setBuilder(builder); - if(mBigTextStyleBigContentTitle != null) + if (mBigTextStyleBigContentTitle != null) notificationStyle.setBigContentTitle(mBigTextStyleBigContentTitle); - if(mBigTextStyleSummaryText != null) + if (mBigTextStyleSummaryText != null) notificationStyle.setSummaryText(mBigTextStyleSummaryText); - if(mBigTextStyleBigText != null) + if (mBigTextStyleBigText != null) notificationStyle.bigText(mBigTextStyleBigText); notification = notificationStyle.build(); - } - else if(mBigPictureStyleBigContentTitle != null || mBigPictureStyleSummaryText != null || mBigPictureStyleBigPicture != null) - { + } else if (mBigPictureStyleBigContentTitle != null || mBigPictureStyleSummaryText != null || mBigPictureStyleBigPicture != null) { NotificationCompat.BigPictureStyle notificationStyle = new NotificationCompat.BigPictureStyle(); notificationStyle.setBuilder(builder); - if(mBigPictureStyleBigContentTitle != null) + if (mBigPictureStyleBigContentTitle != null) notificationStyle.setBigContentTitle(mBigPictureStyleBigContentTitle); - if(mBigPictureStyleSummaryText != null) + if (mBigPictureStyleSummaryText != null) notificationStyle.setSummaryText(mBigPictureStyleSummaryText); - if(mBigPictureStyleBigPicture != null) + if (mBigPictureStyleBigPicture != null) notificationStyle.bigPicture(mBigPictureStyleBigPicture); notification = notificationStyle.build(); - } - else if(mInboxStyleBigContentTitle != null || mInboxStyleSummaryText != null || mInboxStyleLines != null) - { + } else if (mInboxStyleBigContentTitle != null || mInboxStyleSummaryText != null || mInboxStyleLines != null) { NotificationCompat.InboxStyle notificationStyle = new NotificationCompat.InboxStyle(); notificationStyle.setBuilder(builder); - if(mInboxStyleBigContentTitle != null) + if (mInboxStyleBigContentTitle != null) notificationStyle.setBigContentTitle(mInboxStyleBigContentTitle); - if(mInboxStyleSummaryText != null) + if (mInboxStyleSummaryText != null) notificationStyle.setSummaryText(mInboxStyleSummaryText); - if(mInboxStyleLines != null) - { - for(int i = 0; i < mInboxStyleLines.size(); i++) - { + if (mInboxStyleLines != null) { + for (int i = 0; i < mInboxStyleLines.size(); i++) { notificationStyle.addLine(mInboxStyleLines.get(i)); } } notification = notificationStyle.build(); - } - else - { + } else { notification = builder.build(); } diff --git a/Src-Parcelable/java/entity/ExampleEntity.java b/Src-Parcelable/java/entity/ExampleEntity.java index 939c666..8b88f45 100644 --- a/Src-Parcelable/java/entity/ExampleEntity.java +++ b/Src-Parcelable/java/entity/ExampleEntity.java @@ -7,19 +7,13 @@ import java.util.Date; import java.util.List; - -public class ExampleEntity implements Parcelable -{ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() - { - public ExampleEntity createFromParcel(Parcel parcel) - { +public class ExampleEntity implements Parcelable { + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public ExampleEntity createFromParcel(Parcel parcel) { return new ExampleEntity(parcel); } - - public ExampleEntity[] newArray(int size) - { + public ExampleEntity[] newArray(int size) { return new ExampleEntity[size]; } }; @@ -33,30 +27,22 @@ public ExampleEntity[] newArray(int size) private MyEntity myEntity; private List stringList; - // empty constructor - public ExampleEntity() - { + public ExampleEntity() { } - // parcel constructor - public ExampleEntity(Parcel parcel) - { + public ExampleEntity(Parcel parcel) { readFromParcel(parcel); } - @Override - public int describeContents() - { + public int describeContents() { return 0; } - @Override - public void writeToParcel(Parcel parcel, int flags) - { + public void writeToParcel(Parcel parcel, int flags) { // order is important parcel.writeByte((byte) (booleanVar ? 1 : 0)); parcel.writeInt(intVar); @@ -68,9 +54,7 @@ public void writeToParcel(Parcel parcel, int flags) parcel.writeStringList(stringList); } - - private void readFromParcel(Parcel parcel) - { + private void readFromParcel(Parcel parcel) { // order is important booleanVar = parcel.readByte() == 1; intVar = parcel.readInt(); @@ -78,17 +62,14 @@ private void readFromParcel(Parcel parcel) stringVar = parcel.readString(); long dateVarLong = parcel.readLong(); - if(dateVarLong != -1L) dateVar = new Date(dateVarLong); + if (dateVarLong != -1L) dateVar = new Date(dateVarLong); else dateVar = null; long calendarVarLong = parcel.readLong(); - if(calendarVarLong != -1L) - { + if (calendarVarLong != -1L) { calendarVar = Calendar.getInstance(); calendarVar.setTimeInMillis(calendarVarLong); - } - else - { + } else { calendarVar = null; } diff --git a/Src-PopupMenu/java/fragment/ExampleFragment.java b/Src-PopupMenu/java/fragment/ExampleFragment.java index d9bf713..7db210d 100644 --- a/Src-PopupMenu/java/fragment/ExampleFragment.java +++ b/Src-PopupMenu/java/fragment/ExampleFragment.java @@ -11,37 +11,27 @@ import com.example.R; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void setupView() - { + private void setupView() { // reference Button exampleButton = mRootView.findViewById(R.id.example_button); // popup menu - exampleButton.setOnClickListener(new View.OnClickListener() - { + exampleButton.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View view) - { + public void onClick(View view) { PopupMenu popup = new PopupMenu(getActivity(), view); popup.getMenuInflater().inflate(R.menu.fragment_example, popup.getMenu()); - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() - { - public boolean onMenuItemClick(MenuItem item) - { + popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { // TODO return true; diff --git a/Src-PreferenceFragment/java/fragment/ExampleFragment.java b/Src-PreferenceFragment/java/fragment/ExampleFragment.java index dff75b7..441c499 100644 --- a/Src-PreferenceFragment/java/fragment/ExampleFragment.java +++ b/Src-PreferenceFragment/java/fragment/ExampleFragment.java @@ -19,20 +19,15 @@ import com.example.R; import com.example.utility.Preferences; - -public class ExampleFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener -{ +public class ExampleFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // register listener @@ -42,41 +37,32 @@ public void onActivityCreated(Bundle savedInstanceState) setupView(); } - @Override - public void onDestroy() - { + public void onDestroy() { super.onDestroy(); // unregister listener PreferenceManager.getDefaultSharedPreferences(getActivity()).unregisterOnSharedPreferenceChangeListener(this); } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) - { + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setupView(); } - @Override - public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) - { + public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { super.onPreferenceTreeClick(preferenceScreen, preference); // if the user has clicked on a preference screen, setup the action bar - if(preference instanceof PreferenceScreen) - { + if (preference instanceof PreferenceScreen) { setupActionBar((PreferenceScreen) preference); } return false; } - - private void setupActionBar(PreferenceScreen preferenceScreen) - { + private void setupActionBar(PreferenceScreen preferenceScreen) { final Dialog dialog = preferenceScreen.getDialog(); LinearLayout root = dialog.findViewById(android.R.id.list).getParent(); Toolbar toolbar = (Toolbar) LayoutInflater.from(getActivity()).inflate(R.layout.toolbar, root, false); @@ -88,19 +74,15 @@ private void setupActionBar(PreferenceScreen preferenceScreen) toolbar.setTitle(preferenceScreen.getTitle()); toolbar.setNavigationIcon(drawable); - toolbar.setNavigationOnClickListener(new View.OnClickListener() - { + toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { dialog.dismiss(); } }); } - - private void setupView() - { + private void setupView() { // references PreferenceScreen rootPreferenceScreen = getPreferenceScreen(); EditTextPreference displayNameEditTextPreference = (EditTextPreference) findPreference(getString(R.string.prefs_key_display_name)); diff --git a/Src-Preferences/java/activity/ExampleActivity.java b/Src-Preferences/java/activity/ExampleActivity.java index d5fd0c6..7feb68c 100644 --- a/Src-Preferences/java/activity/ExampleActivity.java +++ b/Src-Preferences/java/activity/ExampleActivity.java @@ -8,15 +8,11 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity implements OnSharedPreferenceChangeListener -{ +public class ExampleActivity extends AppCompatActivity implements OnSharedPreferenceChangeListener { private boolean mPreferencesChanged = false; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); @@ -24,36 +20,28 @@ public void onCreate(Bundle savedInstanceState) PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); } - @Override - public void onResume() - { + public void onResume() { super.onResume(); // preferences have changed so refresh data - if(mPreferencesChanged) - { + if (mPreferencesChanged) { refreshData(); mPreferencesChanged = false; } } - @Override - public void onDestroy() - { + public void onDestroy() { // unregister listener PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) - { - if(key.equals(getString(R.string.prefs_key_example))) - { + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + if (key.equals(getString(R.string.prefs_key_example))) { mPreferencesChanged = true; } } diff --git a/Src-Preferences/java/utility/Preferences.java b/Src-Preferences/java/utility/Preferences.java index f1d920c..dd838f2 100644 --- a/Src-Preferences/java/utility/Preferences.java +++ b/Src-Preferences/java/utility/Preferences.java @@ -7,77 +7,55 @@ import com.example.ExampleApplication; import com.example.R; - -public class Preferences -{ +public class Preferences { private Context mContext; private SharedPreferences mSharedPreferences; - - public Preferences() - { + public Preferences() { mContext = ExampleApplication.getContext(); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); } - - public void clearPreferences() - { + public void clearPreferences() { mSharedPreferences.edit().clear().apply(); } - - public long getUserId() - { + public long getUserId() { String key = mContext.getString(R.string.prefs_key_user_id); return mSharedPreferences.getLong(key, -1L); } - - public void setUserId(long userId) - { + public void setUserId(long userId) { String key = mContext.getString(R.string.prefs_key_user_id); mSharedPreferences.edit().putLong(key, userId).apply(); } - - public String getPassword() - { + public String getPassword() { String key = mContext.getString(R.string.prefs_key_password); return mSharedPreferences.getString(key, null); } - - public void setPassword(String password) - { + public void setPassword(String password) { String key = mContext.getString(R.string.prefs_key_password); mSharedPreferences.edit().putString(key, password).apply(); } - - public String getVersion() - { + public String getVersion() { String key = mContext.getString(R.string.prefs_key_version); return mSharedPreferences.getString(key, null); } - - public void setVersion(String version) - { + public void setVersion(String version) { String key = mContext.getString(R.string.prefs_key_version); mSharedPreferences.edit().putString(key, version).apply(); } - - public int getRateCounter() - { + public int getRateCounter() { String key = mContext.getString(R.string.prefs_key_rate_counter); return mSharedPreferences.getInt(key, 0); } - - public void setRateCounter(int rateCounter) - { + public void setRateCounter(int rateCounter) { String key = mContext.getString(R.string.prefs_key_rate_counter); mSharedPreferences.edit().putInt(key, rateCounter).apply(); } diff --git a/Src-Receiver/java/receiver/BootCompletedReceiver.java b/Src-Receiver/java/receiver/BootCompletedReceiver.java index ff9685a..e71ff5e 100644 --- a/Src-Receiver/java/receiver/BootCompletedReceiver.java +++ b/Src-Receiver/java/receiver/BootCompletedReceiver.java @@ -6,12 +6,9 @@ import org.alfonz.utility.Logcat; - -public class BootCompletedReceiver extends BroadcastReceiver -{ +public class BootCompletedReceiver extends BroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) - { + public void onReceive(Context context, Intent intent) { Logcat.d(""); // TODO: do something diff --git a/Src-Receiver/java/receiver/PhoneStateReceiver.java b/Src-Receiver/java/receiver/PhoneStateReceiver.java index cb84065..adcb388 100644 --- a/Src-Receiver/java/receiver/PhoneStateReceiver.java +++ b/Src-Receiver/java/receiver/PhoneStateReceiver.java @@ -8,19 +8,15 @@ import org.alfonz.utility.Logcat; - -public class PhoneStateReceiver extends BroadcastReceiver -{ +public class PhoneStateReceiver extends BroadcastReceiver { @Override - public void onReceive(Context context, Intent intent) - { + public void onReceive(Context context, Intent intent) { Logcat.d(""); String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); String msg = "Phone state changed to " + state; - if(TelephonyManager.EXTRA_STATE_RINGING.equals(state)) - { + if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) { String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); msg += ". Incoming number is " + incomingNumber; } diff --git a/Src-SSL/java/rest/ssl/CertificateAuthoritySslUtility.java b/Src-SSL/java/rest/ssl/CertificateAuthoritySslUtility.java index e9a193d..32703c8 100644 --- a/Src-SSL/java/rest/ssl/CertificateAuthoritySslUtility.java +++ b/Src-SSL/java/rest/ssl/CertificateAuthoritySslUtility.java @@ -10,14 +10,10 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.X509TrustManager; - -public final class CertificateAuthoritySslUtility -{ +public final class CertificateAuthoritySslUtility { private CertificateAuthoritySslUtility() {} - - public static void setupSslConnection(HttpsURLConnection connection, URL requestUrl) throws GeneralSecurityException - { + public static void setupSslConnection(HttpsURLConnection connection, URL requestUrl) throws GeneralSecurityException { SSLContext sslContext = createSslContext(); HostnameVerifier sslHostnameVerifier = createSslHostnameVerifier(requestUrl.getHost()); @@ -26,22 +22,16 @@ public static void setupSslConnection(HttpsURLConnection connection, URL request //HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } - - public static SSLContext createSslContext() throws GeneralSecurityException - { + public static SSLContext createSslContext() throws GeneralSecurityException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[]{new CertificateAuthorityTrustManager()}, new SecureRandom()); return context; } - - public static HostnameVerifier createSslHostnameVerifier(final String apiHostname) - { - HostnameVerifier hostnameVerifier = new HostnameVerifier() - { + public static HostnameVerifier createSslHostnameVerifier(final String apiHostname) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override - public boolean verify(String hostname, SSLSession session) - { + public boolean verify(String hostname, SSLSession session) { //Logcat.d(hostname + " / " + apiHostname); return hostname.equals(apiHostname); } diff --git a/Src-SSL/java/rest/ssl/CertificateAuthorityTrustManager.java b/Src-SSL/java/rest/ssl/CertificateAuthorityTrustManager.java index 87d7b7a..3f1b373 100644 --- a/Src-SSL/java/rest/ssl/CertificateAuthorityTrustManager.java +++ b/Src-SSL/java/rest/ssl/CertificateAuthorityTrustManager.java @@ -16,18 +16,14 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; - // useful articles about trusting SSL certificates: // http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html // http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872#6378872 // http://nelenkov.blogspot.cz/2011/12/using-custom-certificate-trust-store-on.html -public class CertificateAuthorityTrustManager implements X509TrustManager -{ +public class CertificateAuthorityTrustManager implements X509TrustManager { private X509TrustManager mDefaultTrustManager = null; - - public CertificateAuthorityTrustManager() throws NoSuchAlgorithmException, KeyStoreException - { + public CertificateAuthorityTrustManager() throws NoSuchAlgorithmException, KeyStoreException { super(); // init factory @@ -37,52 +33,41 @@ public CertificateAuthorityTrustManager() throws NoSuchAlgorithmException, KeySt // create default trust manager checking certificates signed with certificate authority TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - if(trustManagers.length == 0) - { + if (trustManagers.length == 0) { throw new NoSuchAlgorithmException("No trust manager found."); } mDefaultTrustManager = (X509TrustManager) trustManagers[0]; } - @Override - public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException - { + public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { // check client certificate //Logcat.d(""); mDefaultTrustManager.checkClientTrusted(certificates, authType); } - @Override - public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException - { + public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { boolean expectedCertificateFound = false; // manually verify certificate comparing encoded representation of the certificate - for(X509Certificate certificate : certificates) - { - try - { + for (X509Certificate certificate : certificates) { + try { String certHash = SHA1Base64Encoded(certificate.getEncoded()); //Logcat.d("certificate public key = " + certificate.getPublicKey().toString().substring(0, 100) + " ..."); //Logcat.d("certificate hash = " + certHash); //Logcat.d("---------------------------------------"); - if(certHash.trim().equals(ExampleConfig.SSL_CERTIFICATE_SHA1)) - { + if (certHash.trim().equals(ExampleConfig.SSL_CERTIFICATE_SHA1)) { // manual verification successfull expectedCertificateFound = true; } - } - catch(Exception e) - { + } catch (Exception e) { // manual verification failed throw new CertificateException("Failed to compare hashes of certificates."); } } - if(!expectedCertificateFound) - { + if (!expectedCertificateFound) { // if manual verification failed, throw exception throw new CertificateException("Expected certificate not found."); } @@ -92,16 +77,12 @@ public void checkServerTrusted(X509Certificate[] certificates, String authType) mDefaultTrustManager.checkServerTrusted(certificates, authType); } - @Override - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return mDefaultTrustManager.getAcceptedIssuers(); } - - private String SHA1Base64Encoded(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException - { + private String SHA1Base64Encoded(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(data); diff --git a/Src-SSL/java/rest/ssl/SelfSignedSslUtility.java b/Src-SSL/java/rest/ssl/SelfSignedSslUtility.java index 69c02c9..5d0e236 100644 --- a/Src-SSL/java/rest/ssl/SelfSignedSslUtility.java +++ b/Src-SSL/java/rest/ssl/SelfSignedSslUtility.java @@ -18,14 +18,10 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; - -public final class SelfSignedSslUtility -{ +public final class SelfSignedSslUtility { private SelfSignedSslUtility() {} - - public static void setupSslConnection(HttpsURLConnection connection, URL requestUrl) throws GeneralSecurityException - { + public static void setupSslConnection(HttpsURLConnection connection, URL requestUrl) throws GeneralSecurityException { SSLContext sslContext = createSslContext(); HostnameVerifier sslHostnameVerifier = createSslHostnameVerifier(requestUrl.getHost()); @@ -33,9 +29,7 @@ public static void setupSslConnection(HttpsURLConnection connection, URL request connection.setHostnameVerifier(sslHostnameVerifier); } - - public static SSLContext createSslContext() throws GeneralSecurityException - { + public static SSLContext createSslContext() throws GeneralSecurityException { KeyStore keyStore = loadKeyStore(); SelfSignedTrustManager selfSignedTrustManager = new SelfSignedTrustManager(keyStore); @@ -51,14 +45,10 @@ public static SSLContext createSslContext() throws GeneralSecurityException return context; } - - public static HostnameVerifier createSslHostnameVerifier(final String apiHostname) - { - HostnameVerifier hostnameVerifier = new HostnameVerifier() - { + public static HostnameVerifier createSslHostnameVerifier(final String apiHostname) { + HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override - public boolean verify(String hostname, SSLSession session) - { + public boolean verify(String hostname, SSLSession session) { //Logcat.d(hostname + " / " + apiHostname); return hostname.equals(apiHostname); } @@ -66,25 +56,17 @@ public boolean verify(String hostname, SSLSession session) return hostnameVerifier; } - - public static KeyStore loadKeyStore() - { - try - { + public static KeyStore loadKeyStore() { + try { KeyStore keyStore = KeyStore.getInstance("BKS"); InputStream in = ExampleApplication.getContext().getResources().openRawResource(R.raw.cert_keystore); - try - { + try { keyStore.load(in, ExampleConfig.SSL_KEYSTORE_PASSWORD.toCharArray()); - } - finally - { + } finally { in.close(); } return keyStore; - } - catch(Exception e) - { + } catch (Exception e) { throw new RuntimeException(e); } } diff --git a/Src-SSL/java/rest/ssl/SelfSignedTrustManager.java b/Src-SSL/java/rest/ssl/SelfSignedTrustManager.java index 811838b..fc9353c 100644 --- a/Src-SSL/java/rest/ssl/SelfSignedTrustManager.java +++ b/Src-SSL/java/rest/ssl/SelfSignedTrustManager.java @@ -19,20 +19,16 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; - // useful articles about trusting SSL certificates: // http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html // http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872#6378872 // http://nelenkov.blogspot.cz/2011/12/using-custom-certificate-trust-store-on.html -public class SelfSignedTrustManager implements X509TrustManager -{ +public class SelfSignedTrustManager implements X509TrustManager { private X509TrustManager mDefaultTrustManager = null; private X509TrustManager mLocalTrustManager = null; private X509Certificate[] mAcceptedIssuers; - - public SelfSignedTrustManager(KeyStore localKeyStore) throws NoSuchAlgorithmException, KeyStoreException - { + public SelfSignedTrustManager(KeyStore localKeyStore) throws NoSuchAlgorithmException, KeyStoreException { super(); // init factory @@ -42,8 +38,7 @@ public SelfSignedTrustManager(KeyStore localKeyStore) throws NoSuchAlgorithmExce // create default trust manager checking certificates signed with certificate authority TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - if(trustManagers.length == 0) - { + if (trustManagers.length == 0) { throw new NoSuchAlgorithmException("No trust manager found."); } mDefaultTrustManager = (X509TrustManager) trustManagers[0]; @@ -58,87 +53,66 @@ public SelfSignedTrustManager(KeyStore localKeyStore) throws NoSuchAlgorithmExce // // warning, this cycle takes a lot of time, maybe more than 1 sec // allIssuers.add(cert); // } - for(X509Certificate cert : mLocalTrustManager.getAcceptedIssuers()) - { + for (X509Certificate cert : mLocalTrustManager.getAcceptedIssuers()) { allIssuers.add(cert); } mAcceptedIssuers = allIssuers.toArray(new X509Certificate[allIssuers.size()]); } - @Override - public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException - { + public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { // check client certificate, first self signed, then default - try - { + try { //Logcat.d("localTrustManager"); mLocalTrustManager.checkClientTrusted(certificates, authType); - } - catch(CertificateException e) - { + } catch (CertificateException e) { //Logcat.d("defaultTrustManager"); mDefaultTrustManager.checkClientTrusted(certificates, authType); } } - @Override - public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException - { + public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { boolean expectedCertificateFound = false; // manually verify certificate comparing encoded representation of the certificate - for(X509Certificate certificate : certificates) - { - try - { + for (X509Certificate certificate : certificates) { + try { String certHash = SHA1Base64Encoded(certificate.getEncoded()); //Logcat.d("certificate public key = " + certificate.getPublicKey().toString().substring(0, 100) + " ..."); //Logcat.d("certificate hash = " + certHash); //Logcat.d("---------------------------------------"); - if(certHash.trim().equals(ExampleConfig.SSL_CERTIFICATE_SHA1)) - { + if (certHash.trim().equals(ExampleConfig.SSL_CERTIFICATE_SHA1)) { // manual verification successfull expectedCertificateFound = true; } - } - catch(Exception e) - { + } catch (Exception e) { // manual verification failed throw new CertificateException("Failed to compare hashes of certificates."); } } - if(!expectedCertificateFound) - { + if (!expectedCertificateFound) { // if manual verification failed, throw exception throw new CertificateException("Expected certificate not found."); } // if manual verification successfull, check server certificate, first self signed, then default - try - { + try { //Logcat.d("localTrustManager"); mLocalTrustManager.checkServerTrusted(certificates, authType); - } - catch(CertificateException e) - { + } catch (CertificateException e) { //Logcat.d("defaultTrustManager"); mDefaultTrustManager.checkServerTrusted(certificates, authType); } } - @Override - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return mAcceptedIssuers; } - - private String SHA1Base64Encoded(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException - { + private String SHA1Base64Encoded(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(data); @@ -146,59 +120,41 @@ private String SHA1Base64Encoded(byte[] data) throws NoSuchAlgorithmException, U return Base64.encodeToString(messageDigest, Base64.NO_WRAP); } - - private static class LocalStoreX509TrustManager implements X509TrustManager - { + private static class LocalStoreX509TrustManager implements X509TrustManager { private X509TrustManager mTrustManager; - - public LocalStoreX509TrustManager(KeyStore localTrustStore) - { - try - { + public LocalStoreX509TrustManager(KeyStore localTrustStore) { + try { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(localTrustStore); mTrustManager = findX509TrustManager(tmf); - if(mTrustManager == null) - { + if (mTrustManager == null) { throw new IllegalStateException("Couldn't find X509TrustManager."); } - } - catch(GeneralSecurityException e) - { + } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException - { + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { mTrustManager.checkClientTrusted(chain, authType); } - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException - { + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { mTrustManager.checkServerTrusted(chain, authType); } - @Override - public X509Certificate[] getAcceptedIssuers() - { + public X509Certificate[] getAcceptedIssuers() { return mTrustManager.getAcceptedIssuers(); } - - private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) - { + private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) { TrustManager tms[] = tmf.getTrustManagers(); - for(int i = 0; i < tms.length; i++) - { - if(tms[i] instanceof X509TrustManager) - { + for (int i = 0; i < tms.length; i++) { + if (tms[i] instanceof X509TrustManager) { return (X509TrustManager) tms[i]; } } diff --git a/Src-Service/java/service/ExampleIntentService.java b/Src-Service/java/service/ExampleIntentService.java index 9788b91..dc22438 100644 --- a/Src-Service/java/service/ExampleIntentService.java +++ b/Src-Service/java/service/ExampleIntentService.java @@ -5,66 +5,50 @@ import org.alfonz.utility.Logcat; - -public class ExampleIntentService extends IntentService -{ - public ExampleIntentService() - { +public class ExampleIntentService extends IntentService { + public ExampleIntentService() { super("ExampleIntentService"); setIntentRedelivery(false); // TODO: START_NOT_STICKY if false, START_REDELIVER_INTENT if true Logcat.d(""); } - @Override - public void onCreate() - { + public void onCreate() { Logcat.d(""); super.onCreate(); } - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { + public int onStartCommand(Intent intent, int flags, int startId) { Logcat.d(""); return super.onStartCommand(intent, flags, startId); } - @Override - protected void onHandleIntent(Intent intent) - { + protected void onHandleIntent(Intent intent) { // intent may be null if the service is being restarted - if(intent == null) return; + if (intent == null) return; Logcat.d("%d", intent.getIntExtra("arg", -1)); long endTime = System.currentTimeMillis() + 5L * 1000L; - while(System.currentTimeMillis() < endTime) - { - synchronized(this) - { - try - { + while (System.currentTimeMillis() < endTime) { + synchronized (this) { + try { // TODO: do something wait(endTime - System.currentTimeMillis()); - } - catch(InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } } } } - @Override - public void onDestroy() - { + public void onDestroy() { Logcat.d(""); super.onDestroy(); diff --git a/Src-Service/java/service/ExampleService.java b/Src-Service/java/service/ExampleService.java index 798e202..c1eb08b 100644 --- a/Src-Service/java/service/ExampleService.java +++ b/Src-Service/java/service/ExampleService.java @@ -10,16 +10,12 @@ import org.alfonz.utility.Logcat; - -public class ExampleService extends Service -{ +public class ExampleService extends Service { private Looper mServiceLooper; private ServiceHandler mServiceHandler; - @Override - public void onCreate() - { + public void onCreate() { Logcat.d(""); HandlerThread thread = new HandlerThread("ServiceStartArguments", Thread.NORM_PRIORITY); @@ -29,15 +25,12 @@ public void onCreate() mServiceHandler = new ServiceHandler(mServiceLooper); } - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { + public int onStartCommand(Intent intent, int flags, int startId) { Logcat.d(""); // intent may be null if the service is being restarted - if(intent != null) - { + if (intent != null) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.arg2 = intent.getIntExtra("arg", -1); @@ -47,47 +40,33 @@ public int onStartCommand(Intent intent, int flags, int startId) return START_STICKY; // TODO: START_STICKY, START_NOT_STICKY, START_REDELIVER_INTENT } - @Override - public IBinder onBind(Intent intent) - { + public IBinder onBind(Intent intent) { return null; } - @Override - public void onDestroy() - { + public void onDestroy() { Logcat.d(""); } - - private final class ServiceHandler extends Handler - { - public ServiceHandler(Looper looper) - { + private final class ServiceHandler extends Handler { + public ServiceHandler(Looper looper) { super(looper); } - @Override - public void handleMessage(Message msg) - { + public void handleMessage(Message msg) { Logcat.d("%d", msg.arg2); long endTime = System.currentTimeMillis() + 5L * 1000L; - while(System.currentTimeMillis() < endTime) - { - synchronized(this) - { - try - { + while (System.currentTimeMillis() < endTime) { + synchronized (this) { + try { // TODO: do something wait(endTime - System.currentTimeMillis()); - } - catch(InterruptedException e) - { + } catch (InterruptedException e) { e.printStackTrace(); } } diff --git a/Src-SlidingPaneLayout/java/activity/ExampleActivity.java b/Src-SlidingPaneLayout/java/activity/ExampleActivity.java index 2940eea..cd1f234 100644 --- a/Src-SlidingPaneLayout/java/activity/ExampleActivity.java +++ b/Src-SlidingPaneLayout/java/activity/ExampleActivity.java @@ -15,31 +15,23 @@ import com.example.fragment.DetailFragment; import com.example.fragment.ListingFragment; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { private SlidingPaneLayout mSlidingPaneLayout; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); setupActionBar(); setupSlidingPane(savedInstanceState); } - @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // action bar menu behavior - switch(item.getItemId()) - { + switch (item.getItemId()) { case android.R.id.home: - if(!mSlidingPaneLayout.isOpen()) - { + if (!mSlidingPaneLayout.isOpen()) { mSlidingPaneLayout.openPane(); return true; } @@ -49,9 +41,7 @@ public boolean onOptionsItemSelected(MenuItem item) } } - - private void setupActionBar() - { + private void setupActionBar() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); @@ -63,48 +53,35 @@ private void setupActionBar() bar.setHomeButtonEnabled(false); } - - private void setupSlidingPane(Bundle savedInstanceState) - { + private void setupSlidingPane(Bundle savedInstanceState) { // reference mSlidingPaneLayout = findViewById(R.id.example_sliding_pane_layout); // set slide listener - mSlidingPaneLayout.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() - { + mSlidingPaneLayout.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() { @Override - public void onPanelSlide(View view, float v) - { + public void onPanelSlide(View view, float v) { } - @Override - public void onPanelOpened(View view) - { + public void onPanelOpened(View view) { onSlidingPaneOpened(); } - @Override - public void onPanelClosed(View view) - { + public void onPanelClosed(View view) { onSlidingPaneClosed(); } }); mSlidingPaneLayout.openPane(); // set global layout listener - mSlidingPaneLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() - { + mSlidingPaneLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override - public void onGlobalLayout() - { - if(mSlidingPaneLayout.isSlideable() && !mSlidingPaneLayout.isOpen()) - { + public void onGlobalLayout() { + if (mSlidingPaneLayout.isSlideable() && !mSlidingPaneLayout.isOpen()) { onSlidingPaneClosed(); - } - else - { + } else { onSlidingPaneOpened(); } @@ -113,29 +90,23 @@ public void onGlobalLayout() }); // add fragments - if(savedInstanceState == null) - { + if (savedInstanceState == null) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.example_sliding_pane_left, ListingFragment.newInstance()).commitAllowingStateLoss(); fragmentManager.beginTransaction().replace(R.id.example_sliding_pane_right, DetailFragment.newInstance()).commitAllowingStateLoss(); } } - - private void onSlidingPaneOpened() - { + private void onSlidingPaneOpened() { Fragment fragmentLeft = getSupportFragmentManager().findFragmentById(R.id.example_sliding_pane_left); Fragment fragmentRight = getSupportFragmentManager().findFragmentById(R.id.example_sliding_pane_right); - if(mSlidingPaneLayout.isSlideable()) - { - if(fragmentLeft != null) fragmentLeft.setHasOptionsMenu(true); - if(fragmentRight != null) fragmentRight.setHasOptionsMenu(false); - } - else - { - if(fragmentLeft != null) fragmentLeft.setHasOptionsMenu(false); - if(fragmentRight != null) fragmentRight.setHasOptionsMenu(true); + if (mSlidingPaneLayout.isSlideable()) { + if (fragmentLeft != null) fragmentLeft.setHasOptionsMenu(true); + if (fragmentRight != null) fragmentRight.setHasOptionsMenu(false); + } else { + if (fragmentLeft != null) fragmentLeft.setHasOptionsMenu(false); + if (fragmentRight != null) fragmentRight.setHasOptionsMenu(true); } ActionBar bar = getSupportActionBar(); @@ -143,14 +114,12 @@ private void onSlidingPaneOpened() bar.setHomeButtonEnabled(false); } - - private void onSlidingPaneClosed() - { + private void onSlidingPaneClosed() { Fragment fragmentLeft = getSupportFragmentManager().findFragmentById(R.id.example_sliding_pane_left); Fragment fragmentRight = getSupportFragmentManager().findFragmentById(R.id.example_sliding_pane_right); - if(fragmentLeft != null) fragmentLeft.setHasOptionsMenu(false); - if(fragmentRight != null) fragmentRight.setHasOptionsMenu(true); + if (fragmentLeft != null) fragmentLeft.setHasOptionsMenu(false); + if (fragmentRight != null) fragmentRight.setHasOptionsMenu(true); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); diff --git a/Src-Splash-Screen/java/activity/ExampleActivity.java b/Src-Splash-Screen/java/activity/ExampleActivity.java index 72be11e..86d59ac 100644 --- a/Src-Splash-Screen/java/activity/ExampleActivity.java +++ b/Src-Splash-Screen/java/activity/ExampleActivity.java @@ -5,12 +5,9 @@ import com.example.R; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { setTheme(R.style.Theme_Example_Light); super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); diff --git a/Src-SwipeRefreshLayout/java/fragment/ListingFragment.java b/Src-SwipeRefreshLayout/java/fragment/ListingFragment.java index 77359b1..10a4328 100644 --- a/Src-SwipeRefreshLayout/java/fragment/ListingFragment.java +++ b/Src-SwipeRefreshLayout/java/fragment/ListingFragment.java @@ -12,23 +12,17 @@ import org.alfonz.utility.NetworkUtility; - -public class ListingFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener -{ +public class ListingFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_listing, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // pull to refresh @@ -38,10 +32,8 @@ public void onActivityCreated(Bundle savedInstanceState) showProgress(isProgress()); } - @Override - public void onRefresh() - { + public void onRefresh() { refreshData(); // // testing task @@ -72,26 +64,19 @@ public void onRefresh() // }.execute(); } - - public void refreshData() - { - if(NetworkUtility.isOnline(getActivity())) - { + public void refreshData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress popup showProgress(true); // TODO - } - else - { + } else { showProgress(false); Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show(); } } - - private void showProgress(boolean visible) - { + private void showProgress(boolean visible) { // show pull to refresh progress bar SwipeRefreshLayout listSwipeRefreshLayout = mRootView.findViewById(R.id.listing_swipe_refresh_layout); SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(android.R.id.empty); @@ -105,9 +90,7 @@ private void showProgress(boolean visible) setProgress(visible); } - - private void setupSwipeRefreshLayout() - { + private void setupSwipeRefreshLayout() { SwipeRefreshLayout listSwipeRefreshLayout = mRootView.findViewById(R.id.listing_swipe_refresh_layout); SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(android.R.id.empty); @@ -118,16 +101,12 @@ private void setupSwipeRefreshLayout() emptySwipeRefreshLayout.setOnRefreshListener(this); } - - private boolean isProgress() - { + private boolean isProgress() { // TODO return false; } - - private void setProgress(boolean progress) - { + private void setProgress(boolean progress) { // TODO } } diff --git a/Src-SwipeRefreshLayout/java/fragment/RecyclerFragment.java b/Src-SwipeRefreshLayout/java/fragment/RecyclerFragment.java index ea61bba..b51f4ff 100644 --- a/Src-SwipeRefreshLayout/java/fragment/RecyclerFragment.java +++ b/Src-SwipeRefreshLayout/java/fragment/RecyclerFragment.java @@ -12,23 +12,17 @@ import org.alfonz.utility.NetworkUtility; - -public class RecyclerFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener -{ +public class RecyclerFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private View mRootView; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_recycler, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // pull to refresh @@ -38,10 +32,8 @@ public void onActivityCreated(Bundle savedInstanceState) showProgress(isProgress()); } - @Override - public void onRefresh() - { + public void onRefresh() { refreshData(); // // testing task @@ -72,26 +64,19 @@ public void onRefresh() // }.execute(); } - - public void refreshData() - { - if(NetworkUtility.isOnline(getActivity())) - { + public void refreshData() { + if (NetworkUtility.isOnline(getActivity())) { // show progress popup showProgress(true); // TODO - } - else - { + } else { showProgress(false); Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show(); } } - - private void showProgress(boolean visible) - { + private void showProgress(boolean visible) { // show pull to refresh progress bar SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable); SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable); @@ -109,9 +94,7 @@ private void showProgress(boolean visible) setProgress(visible); } - - private void setupSwipeRefreshLayout() - { + private void setupSwipeRefreshLayout() { SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable); SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable); SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable); @@ -126,16 +109,12 @@ private void setupSwipeRefreshLayout() emptySwipeRefreshLayout.setOnRefreshListener(this); } - - private boolean isProgress() - { + private boolean isProgress() { // TODO return false; } - - private void setProgress(boolean progress) - { + private void setProgress(boolean progress) { // TODO } } diff --git a/Src-Timer/java/fragment/ExampleFragment.java b/Src-Timer/java/fragment/ExampleFragment.java index 51b89d8..61b0ed9 100644 --- a/Src-Timer/java/fragment/ExampleFragment.java +++ b/Src-Timer/java/fragment/ExampleFragment.java @@ -11,60 +11,46 @@ import org.alfonz.utility.Logcat; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private static final long TIMER_DELAY = 5000L; // in milliseconds private View mRootView; private Handler mTimerHandler; private Runnable mTimerRunnable; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupTimer(); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onResume() - { + public void onResume() { super.onResume(); // timer startTimer(); } - @Override - public void onPause() - { + public void onPause() { super.onPause(); // timer stopTimer(); } - - private void setupTimer() - { + private void setupTimer() { mTimerHandler = new Handler(); - mTimerRunnable = new Runnable() - { + mTimerRunnable = new Runnable() { @Override - public void run() - { + public void run() { Logcat.d("timer"); mTimerHandler.postDelayed(this, TIMER_DELAY); @@ -72,15 +58,11 @@ public void run() }; } - - private void startTimer() - { + private void startTimer() { mTimerHandler.postDelayed(mTimerRunnable, 0); } - - private void stopTimer() - { + private void stopTimer() { mTimerHandler.removeCallbacks(mTimerRunnable); } } diff --git a/Src-Version/java/activity/ExampleActivity.java b/Src-Version/java/activity/ExampleActivity.java index d9d26a9..4f1fa15 100644 --- a/Src-Version/java/activity/ExampleActivity.java +++ b/Src-Version/java/activity/ExampleActivity.java @@ -9,28 +9,22 @@ import org.alfonz.utility.Logcat; import org.alfonz.utility.VersionUtility; - -public class ExampleActivity extends AppCompatActivity -{ +public class ExampleActivity extends AppCompatActivity { @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); checkNewVersion(); checkRateCounter(); } - - private void checkNewVersion() - { + private void checkNewVersion() { Preferences preferences = new Preferences(); String currentVersion = VersionUtility.getVersionName(this); String lastVersion = preferences.getVersion(); // new version is available - if(!currentVersion.equals(lastVersion)) - { + if (!currentVersion.equals(lastVersion)) { // TODO: do something // set new version in preferences @@ -38,9 +32,7 @@ private void checkNewVersion() } } - - private void checkRateCounter() - { + private void checkRateCounter() { // get current rate counter Preferences preferences = new Preferences(); final int rateCounter = preferences.getRateCounter(); @@ -48,18 +40,14 @@ private void checkRateCounter() // check rate counter boolean showMessage = false; - if(rateCounter != -1) - { - if(rateCounter >= 10 && rateCounter % 10 == 0) showMessage = true; - } - else - { + if (rateCounter != -1) { + if (rateCounter >= 10 && rateCounter % 10 == 0) showMessage = true; + } else { return; } // show rate message - if(showMessage) - { + if (showMessage) { // TODO: show message // TODO: set rate counter to -1 } diff --git a/Src-ViewPager/java/activity/IndicatorActivity.java b/Src-ViewPager/java/activity/IndicatorActivity.java index 8baa758..4de886d9 100644 --- a/Src-ViewPager/java/activity/IndicatorActivity.java +++ b/Src-ViewPager/java/activity/IndicatorActivity.java @@ -8,35 +8,26 @@ import com.example.adapter.IndicatorFragmentPagerAdapter; import com.viewpagerindicator.CirclePageIndicator; - -public class IndicatorActivity extends AppCompatActivity -{ +public class IndicatorActivity extends AppCompatActivity { private IndicatorFragmentPagerAdapter mAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_indicator); setupView(); } - - private void setupView() - { + private void setupView() { // reference ViewPager viewPager = findViewById(R.id.indicator_pager); CirclePageIndicator circlePageIndicator = findViewById(R.id.indicator_indicator); // pager content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new IndicatorFragmentPagerAdapter(getSupportFragmentManager()); - } - else - { + } else { // refill adapter mAdapter.refill(); } diff --git a/Src-ViewPager/java/activity/PagerActivity.java b/Src-ViewPager/java/activity/PagerActivity.java index 18bdf2b..ed7c1c0 100644 --- a/Src-ViewPager/java/activity/PagerActivity.java +++ b/Src-ViewPager/java/activity/PagerActivity.java @@ -7,34 +7,25 @@ import com.example.R; import com.example.adapter.PagerFragmentPagerAdapter; - -public class PagerActivity extends AppCompatActivity -{ +public class PagerActivity extends AppCompatActivity { private PagerFragmentPagerAdapter mAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager); setupView(); } - - private void setupView() - { + private void setupView() { // reference ViewPager viewPager = findViewById(R.id.pager_pager); // pager content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new PagerFragmentPagerAdapter(getSupportFragmentManager()); - } - else - { + } else { // refill adapter mAdapter.refill(); } diff --git a/Src-ViewPager/java/activity/TabHostActivity.java b/Src-ViewPager/java/activity/TabHostActivity.java index 88f9b02..c3b78ea 100644 --- a/Src-ViewPager/java/activity/TabHostActivity.java +++ b/Src-ViewPager/java/activity/TabHostActivity.java @@ -9,23 +9,17 @@ import com.example.adapter.TabHostFragmentPagerAdapter; import com.example.fragment.ExampleFragment; - -public class TabHostActivity extends AppCompatActivity -{ +public class TabHostActivity extends AppCompatActivity { private TabHostFragmentPagerAdapter mAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabhost); setupView(); } - - private void setupView() - { + private void setupView() { // reference ViewPager viewPager = findViewById(R.id.tabhost_pager); TabHost tabHost = findViewById(android.R.id.tabhost); @@ -34,16 +28,13 @@ private void setupView() tabHost.setup(); // pager content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new TabHostFragmentPagerAdapter(this, tabHost, viewPager); mAdapter.addTab(tabHost.newTabSpec("tag0").setIndicator("Title 0"), ExampleFragment.class, null); mAdapter.addTab(tabHost.newTabSpec("tag1").setIndicator("Title 1"), ExampleFragment.class, null); mAdapter.addTab(tabHost.newTabSpec("tag2").setIndicator("Title 2"), ExampleFragment.class, null); - } - else - { + } else { // refill adapter mAdapter.refill(); } diff --git a/Src-ViewPager/java/activity/TabIndicatorActivity.java b/Src-ViewPager/java/activity/TabIndicatorActivity.java index c9f788b..e6a0398 100644 --- a/Src-ViewPager/java/activity/TabIndicatorActivity.java +++ b/Src-ViewPager/java/activity/TabIndicatorActivity.java @@ -8,35 +8,26 @@ import com.example.adapter.TabIndicatorFragmentPagerAdapter; import com.viewpagerindicator.TabPageIndicator; - -public class TabIndicatorActivity extends AppCompatActivity -{ +public class TabIndicatorActivity extends AppCompatActivity { private TabIndicatorFragmentPagerAdapter mAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabindicator); setupView(); } - - private void setupView() - { + private void setupView() { // reference ViewPager viewPager = findViewById(R.id.tabindicator_pager); TabPageIndicator tabPageIndicator = findViewById(R.id.tabindicator_indicator); // pager content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new TabIndicatorFragmentPagerAdapter(getSupportFragmentManager()); - } - else - { + } else { // refill adapter mAdapter.refill(); } diff --git a/Src-ViewPager/java/activity/TabLayoutActivity.java b/Src-ViewPager/java/activity/TabLayoutActivity.java index dfbd5cc..a6fce20 100644 --- a/Src-ViewPager/java/activity/TabLayoutActivity.java +++ b/Src-ViewPager/java/activity/TabLayoutActivity.java @@ -8,35 +8,26 @@ import com.example.R; import com.example.adapter.TabLayoutFragmentPagerAdapter; - -public class TabLayoutActivity extends AppCompatActivity -{ +public class TabLayoutActivity extends AppCompatActivity { private TabLayoutFragmentPagerAdapter mAdapter; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tablayout); setupView(); } - - private void setupView() - { + private void setupView() { // reference ViewPager viewPager = findViewById(R.id.tablayout_pager); TabLayout tabLayout = findViewById(R.id.tablayout_tabs); // pager content - if(mAdapter == null) - { + if (mAdapter == null) { // create adapter mAdapter = new TabLayoutFragmentPagerAdapter(getSupportFragmentManager()); - } - else - { + } else { // refill adapter mAdapter.refill(); } diff --git a/Src-ViewPager/java/adapter/IndicatorFragmentPagerAdapter.java b/Src-ViewPager/java/adapter/IndicatorFragmentPagerAdapter.java index b0c9046..efbfbae 100644 --- a/Src-ViewPager/java/adapter/IndicatorFragmentPagerAdapter.java +++ b/Src-ViewPager/java/adapter/IndicatorFragmentPagerAdapter.java @@ -6,47 +6,34 @@ import com.example.fragment.ExampleFragment; - public class IndicatorFragmentPagerAdapter extends FragmentPagerAdapter // TODO: use FragmentPagerAdapter or FragmentStatePagerAdapter { private static final int FRAGMENT_COUNT = 8; - - public IndicatorFragmentPagerAdapter(FragmentManager fragmentManager) - { + public IndicatorFragmentPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } - - public static String getFragmentTag(int viewPagerId, int position) - { + public static String getFragmentTag(int viewPagerId, int position) { return "android:switcher:" + viewPagerId + ":" + position; } - @Override - public int getCount() - { + public int getCount() { return FRAGMENT_COUNT; } - @Override - public Fragment getItem(int position) - { + public Fragment getItem(int position) { return ExampleFragment.newInstance(Integer.toString(position)); } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Fragment " + position; } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } } diff --git a/Src-ViewPager/java/adapter/PagerFragmentPagerAdapter.java b/Src-ViewPager/java/adapter/PagerFragmentPagerAdapter.java index a9270b9..ddf8f48 100644 --- a/Src-ViewPager/java/adapter/PagerFragmentPagerAdapter.java +++ b/Src-ViewPager/java/adapter/PagerFragmentPagerAdapter.java @@ -6,47 +6,34 @@ import com.example.fragment.ExampleFragment; - public class PagerFragmentPagerAdapter extends FragmentPagerAdapter // TODO: use FragmentPagerAdapter or FragmentStatePagerAdapter { private static final int FRAGMENT_COUNT = 8; - - public PagerFragmentPagerAdapter(FragmentManager fragmentManager) - { + public PagerFragmentPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } - - public static String getFragmentTag(int viewPagerId, int position) - { + public static String getFragmentTag(int viewPagerId, int position) { return "android:switcher:" + viewPagerId + ":" + position; } - @Override - public int getCount() - { + public int getCount() { return FRAGMENT_COUNT; } - @Override - public Fragment getItem(int position) - { + public Fragment getItem(int position) { return ExampleFragment.newInstance(Integer.toString(position)); } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Fragment " + position; } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } } diff --git a/Src-ViewPager/java/adapter/PagerLayoutPagerAdapter.java b/Src-ViewPager/java/adapter/PagerLayoutPagerAdapter.java index bc04c0c..ea11e3a 100644 --- a/Src-ViewPager/java/adapter/PagerLayoutPagerAdapter.java +++ b/Src-ViewPager/java/adapter/PagerLayoutPagerAdapter.java @@ -8,60 +8,44 @@ import com.example.R; - -public class PagerLayoutPagerAdapter extends PagerAdapter -{ +public class PagerLayoutPagerAdapter extends PagerAdapter { private static final int LAYOUT_COUNT = 8; private Context mContext; - - public PagerLayoutPagerAdapter(Context context) - { + public PagerLayoutPagerAdapter(Context context) { mContext = context; } - @Override - public Object instantiateItem(ViewGroup container, int position) - { + public Object instantiateItem(ViewGroup container, int position) { LayoutInflater inflater = LayoutInflater.from(mContext); ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.fragment_example, container, false); container.addView(layout); return layout; } - @Override - public void destroyItem(ViewGroup container, int position, Object object) - { + public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } - @Override - public boolean isViewFromObject(View view, Object object) - { + public boolean isViewFromObject(View view, Object object) { return view == object; } - @Override - public int getCount() - { + public int getCount() { return LAYOUT_COUNT; } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Layout " + position; } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } } diff --git a/Src-ViewPager/java/adapter/TabHostFragmentPagerAdapter.java b/Src-ViewPager/java/adapter/TabHostFragmentPagerAdapter.java index d7ea950..8faf5c9 100644 --- a/Src-ViewPager/java/adapter/TabHostFragmentPagerAdapter.java +++ b/Src-ViewPager/java/adapter/TabHostFragmentPagerAdapter.java @@ -16,7 +16,6 @@ import java.util.ArrayList; import java.util.List; - public class TabHostFragmentPagerAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener // TODO: use FragmentPagerAdapter or FragmentStatePagerAdapter { private final Context mContext; @@ -24,9 +23,7 @@ public class TabHostFragmentPagerAdapter extends FragmentPagerAdapter implements private final ViewPager mViewPager; private final List mTabList = new ArrayList<>(); - - public TabHostFragmentPagerAdapter(FragmentActivity activity, TabHost tabHost, ViewPager viewPager) - { + public TabHostFragmentPagerAdapter(FragmentActivity activity, TabHost tabHost, ViewPager viewPager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; @@ -36,47 +33,35 @@ public TabHostFragmentPagerAdapter(FragmentActivity activity, TabHost tabHost, V mViewPager.addOnPageChangeListener(this); } - - public static String getFragmentTag(int viewPagerId, int position) - { + public static String getFragmentTag(int viewPagerId, int position) { return "android:switcher:" + viewPagerId + ":" + position; } - @Override - public int getCount() - { + public int getCount() { return mTabList.size(); } - @Override - public Fragment getItem(int position) - { + public Fragment getItem(int position) { //TabInfo info = mTabList.get(position); //return Fragment.instantiate(mContext, info.clss.getName(), info.args); return ExampleFragment.newInstance(Integer.toString(position)); // TODO } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Fragment " + position; } - @Override - public void onTabChanged(String tabId) - { + public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } - @Override - public void onPageSelected(int position) - { + public void onPageSelected(int position) { // this hack tries to prevent this from pulling focus out of our ViewPager TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); @@ -85,21 +70,15 @@ public void onPageSelected(int position) widget.setDescendantFocusability(oldFocusability); } - @Override - public void onPageScrollStateChanged(int state) - { + public void onPageScrollStateChanged(int state) { } - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) - { + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } - - public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) - { + public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); @@ -108,43 +87,31 @@ public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) notifyDataSetChanged(); } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } - - public static final class TabInfo - { + public static final class TabInfo { private final String mTag; private final Class mClss; private final Bundle mArgs; - - TabInfo(String tag, Class clss, Bundle args) - { + TabInfo(String tag, Class clss, Bundle args) { mTag = tag; mClss = clss; mArgs = args; } } - - public static class DummyTabFactory implements TabHost.TabContentFactory - { + public static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; - - public DummyTabFactory(Context context) - { + public DummyTabFactory(Context context) { mContext = context; } - @Override - public View createTabContent(String tag) - { + public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); diff --git a/Src-ViewPager/java/adapter/TabIndicatorFragmentPagerAdapter.java b/Src-ViewPager/java/adapter/TabIndicatorFragmentPagerAdapter.java index da2cace..66aa3c0 100644 --- a/Src-ViewPager/java/adapter/TabIndicatorFragmentPagerAdapter.java +++ b/Src-ViewPager/java/adapter/TabIndicatorFragmentPagerAdapter.java @@ -6,47 +6,34 @@ import com.example.fragment.ExampleFragment; - public class TabIndicatorFragmentPagerAdapter extends FragmentPagerAdapter // TODO: use FragmentPagerAdapter or FragmentStatePagerAdapter { private static final int FRAGMENT_COUNT = 8; - - public TabIndicatorFragmentPagerAdapter(FragmentManager fragmentManager) - { + public TabIndicatorFragmentPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } - - public static String getFragmentTag(int viewPagerId, int position) - { + public static String getFragmentTag(int viewPagerId, int position) { return "android:switcher:" + viewPagerId + ":" + position; } - @Override - public int getCount() - { + public int getCount() { return FRAGMENT_COUNT; } - @Override - public Fragment getItem(int position) - { + public Fragment getItem(int position) { return ExampleFragment.newInstance(Integer.toString(position)); } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Fragment " + position; } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } } diff --git a/Src-ViewPager/java/adapter/TabLayoutFragmentPagerAdapter.java b/Src-ViewPager/java/adapter/TabLayoutFragmentPagerAdapter.java index 9e7f139..1cf7ea4 100644 --- a/Src-ViewPager/java/adapter/TabLayoutFragmentPagerAdapter.java +++ b/Src-ViewPager/java/adapter/TabLayoutFragmentPagerAdapter.java @@ -6,47 +6,34 @@ import com.example.fragment.ExampleFragment; - public class TabLayoutFragmentPagerAdapter extends FragmentPagerAdapter // TODO: use FragmentPagerAdapter or FragmentStatePagerAdapter { private static final int FRAGMENT_COUNT = 8; - - public TabLayoutFragmentPagerAdapter(FragmentManager fragmentManager) - { + public TabLayoutFragmentPagerAdapter(FragmentManager fragmentManager) { super(fragmentManager); } - - public static String getFragmentTag(int viewPagerId, int position) - { + public static String getFragmentTag(int viewPagerId, int position) { return "android:switcher:" + viewPagerId + ":" + position; } - @Override - public int getCount() - { + public int getCount() { return FRAGMENT_COUNT; } - @Override - public Fragment getItem(int position) - { + public Fragment getItem(int position) { return ExampleFragment.newInstance(Integer.toString(position)); } - @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return "Fragment " + position; } - - public void refill() - { + public void refill() { notifyDataSetChanged(); } } diff --git a/Src-ViewPager/java/fragment/ExampleFragment.java b/Src-ViewPager/java/fragment/ExampleFragment.java index 091b4a4..a983ee3 100644 --- a/Src-ViewPager/java/fragment/ExampleFragment.java +++ b/Src-ViewPager/java/fragment/ExampleFragment.java @@ -9,17 +9,13 @@ import com.example.R; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private static final String ARGUMENT_EXAMPLE = "example"; private String mExample; private View mRootView; - - public static ExampleFragment newInstance(String example) - { + public static ExampleFragment newInstance(String example) { ExampleFragment fragment = new ExampleFragment(); // arguments @@ -30,48 +26,36 @@ public static ExampleFragment newInstance(String example) return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // handle fragment arguments Bundle arguments = getArguments(); - if(arguments != null) - { + if (arguments != null) { handleArguments(arguments); } } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - @Override - public void onActivityCreated(Bundle savedInstanceState) - { + public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupView(); } - - private void handleArguments(Bundle arguments) - { - if(arguments.containsKey(ARGUMENT_EXAMPLE)) - { + private void handleArguments(Bundle arguments) { + if (arguments.containsKey(ARGUMENT_EXAMPLE)) { mExample = (String) arguments.get(ARGUMENT_EXAMPLE); } } - - private void setupView() - { + private void setupView() { // reference TextView nameTextView = mRootView.findViewById(R.id.example_name); diff --git a/Src-ViewPager/java/widget/FixedScroller.java b/Src-ViewPager/java/widget/FixedScroller.java index c87c797..d621555 100644 --- a/Src-ViewPager/java/widget/FixedScroller.java +++ b/Src-ViewPager/java/widget/FixedScroller.java @@ -8,35 +8,24 @@ import java.lang.reflect.Field; - // source: http://stackoverflow.com/questions/8155257/slowing-speed-of-viewpager-controller-in-android/ -public class FixedScroller extends Scroller -{ +public class FixedScroller extends Scroller { private int mFixedDuration = 100; - - public FixedScroller(Context context) - { + public FixedScroller(Context context) { super(context); } - - public FixedScroller(Context context, Interpolator interpolator) - { + public FixedScroller(Context context, Interpolator interpolator) { super(context, interpolator); } - - public FixedScroller(Context context, Interpolator interpolator, boolean flywheel) - { + public FixedScroller(Context context, Interpolator interpolator, boolean flywheel) { super(context, interpolator, flywheel); } - - public static void setViewPagerDuration(ViewPager viewPager, int duration) - { - try - { + public static void setViewPagerDuration(ViewPager viewPager, int duration) { + try { Field field = ViewPager.class.getDeclaredField("mScroller"); field.setAccessible(true); @@ -44,43 +33,29 @@ public static void setViewPagerDuration(ViewPager viewPager, int duration) fixedScroller.setFixedDuration(duration); field.set(viewPager, fixedScroller); - } - catch(NoSuchFieldException e) - { - } - catch(IllegalArgumentException e) - { - } - catch(IllegalAccessException e) - { + } catch (NoSuchFieldException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { } } - @Override - public void startScroll(int startX, int startY, int dx, int dy, int duration) - { + public void startScroll(int startX, int startY, int dx, int dy, int duration) { // Ignore received duration, use fixed one instead super.startScroll(startX, startY, dx, dy, mFixedDuration); } - @Override - public void startScroll(int startX, int startY, int dx, int dy) - { + public void startScroll(int startX, int startY, int dx, int dy) { // Ignore received duration, use fixed one instead super.startScroll(startX, startY, dx, dy, mFixedDuration); } - - public int getFixedDuration() - { + public int getFixedDuration() { return mFixedDuration; } - - public void setFixedDuration(int duration) - { + public void setFixedDuration(int duration) { mFixedDuration = duration; } } diff --git a/Src-WebView/java/fragment/ExampleFragment.java b/Src-WebView/java/fragment/ExampleFragment.java index 0dd38cf..07014c9 100644 --- a/Src-WebView/java/fragment/ExampleFragment.java +++ b/Src-WebView/java/fragment/ExampleFragment.java @@ -25,31 +25,23 @@ import org.alfonz.view.StatefulLayout; - -public class ExampleFragment extends Fragment -{ +public class ExampleFragment extends Fragment { private View mRootView; private StatefulLayout mStatefulLayout; private String mUrl = "about:blank"; - @Override - public void onCreate(Bundle savedInstanceState) - { + public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_example, container, false); return mRootView; } - - private void setupView() - { + private void setupView() { // reference final WebView webView = mRootView.findViewById(R.id.example_webview); @@ -68,12 +60,9 @@ private void setupView() webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo // webview hardware acceleration - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) - { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); - } - else - { + } else { webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } @@ -95,54 +84,39 @@ private void setupView() webView.loadUrl(mUrl); } - - private void controlBack() - { + private void controlBack() { final WebView webView = mRootView.findViewById(R.id.example_webview); - if(webView.canGoBack()) webView.goBack(); + if (webView.canGoBack()) webView.goBack(); } - - private void controlForward() - { + private void controlForward() { final WebView webView = mRootView.findViewById(R.id.example_webview); - if(webView.canGoForward()) webView.goForward(); + if (webView.canGoForward()) webView.goForward(); } - - private void controlStop() - { + private void controlStop() { final WebView webView = mRootView.findViewById(R.id.example_webview); webView.stopLoading(); } - - private void controlReload() - { + private void controlReload() { final WebView webView = mRootView.findViewById(R.id.example_webview); webView.reload(); } - - private class MyWebViewClient extends WebViewClient - { + private class MyWebViewClient extends WebViewClient { @Override - public void onPageFinished(WebView view, String url) - { - if(getActivity() != null) - { + public void onPageFinished(WebView view, String url) { + if (getActivity() != null) { Toast.makeText(getActivity(), mUrl, Toast.LENGTH_LONG).show(); mStatefulLayout.showContent(); } } - @SuppressWarnings("deprecation") @Override - public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) - { - if(getActivity() != null) - { + public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { + if (getActivity() != null) { final WebView webView = mRootView.findViewById(R.id.example_webview); webView.loadUrl("about:blank"); Toast.makeText(getActivity(), errorCode + ": " + description, Toast.LENGTH_LONG).show(); @@ -150,46 +124,33 @@ public void onReceivedError(WebView view, int errorCode, String description, Str } } - @TargetApi(Build.VERSION_CODES.M) @Override - public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) - { + public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { // forward to deprecated method onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString()); } - @Override - public boolean shouldOverrideUrlLoading(WebView view, String url) - { - if(url != null && (url.startsWith("http://") || url.startsWith("https://"))) - { + public boolean shouldOverrideUrlLoading(WebView view, String url) { + if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; - } - else - { + } else { return false; } } } - - private class WebViewOnKeyListener implements OnKeyListener - { + private class WebViewOnKeyListener implements OnKeyListener { @Override - public boolean onKey(View v, int keyCode, KeyEvent event) - { - if(event.getAction() == KeyEvent.ACTION_DOWN) - { + public boolean onKey(View v, int keyCode, KeyEvent event) { + if (event.getAction() == KeyEvent.ACTION_DOWN) { WebView webView = (WebView) v; - switch(keyCode) - { + switch (keyCode) { case KeyEvent.KEYCODE_BACK: - if(webView.canGoBack()) - { + if (webView.canGoBack()) { webView.goBack(); return true; } @@ -201,18 +162,13 @@ public boolean onKey(View v, int keyCode, KeyEvent event) } } - - private class WebViewOnTouchListener implements OnTouchListener - { + private class WebViewOnTouchListener implements OnTouchListener { @Override - public boolean onTouch(View v, MotionEvent event) - { - switch(event.getAction()) - { + public boolean onTouch(View v, MotionEvent event) { + switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: - if(!v.hasFocus()) - { + if (!v.hasFocus()) { v.requestFocus(); } break;