From 1d644f8516ad2ac09ed910d79d5b0a065a490e4e Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 23 Mar 2016 20:57:43 +0100 Subject: [PATCH 01/24] Updated build tools --- SWADroid.iml | 2 +- SWADroid/build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SWADroid.iml b/SWADroid.iml index 813e2f2ff..e6de05ec6 100644 --- a/SWADroid.iml +++ b/SWADroid.iml @@ -13,7 +13,7 @@ - + \ No newline at end of file diff --git a/SWADroid/build.gradle b/SWADroid/build.gradle index 975c899a6..a053bc22b 100644 --- a/SWADroid/build.gradle +++ b/SWADroid/build.gradle @@ -8,7 +8,7 @@ ext { android { compileSdkVersion 23 - buildToolsVersion "23.0.2" + buildToolsVersion "23.0.3" defaultConfig { applicationId "es.ugr.swad.swadroid" versionCode gitVersionCode From 4211759a82dc9eb0fe49f8aa60ae1329275373da Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Thu, 12 May 2016 22:35:11 +0200 Subject: [PATCH 02/24] Enabled Android Studio's "Dex In Process" for Faster App Builds --- SWADroid/build.gradle | 6 ++++++ gradle.properties | 1 + 2 files changed, 7 insertions(+) diff --git a/SWADroid/build.gradle b/SWADroid/build.gradle index a053bc22b..234066496 100644 --- a/SWADroid/build.gradle +++ b/SWADroid/build.gradle @@ -9,6 +9,12 @@ ext { android { compileSdkVersion 23 buildToolsVersion "23.0.3" + + dexOptions { + maxProcessCount=2 + javaMaxHeapSize "2g" + } + defaultConfig { applicationId "es.ugr.swad.swadroid" versionCode gitVersionCode diff --git a/gradle.properties b/gradle.properties index 1d3591c8a..7f722e5f4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,6 +11,7 @@ # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 +org.gradle.jvmargs=-Xmx2048m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit From 4ba0f05a2d307acee53564aff426bfef50d249ff Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Sun, 5 Jun 2016 16:46:32 +0200 Subject: [PATCH 03/24] Replaced ZXing library with ZXing Android Embedded library --- .gitignore | 3 +- SWADroid/build.gradle | 15 +- SWADroid/src/main/AndroidManifest.xml | 37 +- .../zxing/client/android/BeepManager.java | 110 ----- .../zxing/client/android/CaptureActivity.java | 456 ------------------ .../android/CaptureActivityHandler.java | 134 ----- .../google/zxing/client/android/Contents.java | 114 ----- .../client/android/DecodeFormatManager.java | 102 ---- .../zxing/client/android/DecodeHandler.java | 106 ---- .../zxing/client/android/DecodeThread.java | 97 ---- .../zxing/client/android/FinishListener.java | 51 -- .../zxing/client/android/InactivityTimer.java | 110 ----- .../zxing/client/android/IntentSource.java | 26 - .../google/zxing/client/android/Intents.java | 265 ---------- .../android/PlanarYUVLuminanceSource.java | 142 ------ .../client/android/PreferencesActivity.java | 94 ---- .../ViewfinderResultPointCallback.java | 35 -- .../zxing/client/android/ViewfinderView.java | 196 -------- .../android/camera/AutoFocusCallback.java | 52 -- .../camera/CameraConfigurationManager.java | 181 ------- .../client/android/camera/CameraManager.java | 281 ----------- .../android/camera/PreviewCallback.java | 56 --- .../client/android/encode/ContactEncoder.java | 93 ---- .../client/android/encode/Formatter.java | 28 -- .../android/encode/MECARDContactEncoder.java | 96 ---- .../client/android/encode/QRCodeEncoder.java | 362 -------------- .../android/encode/VCardContactEncoder.java | 90 ---- .../swadroid/analytics/SWADroidTracker.java | 33 +- .../ugr/swad/swadroid/gui/ImageFactory.java | 9 +- .../ugr/swad/swadroid/gui/MenuActivity.java | 8 +- .../gui/MenuExpandableListActivity.java | 8 +- .../swad/swadroid/modules/qr/GenerateQR.java | 37 +- .../rollcall/ContinuousCaptureActivity.java | 196 ++++++++ .../modules/rollcall/UsersActivity.java | 72 +-- .../modules/rollcall/UsersCursorAdapter.java | 22 - .../java/es/ugr/swad/swadroid/utils/QR.java | 47 -- .../src/main/res/layout/continuous_scan.xml | 13 + build.gradle | 4 +- 38 files changed, 316 insertions(+), 3465 deletions(-) delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/BeepManager.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivity.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivityHandler.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/Contents.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/DecodeFormatManager.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/DecodeHandler.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/DecodeThread.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/FinishListener.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/InactivityTimer.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/IntentSource.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/Intents.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/PlanarYUVLuminanceSource.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/PreferencesActivity.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderResultPointCallback.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderView.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/camera/AutoFocusCallback.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraConfigurationManager.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraManager.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/camera/PreviewCallback.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/encode/ContactEncoder.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/encode/Formatter.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/encode/MECARDContactEncoder.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/encode/QRCodeEncoder.java delete mode 100644 SWADroid/src/main/java/com/google/zxing/client/android/encode/VCardContactEncoder.java create mode 100644 SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java delete mode 100644 SWADroid/src/main/java/es/ugr/swad/swadroid/utils/QR.java create mode 100644 SWADroid/src/main/res/layout/continuous_scan.xml diff --git a/.gitignore b/.gitignore index 395beef9a..1922c65fe 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,5 @@ import-summary.txt local.properties /SWADroid/SWADroid-SWADroid.iml /SWADroid.iml -app/lint.xml \ No newline at end of file +app/lint.xml +/SWADroid/google-services.json diff --git a/SWADroid/build.gradle b/SWADroid/build.gradle index 234066496..21283ab7c 100644 --- a/SWADroid/build.gradle +++ b/SWADroid/build.gradle @@ -56,11 +56,12 @@ android { } dependencies { - compile 'com.android.support:support-v4:latest.release' - compile 'com.android.support:appcompat-v7:latest.release' - compile 'com.google.android.gms:play-services-analytics:latest.release' - compile 'com.google.code.ksoap2-android:ksoap2-android:latest.release' - compile 'commons-io:commons-io:latest.release' - compile 'com.nostra13.universalimageloader:universal-image-loader:latest.release' - compile 'com.google.zxing:core:2.1' + compile 'com.android.support:support-v4:23.4.0' + compile 'com.android.support:appcompat-v7:23.4.0' + compile 'com.google.android.gms:play-services-analytics:9.0.2' + compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.1' + compile 'commons-io:commons-io:2.5' + compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' + compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar' + compile 'com.google.zxing:core:3.2.1' } \ No newline at end of file diff --git a/SWADroid/src/main/AndroidManifest.xml b/SWADroid/src/main/AndroidManifest.xml index adbeddee2..b6a10314f 100644 --- a/SWADroid/src/main/AndroidManifest.xml +++ b/SWADroid/src/main/AndroidManifest.xml @@ -101,20 +101,14 @@ android:theme="@style/Theme.AppCompat.Translucent" > + android:theme="@style/Theme.AppCompat.Translucent"> - - - - - + android:name=".modules.groups.Groups" + android:label="@string/myGroupsModuleLabel" + android:theme="@style/Theme.AppCompat.Translucent" > + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/BeepManager.java b/SWADroid/src/main/java/com/google/zxing/client/android/BeepManager.java deleted file mode 100644 index 8380b6ee4..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/BeepManager.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.res.AssetFileDescriptor; -import android.media.AudioManager; -import android.media.MediaPlayer; -import android.os.Vibrator; -import android.preference.PreferenceManager; -import android.util.Log; - -import java.io.IOException; - -/** - * Manages beeps and vibrations for {@link CaptureActivity}. - */ -final class BeepManager { - - private static final String TAG = BeepManager.class.getSimpleName(); - - private static final float BEEP_VOLUME = 0.10f; - private static final long VIBRATE_DURATION = 200L; - - private final Activity activity; - private MediaPlayer mediaPlayer; - private boolean playBeep; - private boolean vibrate; - - BeepManager(Activity activity, int sound) { - this.activity = activity; - this.mediaPlayer = null; - updatePrefs(sound); - } - - void updatePrefs(int sound) { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); - playBeep = shouldBeep(prefs, activity); - vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false); - if (playBeep && mediaPlayer == null) { - // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud, - // so we now play on the music stream. - activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); - mediaPlayer = buildMediaPlayer(activity, sound); - } - } - - void playBeepSoundAndVibrate() { - if (playBeep && mediaPlayer != null) { - mediaPlayer.start(); - } - if (vibrate) { - Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); - vibrator.vibrate(VIBRATE_DURATION); - } - } - - private static boolean shouldBeep(SharedPreferences prefs, Context activity) { - boolean shouldPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true); - if (shouldPlayBeep) { - // See if sound settings overrides this - AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE); - if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { - shouldPlayBeep = false; - } - } - return shouldPlayBeep; - } - - private static MediaPlayer buildMediaPlayer(Context activity, int sound) { - MediaPlayer mediaPlayer = new MediaPlayer(); - mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); - // When the beep has finished playing, rewind to queue up another one. - mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(MediaPlayer player) { - player.seekTo(0); - } - }); - - AssetFileDescriptor file = activity.getResources().openRawResourceFd(sound); - try { - mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); - file.close(); - mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); - mediaPlayer.prepare(); - } catch (IOException ioe) { - Log.w(TAG, ioe); - mediaPlayer = null; - } - return mediaPlayer; - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivity.java b/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivity.java deleted file mode 100644 index 8545bc439..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivity.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.util.Log; -import android.view.Gravity; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.SurfaceHolder; -import android.view.SurfaceView; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.Result; -import com.google.zxing.ResultPoint; -import com.google.zxing.client.android.camera.CameraManager; - -import java.io.IOException; -import java.util.Collection; - -import es.ugr.swad.swadroid.R; -import es.ugr.swad.swadroid.database.DataBaseHelper; -import es.ugr.swad.swadroid.gui.ImageFactory; -import es.ugr.swad.swadroid.model.User; -import es.ugr.swad.swadroid.modules.rollcall.UsersActivity; -import es.ugr.swad.swadroid.utils.Crypto; -import es.ugr.swad.swadroid.utils.Utils; - -/** - * This activity opens the camera and does the actual scanning on a background thread. It draws a - * viewfinder to help the user place the barcode correctly, shows feedback as the image processing - * is happening, and then overlays the results when a scan is successful. - * - * @author dswitkin@google.com (Daniel Switkin) - * @author Sean Owen - * @author Antonio Aguilera Malagon (aguilerin@gmail.com) - * @author Juan Miguel Boyero Corral (juanmi1982@gmail.com) - */ -public class CaptureActivity extends Activity implements SurfaceHolder.Callback { - /** - * Text size in scan window - */ - private static final int SCAN_TEXT_SIZE = 18; - - private static final String TAG = CaptureActivity.class.getSimpleName(); - - private static final long BULK_MODE_SCAN_DELAY_MS = 1000L; - - private static final int[] sounds = {R.raw.beep, R.raw.klaxon}; - - private CameraManager cameraManager; - private CaptureActivityHandler handler; - private Result savedResultToShow; - private ViewfinderView viewfinderView; - private TextView statusView; - private View resultView; - private Result lastResult; - private boolean hasSurface; - private IntentSource source; - private Collection decodeFormats; - private String characterSet; - private InactivityTimer inactivityTimer; - private BeepManager beepManager; - private static DataBaseHelper dbHelper; - private static Crypto crypto; - - ViewfinderView getViewfinderView() { - return viewfinderView; - } - - public Handler getHandler() { - return handler; - } - - CameraManager getCameraManager() { - return cameraManager; - } - - @Override - public void onCreate(Bundle icicle) { - super.onCreate(icicle); - - Window window = getWindow(); - window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - setContentView(R.layout.capture); - - hasSurface = false; - inactivityTimer = new InactivityTimer(this); - - try { - //Initialize database - dbHelper = new DataBaseHelper(this); - crypto = new Crypto(this, dbHelper.getDBKey()); - } catch (Exception ex) { - Log.e(TAG, ex.getMessage(), ex); - } - } - - @Override - protected void onResume() { - super.onResume(); - - // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't - // want to open the camera driver and measure the screen size if we're going to show the help on - // first launch. That led to bugs where the scanning rectangle was the wrong size and partially - // off screen. - cameraManager = new CameraManager(getApplication()); - - viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); - viewfinderView.setCameraManager(cameraManager); - - resultView = findViewById(R.id.result_view); - statusView = (TextView) findViewById(R.id.status_view); - - handler = null; - lastResult = null; - - resetStatusView(); - - SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); - SurfaceHolder surfaceHolder = surfaceView.getHolder(); - if (hasSurface) { - // The activity was paused but not stopped, so the surface still exists. Therefore - // surfaceCreated() won't be called, so init the camera here. - initCamera(surfaceHolder); - } else { - // Install the callback and wait for surfaceCreated() to init the camera. - surfaceHolder.addCallback(this); - surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); - } - - inactivityTimer.onResume(); - - Intent intent = getIntent(); - - source = IntentSource.NONE; - decodeFormats = null; - characterSet = null; - - if (intent != null) { - String action = intent.getAction(); - - if (Intents.Scan.ACTION.equals(action)) { - // Scan the formats the intent requested, and return the result to the calling activity. - source = IntentSource.NATIVE_APP_INTENT; - decodeFormats = DecodeFormatManager.parseDecodeFormats(intent); - - if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) { - int width = intent.getIntExtra(Intents.Scan.WIDTH, 0); - int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0); - if (width > 0 && height > 0) { - cameraManager.setManualFramingRect(width, height); - } - } - String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE); - if (customPromptMessage != null) { - statusView.setText(customPromptMessage); - } - } - characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET); - } - } - - @Override - protected void onPause() { - if (handler != null) { - handler.quitSynchronously(); - handler = null; - } - inactivityTimer.onPause(); - cameraManager.closeDriver(); - if (!hasSurface) { - SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); - SurfaceHolder surfaceHolder = surfaceView.getHolder(); - surfaceHolder.removeCallback(this); - } - super.onPause(); - } - - @Override - protected void onDestroy() { - inactivityTimer.shutdown(); - super.onDestroy(); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { - if (source == IntentSource.NATIVE_APP_INTENT) { - setResult(RESULT_OK); - finish(); - return true; - } else if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) { - restartPreviewAfterDelay(0L); - return true; - } - } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) { - // Handle these events so they don't launch the Camera app - return true; - } - return super.onKeyDown(keyCode, event); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - } - - private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) { - // Bitmap isn't used yet -- will be used soon - if (handler == null) { - savedResultToShow = result; - } else { - if (result != null) { - savedResultToShow = result; - } - if (savedResultToShow != null) { - Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow); - handler.sendMessage(message); - } - savedResultToShow = null; - } - } - - @Override - public void surfaceCreated(SurfaceHolder holder) { - if (holder == null) { - Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); - } - if (!hasSurface) { - hasSurface = true; - initCamera(holder); - } - } - - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - hasSurface = false; - } - - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - - } - - /** - * A valid barcode has been found, so give an indication of success and show the results. - * - * @param rawResult The contents of the barcode. - * @param barcode A greyscale bitmap of the camera data which was decoded. - */ - public void handleDecode(Result rawResult, Bitmap barcode) { - String messageResult; - int iconResult; - int soundResult; - String qrContent = rawResult.toString(); - boolean validContent = Utils.isValidNickname(qrContent); - User u = dbHelper.getUser("userNickname", crypto.encrypt(qrContent.substring(1))); - - inactivityTimer.onActivity(); - lastResult = rawResult; - - if (validContent) { - if ((u != null) && dbHelper.isUserEnrolledEvent(UsersActivity.getEventCode(), "userCode", - String.valueOf(u.getId()))) { - Log.d(TAG, "isUserEnrolledEvent=" + dbHelper.isUserEnrolledEvent(UsersActivity.getEventCode(), "userCode", - crypto.encrypt(String.valueOf(u.getId())))); - //Mark student as present in the event - dbHelper.insertAttendance(u.getId(), UsersActivity.getEventCode(), true); - - //Mark event status as "pending" - dbHelper.updateEventStatus(UsersActivity.getEventCode(), "pending"); - - messageResult = getString(R.string.scan_valid_student); - iconResult = R.drawable.ok; - soundResult = sounds[0]; // Positive sound - - messageResult += "\n\n" - + getString(R.string.scan_id) + ": " + u.getUserID() + "\n" - + getString(R.string.scan_name) + ": " + u.getUserFirstname() + " " - + u.getUserSurname1() + " " + u.getUserSurname2(); - } else { - // There is no user with that nickname - messageResult = getString(R.string.scan_data_not_found); - iconResult = R.drawable.not_ok; - soundResult = sounds[1]; // Negative sound - } - } else { - // Not detected any valid ID or nickname - messageResult = getString(R.string.scan_not_valid_code); - iconResult = R.drawable.not_ok; - soundResult = sounds[1]; // Negative sound - } - - drawResultPoints(barcode, rawResult); - - // Play the appropriate sound - beepManager = new BeepManager(this, soundResult); - beepManager.playBeepSoundAndVibrate(); - - // Show photo of student - LayoutInflater inflater = getLayoutInflater(); - View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); - ImageView image = (ImageView) layout.findViewById(R.id.image); - - if (u != null) { - ImageFactory.displayImage(getApplicationContext(), u.getUserPhoto(), image, true, true, - R.drawable.usr_bl, R.drawable.usr_bl, R.drawable.usr_bl); - } - - // Show appropriate icon - ImageView icon = (ImageView) layout.findViewById(R.id.icon); - icon.setImageResource(iconResult); - - // Show appropriate message - TextView toastText = (TextView) layout.findViewById(R.id.text); - toastText.setText(messageResult); - toastText.setGravity(Gravity.CENTER_VERTICAL); - toastText.setTextSize(SCAN_TEXT_SIZE); - - final Toast toast = new Toast(getApplicationContext()); - toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); - toast.setDuration(Toast.LENGTH_SHORT); - toast.setView(layout); - toast.show(); - - // Hide message after delay - if(BULK_MODE_SCAN_DELAY_MS < 2000L) { - new Handler().postDelayed(new Runnable() { - @Override - public void run() { - toast.cancel(); - } - }, BULK_MODE_SCAN_DELAY_MS); - } - - // Wait a moment or else it will scan the same barcode continuously about 3 times - restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS); - } - - /** - * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode. - * - * @param barcode A bitmap of the captured image. - * @param rawResult The decoded results which contains the points to draw. - */ - private void drawResultPoints(Bitmap barcode, Result rawResult) { - ResultPoint[] points = rawResult.getResultPoints(); - if (points != null && points.length > 0) { - Canvas canvas = new Canvas(barcode); - Paint paint = new Paint(); - paint.setColor(getResources().getColor(R.color.result_image_border)); - paint.setStrokeWidth(3.0f); - paint.setStyle(Paint.Style.STROKE); - Rect border = new Rect(2, 2, barcode.getWidth() - 2, barcode.getHeight() - 2); - canvas.drawRect(border, paint); - - paint.setColor(getResources().getColor(R.color.result_points)); - if (points.length == 2) { - paint.setStrokeWidth(4.0f); - drawLine(canvas, paint, points[0], points[1]); - } else if (points.length == 4 && - (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || - rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) { - // Hacky special case -- draw two lines, for the barcode and metadata - drawLine(canvas, paint, points[0], points[1]); - drawLine(canvas, paint, points[2], points[3]); - } else { - paint.setStrokeWidth(10.0f); - for (ResultPoint point : points) { - canvas.drawPoint(point.getX(), point.getY(), paint); - } - } - } - } - - private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b) { - canvas.drawLine(a.getX(), a.getY(), b.getX(), b.getY(), paint); - } - - private void initCamera(SurfaceHolder surfaceHolder) { - try { - cameraManager.openDriver(surfaceHolder); - // Creating the handler starts the preview, which can also throw a RuntimeException. - if (handler == null) { - handler = new CaptureActivityHandler(this, decodeFormats, characterSet, cameraManager); - } - decodeOrStoreSavedBitmap(null, null); - } catch (IOException ioe) { - Log.w(TAG, ioe); - displayFrameworkBugMessageAndExit(); - } catch (RuntimeException e) { - // Barcode Scanner has seen crashes in the wild of this variety: - // java.?lang.?RuntimeException: Fail to connect to camera service - Log.w(TAG, "Unexpected error initializing camera", e); - displayFrameworkBugMessageAndExit(); - } - } - - private void displayFrameworkBugMessageAndExit() { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(getString(R.string.app_name)); - builder.setMessage(getString(R.string.msg_camera_framework_bug)); - builder.setPositiveButton(R.string.button_ok, new FinishListener(this)); - builder.setOnCancelListener(new FinishListener(this)); - builder.show(); - } - - void restartPreviewAfterDelay(long delayMS) { - if (handler != null) { - handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS); - } - resetStatusView(); - } - - private void resetStatusView() { - resultView.setVisibility(View.GONE); - statusView.setText(R.string.msg_default_status); - statusView.setVisibility(View.VISIBLE); - viewfinderView.setVisibility(View.VISIBLE); - lastResult = null; - } - - public void drawViewfinder() { - viewfinderView.drawViewfinder(); - } -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivityHandler.java b/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivityHandler.java deleted file mode 100644 index f3222ec69..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/CaptureActivityHandler.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.app.Activity; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.util.Log; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.Result; -import com.google.zxing.client.android.camera.CameraManager; - -import java.util.Collection; - -import es.ugr.swad.swadroid.R; - -/** - * This class handles all the messaging which comprises the state machine for capture. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class CaptureActivityHandler extends Handler { - - private static final String TAG = CaptureActivityHandler.class.getSimpleName(); - - private final CaptureActivity activity; - private final DecodeThread decodeThread; - private State state; - private final CameraManager cameraManager; - - private enum State { - PREVIEW, - SUCCESS, - DONE - } - - CaptureActivityHandler(CaptureActivity activity, - Collection decodeFormats, - String characterSet, - CameraManager cameraManager) { - this.activity = activity; - decodeThread = new DecodeThread(activity, decodeFormats, characterSet, - new ViewfinderResultPointCallback(activity.getViewfinderView())); - decodeThread.start(); - state = State.SUCCESS; - - // Start ourselves capturing previews and decoding. - this.cameraManager = cameraManager; - cameraManager.startPreview(); - restartPreviewAndDecode(); - } - - @Override - public void handleMessage(Message message) { - if (message.what == R.id.auto_focus) { - //Log.d(TAG, "Got auto-focus message"); - // When one auto focus pass finishes, start another. This is the closest thing to - // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do. - if (state == State.PREVIEW) { - cameraManager.requestAutoFocus(this, R.id.auto_focus); - } - } else if (message.what == R.id.restart_preview) { - Log.d(TAG, "Got restart preview message"); - restartPreviewAndDecode(); - } else if (message.what == R.id.decode_succeeded) { - Log.d(TAG, "Got decode succeeded message"); - state = State.SUCCESS; - Bundle bundle = message.getData(); - Bitmap barcode = bundle == null ? null : - (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP); - activity.handleDecode((Result) message.obj, barcode); - } else if (message.what == R.id.decode_failed) { - // We're decoding as fast as possible, so when one decode fails, start another. - state = State.PREVIEW; - cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); - } else if (message.what == R.id.return_scan_result) { - Log.d(TAG, "Got return scan result message"); - activity.setResult(Activity.RESULT_OK, (Intent) message.obj); - activity.finish(); - } else if (message.what == R.id.launch_product_query) { - Log.d(TAG, "Got product query message"); - String url = (String) message.obj; - Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); - intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); - activity.startActivity(intent); - } - } - - public void quitSynchronously() { - state = State.DONE; - cameraManager.stopPreview(); - Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit); - quit.sendToTarget(); - try { - // Wait at most half a second; should be enough time, and onPause() will timeout quickly - decodeThread.join(500L); - } catch (InterruptedException e) { - // continue - } - - // Be absolutely sure we don't send any queued up messages - removeMessages(R.id.decode_succeeded); - removeMessages(R.id.decode_failed); - } - - private void restartPreviewAndDecode() { - if (state == State.SUCCESS) { - state = State.PREVIEW; - cameraManager.requestPreviewFrame(decodeThread.getHandler(), R.id.decode); - cameraManager.requestAutoFocus(this, R.id.auto_focus); - activity.drawViewfinder(); - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/Contents.java b/SWADroid/src/main/java/com/google/zxing/client/android/Contents.java deleted file mode 100644 index 5d3d1436a..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/Contents.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.provider.ContactsContract; - -/** - * The set of constants to use when sending Barcode Scanner an Intent which requests a barcode - * to be encoded. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class Contents { - private Contents() { - } - - public static final class Type { - /** - * Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string - * must include "http://" or "https://". - */ - public static final String TEXT = "TEXT_TYPE"; - - /** - * An email type. Use Intent.putExtra(DATA, string) where string is the email address. - */ - public static final String EMAIL = "EMAIL_TYPE"; - - /** - * Use Intent.putExtra(DATA, string) where string is the phone number to call. - */ - public static final String PHONE = "PHONE_TYPE"; - - /** - * An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS. - */ - public static final String SMS = "SMS_TYPE"; - - /** - * A contact. Send a request to encode it as follows: - *

- * import android.provider.Contacts; - *

- * Intent intent = new Intent(Intents.Encode.ACTION); - * intent.putExtra(Intents.Encode.TYPE, CONTACT); - * Bundle bundle = new Bundle(); - * bundle.putString(Contacts.Intents.Insert.NAME, "Jenny"); - * bundle.putString(Contacts.Intents.Insert.PHONE, "8675309"); - * bundle.putString(Contacts.Intents.Insert.EMAIL, "jenny@the80s.com"); - * bundle.putString(Contacts.Intents.Insert.POSTAL, "123 Fake St. San Francisco, CA 94102"); - * intent.putExtra(Intents.Encode.DATA, bundle); - */ - public static final String CONTACT = "CONTACT_TYPE"; - - /** - * A geographic location. Use as follows: - * Bundle bundle = new Bundle(); - * bundle.putFloat("LAT", latitude); - * bundle.putFloat("LONG", longitude); - * intent.putExtra(Intents.Encode.DATA, bundle); - */ - public static final String LOCATION = "LOCATION_TYPE"; - - private Type() { - } - } - - public static final String URL_KEY = "URL_KEY"; - - public static final String NOTE_KEY = "NOTE_KEY"; - - /** - * When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple - * phone numbers and addresses. - */ - public static final String[] PHONE_KEYS = { - ContactsContract.Intents.Insert.PHONE, - ContactsContract.Intents.Insert.SECONDARY_PHONE, - ContactsContract.Intents.Insert.TERTIARY_PHONE - }; - - public static final String[] PHONE_TYPE_KEYS = { - ContactsContract.Intents.Insert.PHONE_TYPE, - ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE, - ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE - }; - - public static final String[] EMAIL_KEYS = { - ContactsContract.Intents.Insert.EMAIL, - ContactsContract.Intents.Insert.SECONDARY_EMAIL, - ContactsContract.Intents.Insert.TERTIARY_EMAIL - }; - - public static final String[] EMAIL_TYPE_KEYS = { - ContactsContract.Intents.Insert.EMAIL_TYPE, - ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE, - ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE - }; - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeFormatManager.java b/SWADroid/src/main/java/com/google/zxing/client/android/DecodeFormatManager.java deleted file mode 100644 index 524e75d07..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeFormatManager.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.content.Intent; -import android.net.Uri; - -import com.google.zxing.BarcodeFormat; - -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; -import java.util.regex.Pattern; - -final class DecodeFormatManager { - - private static final Pattern COMMA_PATTERN = Pattern.compile(","); - - private static final Collection PRODUCT_FORMATS; - static final Collection ONE_D_FORMATS; - static final Collection QR_CODE_FORMATS = EnumSet.of(BarcodeFormat.QR_CODE); - static final Collection DATA_MATRIX_FORMATS = EnumSet.of(BarcodeFormat.DATA_MATRIX); - - static { - PRODUCT_FORMATS = EnumSet.of(BarcodeFormat.UPC_A, - BarcodeFormat.UPC_E, - BarcodeFormat.EAN_13, - BarcodeFormat.EAN_8, - BarcodeFormat.RSS_14); - ONE_D_FORMATS = EnumSet.of(BarcodeFormat.CODE_39, - BarcodeFormat.CODE_93, - BarcodeFormat.CODE_128, - BarcodeFormat.ITF); - ONE_D_FORMATS.addAll(PRODUCT_FORMATS); - } - - private DecodeFormatManager() { - } - - static Collection parseDecodeFormats(Intent intent) { - List scanFormats = null; - String scanFormatsString = intent.getStringExtra(Intents.Scan.FORMATS); - if (scanFormatsString != null) { - scanFormats = Arrays.asList(COMMA_PATTERN.split(scanFormatsString)); - } - return parseDecodeFormats(scanFormats, intent.getStringExtra(Intents.Scan.MODE)); - } - - static Collection parseDecodeFormats(Uri inputUri) { - List formats = inputUri.getQueryParameters(Intents.Scan.FORMATS); - if (formats != null && formats.size() == 1 && formats.get(0) != null) { - formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0))); - } - return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE)); - } - - private static Collection parseDecodeFormats(Iterable scanFormats, - String decodeMode) { - if (scanFormats != null) { - Collection formats = EnumSet.noneOf(BarcodeFormat.class); - try { - for (String format : scanFormats) { - formats.add(BarcodeFormat.valueOf(format)); - } - return formats; - } catch (IllegalArgumentException iae) { - // ignore it then - } - } - if (decodeMode != null) { - if (Intents.Scan.PRODUCT_MODE.equals(decodeMode)) { - return PRODUCT_FORMATS; - } - if (Intents.Scan.QR_CODE_MODE.equals(decodeMode)) { - return QR_CODE_FORMATS; - } - if (Intents.Scan.DATA_MATRIX_MODE.equals(decodeMode)) { - return DATA_MATRIX_FORMATS; - } - if (Intents.Scan.ONE_D_MODE.equals(decodeMode)) { - return ONE_D_FORMATS; - } - } - return null; - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeHandler.java b/SWADroid/src/main/java/com/google/zxing/client/android/DecodeHandler.java deleted file mode 100644 index 6fd806a42..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeHandler.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.os.Message; -import android.util.Log; - -import com.google.zxing.BinaryBitmap; -import com.google.zxing.DecodeHintType; -import com.google.zxing.MultiFormatReader; -import com.google.zxing.ReaderException; -import com.google.zxing.Result; -import com.google.zxing.common.HybridBinarizer; - -import java.util.Map; - -import es.ugr.swad.swadroid.R; - -final class DecodeHandler extends Handler { - - private static final String TAG = DecodeHandler.class.getSimpleName(); - - private final CaptureActivity activity; - private final MultiFormatReader multiFormatReader; - private boolean running = true; - - DecodeHandler(CaptureActivity activity, Map hints) { - multiFormatReader = new MultiFormatReader(); - multiFormatReader.setHints(hints); - this.activity = activity; - } - - @Override - public void handleMessage(Message message) { - if (!running) { - return; - } - if (message.what == R.id.decode) { - decode((byte[]) message.obj, message.arg1, message.arg2); - } else if (message.what == R.id.quit) { - running = false; - Looper.myLooper().quit(); - } - } - - /** - * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency, - * reuse the same reader objects from one decode to the next. - * - * @param data The YUV preview frame. - * @param width The width of the preview frame. - * @param height The height of the preview frame. - */ - private void decode(byte[] data, int width, int height) { - long start = System.currentTimeMillis(); - Result rawResult = null; - PlanarYUVLuminanceSource source = activity.getCameraManager().buildLuminanceSource(data, width, height); - if (source != null) { - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - try { - rawResult = multiFormatReader.decodeWithState(bitmap); - } catch (ReaderException re) { - // continue - } finally { - multiFormatReader.reset(); - } - } - - Handler handler = activity.getHandler(); - if (rawResult != null) { - // Don't log the barcode contents for security. - long end = System.currentTimeMillis(); - Log.d(TAG, "Found barcode in " + (end - start) + " ms"); - if (handler != null) { - Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult); - Bundle bundle = new Bundle(); - bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap()); - message.setData(bundle); - message.sendToTarget(); - } - } else { - if (handler != null) { - Message message = Message.obtain(handler, R.id.decode_failed); - message.sendToTarget(); - } - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeThread.java b/SWADroid/src/main/java/com/google/zxing/client/android/DecodeThread.java deleted file mode 100644 index 25bf4ed29..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/DecodeThread.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.content.SharedPreferences; -import android.os.Handler; -import android.os.Looper; -import android.preference.PreferenceManager; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.DecodeHintType; -import com.google.zxing.ResultPointCallback; - -import java.util.Collection; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -/** - * This thread does all the heavy lifting of decoding the images. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -final class DecodeThread extends Thread { - - public static final String BARCODE_BITMAP = "barcode_bitmap"; - - private final CaptureActivity activity; - private final Map hints; - private Handler handler; - private final CountDownLatch handlerInitLatch; - - DecodeThread(CaptureActivity activity, - Collection decodeFormats, - String characterSet, - ResultPointCallback resultPointCallback) { - - this.activity = activity; - handlerInitLatch = new CountDownLatch(1); - - hints = new EnumMap(DecodeHintType.class); - - // The prefs can't change while the thread is running, so pick them up once here. - if (decodeFormats == null || decodeFormats.isEmpty()) { - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); - decodeFormats = EnumSet.noneOf(BarcodeFormat.class); - if (prefs.getBoolean(PreferencesActivity.KEY_DECODE_1D, false)) { - decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS); - } - if (prefs.getBoolean(PreferencesActivity.KEY_DECODE_QR, false)) { - decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS); - } - if (prefs.getBoolean(PreferencesActivity.KEY_DECODE_DATA_MATRIX, false)) { - decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS); - } - } - hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); - - if (characterSet != null) { - hints.put(DecodeHintType.CHARACTER_SET, characterSet); - } - hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback); - } - - Handler getHandler() { - try { - handlerInitLatch.await(); - } catch (InterruptedException ie) { - // continue? - } - return handler; - } - - @Override - public void run() { - Looper.prepare(); - handler = new DecodeHandler(activity, hints); - handlerInitLatch.countDown(); - Looper.loop(); - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/FinishListener.java b/SWADroid/src/main/java/com/google/zxing/client/android/FinishListener.java deleted file mode 100644 index 8816f78eb..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/FinishListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.app.Activity; -import android.content.DialogInterface; - -/** - * Simple listener used to exit the app in a few cases. - * - * @author Sean Owen - */ -public final class FinishListener - implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable { - - private final Activity activityToFinish; - - public FinishListener(Activity activityToFinish) { - this.activityToFinish = activityToFinish; - } - - @Override - public void onCancel(DialogInterface dialogInterface) { - run(); - } - - @Override - public void onClick(DialogInterface dialogInterface, int i) { - run(); - } - - @Override - public void run() { - activityToFinish.finish(); - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/InactivityTimer.java b/SWADroid/src/main/java/com/google/zxing/client/android/InactivityTimer.java deleted file mode 100644 index 501b43d8f..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/InactivityTimer.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.app.Activity; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; - -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -/** - * Finishes an activity after a period of inactivity if the device is on battery power. - */ -final class InactivityTimer { - - private static final int INACTIVITY_DELAY_SECONDS = 5 * 60; - - private final ScheduledExecutorService inactivityTimer = - Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory()); - private final Activity activity; - private ScheduledFuture inactivityFuture = null; - private final BroadcastReceiver powerStatusReceiver = new PowerStatusReceiver(); - - InactivityTimer(Activity activity) { - this.activity = activity; - onActivity(); - } - - void onActivity() { - cancel(); - if (!inactivityTimer.isShutdown()) { - try { - inactivityFuture = inactivityTimer.schedule(new FinishListener(activity), - INACTIVITY_DELAY_SECONDS, - TimeUnit.SECONDS); - } catch (RejectedExecutionException ree) { - // surprising, but could be normal if for some reason the implementation just doesn't - // think it can shcedule again. Since this time-out is non-essential, just forget it - } - } - } - - public void onPause() { - cancel(); - activity.unregisterReceiver(powerStatusReceiver); - } - - public void onResume() { - activity.registerReceiver(powerStatusReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); - onActivity(); - } - - private void cancel() { - ScheduledFuture future = inactivityFuture; - if (future != null) { - future.cancel(true); - inactivityFuture = null; - } - } - - void shutdown() { - cancel(); - inactivityTimer.shutdown(); - } - - private static final class DaemonThreadFactory implements ThreadFactory { - @Override - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable); - thread.setDaemon(true); - return thread; - } - } - - private final class PowerStatusReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { - // 0 indicates that we're on battery - // In Android 2.0+, use BatteryManager.EXTRA_PLUGGED - int batteryPlugged = intent.getIntExtra("plugged", -1); - if (batteryPlugged > 0) { - InactivityTimer.this.cancel(); - } - } - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/IntentSource.java b/SWADroid/src/main/java/com/google/zxing/client/android/IntentSource.java deleted file mode 100644 index c166e4836..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/IntentSource.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (C) 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -enum IntentSource { - - NATIVE_APP_INTENT, - PRODUCT_SEARCH_LINK, - ZXING_LINK, - NONE - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/Intents.java b/SWADroid/src/main/java/com/google/zxing/client/android/Intents.java deleted file mode 100644 index 9b0eed132..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/Intents.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -/** - * This class provides the constants to use when sending an Intent to Barcode Scanner. - * These strings are effectively API and cannot be changed. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class Intents { - private Intents() { - } - - public static final class Scan { - /** - * Send this intent to open the Barcodes app in scanning mode, find a barcode, and return - * the results. - */ - public static final String ACTION = "es.ugr.swad.swadroid.android.SCAN"; - - /** - * By default, sending this will decode all barcodes that we understand. However it - * may be useful to limit scanning to certain formats. Use - * {@link android.content.Intent#putExtra(String, String)} with one of the values below. - *

- * Setting this is effectively shorthand for setting explicit formats with {@link #FORMATS}. - * It is overridden by that setting. - */ - public static final String MODE = "SCAN_MODE"; - - /** - * Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get - * prices, reviews, etc. for products. - */ - public static final String PRODUCT_MODE = "PRODUCT_MODE"; - - /** - * Decode only 1D barcodes. - */ - public static final String ONE_D_MODE = "ONE_D_MODE"; - - /** - * Decode only QR codes. - */ - public static final String QR_CODE_MODE = "QR_CODE_MODE"; - - /** - * Decode only Data Matrix codes. - */ - public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE"; - - /** - * Comma-separated list of formats to scan for. The values must match the names of - * {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}. - * Example: "EAN_13,EAN_8,QR_CODE". This overrides {@link #MODE}. - */ - public static final String FORMATS = "SCAN_FORMATS"; - - /** - * @see com.google.zxing.DecodeHintType#CHARACTER_SET - */ - public static final String CHARACTER_SET = "CHARACTER_SET"; - - /** - * Optional parameters to specify the width and height of the scanning rectangle in pixels. - * The app will try to honor these, but will clamp them to the size of the preview frame. - * You should specify both or neither, and pass the size as an int. - */ - public static final String WIDTH = "SCAN_WIDTH"; - public static final String HEIGHT = "SCAN_HEIGHT"; - - /** - * Desired duration in milliseconds for which to pause after a successful scan before - * returning to the calling intent. Specified as a long, not an integer! - * For example: 1000L, not 1000. - */ - public static final String RESULT_DISPLAY_DURATION_MS = "RESULT_DISPLAY_DURATION_MS"; - - /** - * Prompt to show on-screen when scanning by intent. Specified as a {@link String}. - */ - public static final String PROMPT_MESSAGE = "PROMPT_MESSAGE"; - - /** - * If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to - * {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)} - * of the app which requested the scan via - * {@link android.app.Activity#startActivityForResult(android.content.Intent, int)} - * The barcodes contents can be retrieved with - * {@link android.content.Intent#getStringExtra(String)}. - * If the user presses Back, the result code will be {@link android.app.Activity#RESULT_CANCELED}. - */ - public static final String RESULT = "SCAN_RESULT"; - - /** - * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT} - * to determine which barcode format was found. - * See {@link com.google.zxing.BarcodeFormat} for possible values. - */ - public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT"; - - /** - * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION} - * to return the content of any UPC extension barcode that was also found. Only applicable - * to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13} - * formats. - */ - public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION"; - - /** - * Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES} - * to get a {@code byte[]} of raw bytes in the barcode, if available. - */ - public static final String RESULT_BYTES = "SCAN_RESULT_BYTES"; - - /** - * Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available. - * Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}. - */ - public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION"; - - /** - * Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available. - * Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}. - */ - public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL"; - - /** - * Prefix for keys that map to the values of {@link com.google.zxing.ResultMetadataType#BYTE_SEGMENTS}, - * if available. The actual values will be set under a series of keys formed by adding 0, 1, 2, ... - * to this prefix. So the first byte segment is under key "SCAN_RESULT_BYTE_SEGMENTS_0" for example. - * Call {@link android.content.Intent#getByteArrayExtra(String)} with these keys. - */ - public static final String RESULT_BYTE_SEGMENTS_PREFIX = "SCAN_RESULT_BYTE_SEGMENTS_"; - - /** - * Setting this to false will not save scanned codes in the history. Specified as a {@code boolean}. - */ - public static final String SAVE_HISTORY = "SAVE_HISTORY"; - - private Scan() { - } - } - - @SuppressWarnings("unused") - private static final class History { - - public static final String ITEM_NUMBER = "ITEM_NUMBER"; - - private History() { - } - } - - public static final class Encode { - /** - * Send this intent to encode a piece of data as a QR code and display it full screen, so - * that another person can scan the barcode from your screen. - */ - public static final String ACTION = "com.google.zxing.client.android.ENCODE"; - - /** - * The data to encode. Use {@link android.content.Intent#putExtra(String, String)} or - * {@link android.content.Intent#putExtra(String, android.os.Bundle)}, - * depending on the type and format specified. Non-QR Code formats should - * just use a String here. For QR Code, see Contents for details. - */ - public static final String DATA = "ENCODE_DATA"; - - /** - * The type of data being supplied if the format is QR Code. Use - * {@link android.content.Intent#putExtra(String, String)} with one of {@link Contents.Type}. - */ - public static final String TYPE = "ENCODE_TYPE"; - - /** - * The barcode format to be displayed. If this isn't specified or is blank, - * it defaults to QR Code. Use {@link android.content.Intent#putExtra(String, String)}, where - * format is one of {@link com.google.zxing.BarcodeFormat}. - */ - public static final String FORMAT = "ENCODE_FORMAT"; - - /** - * Normally the contents of the barcode are displayed to the user in a TextView. Setting this - * boolean to false will hide that TextView, showing only the encode barcode. - */ - public static final String SHOW_CONTENTS = "ENCODE_SHOW_CONTENTS"; - - private Encode() { - } - } - - @SuppressWarnings("unused") - private static final class SearchBookContents { - /** - * Use Google Book Search to search the contents of the book provided. - */ - public static final String ACTION = "com.google.zxing.client.android.SEARCH_BOOK_CONTENTS"; - - /** - * The book to search, identified by ISBN number. - */ - public static final String ISBN = "ISBN"; - - /** - * An optional field which is the text to search for. - */ - public static final String QUERY = "QUERY"; - - private SearchBookContents() { - } - } - - @SuppressWarnings("unused") - private static final class WifiConnect { - /** - * Internal intent used to trigger connection to a wi-fi network. - */ - public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT"; - - /** - * The network to connect to, all the configuration provided here. - */ - public static final String SSID = "SSID"; - - /** - * The network to connect to, all the configuration provided here. - */ - public static final String TYPE = "TYPE"; - - /** - * The network to connect to, all the configuration provided here. - */ - public static final String PASSWORD = "PASSWORD"; - - private WifiConnect() { - } - } - - @SuppressWarnings("unused") - private static final class Share { - /** - * Give the user a choice of items to encode as a barcode, then render it as a QR Code and - * display onscreen for a friend to scan with their phone. - */ - public static final String ACTION = "com.google.zxing.client.android.SHARE"; - - private Share() { - } - } -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/PlanarYUVLuminanceSource.java b/SWADroid/src/main/java/com/google/zxing/client/android/PlanarYUVLuminanceSource.java deleted file mode 100644 index 563f90dcd..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/PlanarYUVLuminanceSource.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2009 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.graphics.Bitmap; - -import com.google.zxing.LuminanceSource; - -/** - * This object extends LuminanceSource around an array of YUV data returned from the camera driver, - * with the option to crop to a rectangle within the full data. This can be used to exclude - * superfluous pixels around the perimeter and speed up decoding. - *

- * It works for any pixel format where the Y channel is planar and appears first, including - * YCbCr_420_SP and YCbCr_422_SP. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class PlanarYUVLuminanceSource extends LuminanceSource { - - private final byte[] yuvData; - private final int dataWidth; - private final int dataHeight; - private final int left; - private final int top; - - public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top, - int width, int height, boolean reverseHorizontal) { - super(width, height); - - if (left + width > dataWidth || top + height > dataHeight) { - throw new IllegalArgumentException("Crop rectangle does not fit within image data."); - } - - this.yuvData = yuvData; - this.dataWidth = dataWidth; - this.dataHeight = dataHeight; - this.left = left; - this.top = top; - if (reverseHorizontal) { - reverseHorizontal(width, height); - } - } - - @Override - public byte[] getRow(int y, byte[] row) { - if (y < 0 || y >= getHeight()) { - throw new IllegalArgumentException("Requested row is outside the image: " + y); - } - int width = getWidth(); - if (row == null || row.length < width) { - row = new byte[width]; - } - int offset = (y + top) * dataWidth + left; - System.arraycopy(yuvData, offset, row, 0, width); - return row; - } - - @Override - public byte[] getMatrix() { - int width = getWidth(); - int height = getHeight(); - - // If the caller asks for the entire underlying image, save the copy and give them the - // original data. The docs specifically warn that result.length must be ignored. - if (width == dataWidth && height == dataHeight) { - return yuvData; - } - - int area = width * height; - byte[] matrix = new byte[area]; - int inputOffset = top * dataWidth + left; - - // If the width matches the full width of the underlying data, perform a single copy. - if (width == dataWidth) { - System.arraycopy(yuvData, inputOffset, matrix, 0, area); - return matrix; - } - - // Otherwise copy one cropped row at a time. - byte[] yuv = yuvData; - for (int y = 0; y < height; y++) { - int outputOffset = y * width; - System.arraycopy(yuv, inputOffset, matrix, outputOffset, width); - inputOffset += dataWidth; - } - return matrix; - } - - @Override - public boolean isCropSupported() { - return true; - } - - public Bitmap renderCroppedGreyscaleBitmap() { - int width = getWidth(); - int height = getHeight(); - int[] pixels = new int[width * height]; - byte[] yuv = yuvData; - int inputOffset = top * dataWidth + left; - - for (int y = 0; y < height; y++) { - int outputOffset = y * width; - for (int x = 0; x < width; x++) { - int grey = yuv[inputOffset + x] & 0xff; - pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101); - } - inputOffset += dataWidth; - } - - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.setPixels(pixels, 0, width, 0, 0, width, height); - return bitmap; - } - - private void reverseHorizontal(int width, int height) { - byte[] yuvData = this.yuvData; - for (int y = 0, rowStart = top * dataWidth + left; y < height; y++, rowStart += dataWidth) { - int middle = rowStart + width / 2; - for (int x1 = rowStart, x2 = rowStart + width - 1; x1 < middle; x1++, x2--) { - byte temp = yuvData[x1]; - yuvData[x1] = yuvData[x2]; - yuvData[x2] = temp; - } - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/PreferencesActivity.java b/SWADroid/src/main/java/com/google/zxing/client/android/PreferencesActivity.java deleted file mode 100644 index ec75bbe89..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/PreferencesActivity.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.os.Bundle; -import android.preference.CheckBoxPreference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceScreen; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * The main settings activity. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class PreferencesActivity extends PreferenceActivity - implements OnSharedPreferenceChangeListener { - - public static final String KEY_DECODE_1D = "preferences_decode_1D"; - public static final String KEY_DECODE_QR = "preferences_decode_QR"; - public static final String KEY_DECODE_DATA_MATRIX = "preferences_decode_Data_Matrix"; - public static final String KEY_CUSTOM_PRODUCT_SEARCH = "preferences_custom_product_search"; - - public static final String KEY_REVERSE_IMAGE = "preferences_reverse_image"; - public static final String KEY_PLAY_BEEP = "preferences_play_beep"; - public static final String KEY_VIBRATE = "preferences_vibrate"; - public static final String KEY_COPY_TO_CLIPBOARD = "preferences_copy_to_clipboard"; - public static final String KEY_FRONT_LIGHT = "preferences_front_light"; - public static final String KEY_BULK_MODE = "preferences_bulk_mode"; - public static final String KEY_REMEMBER_DUPLICATES = "preferences_remember_duplicates"; - public static final String KEY_SUPPLEMENTAL = "preferences_supplemental"; - public static final String KEY_SEARCH_COUNTRY = "preferences_search_country"; - - public static final String KEY_HELP_VERSION_SHOWN = "preferences_help_version_shown"; - - private CheckBoxPreference decode1D; - private CheckBoxPreference decodeQR; - private CheckBoxPreference decodeDataMatrix; - - @Override - protected void onCreate(Bundle icicle) { - super.onCreate(icicle); - //addPreferencesFromResource(R.xml.preferences); - - PreferenceScreen preferences = getPreferenceScreen(); - preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this); - decode1D = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_1D); - decodeQR = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_QR); - decodeDataMatrix = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_DATA_MATRIX); - disableLastCheckedPref(); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - disableLastCheckedPref(); - } - - private void disableLastCheckedPref() { - Collection checked = new ArrayList(3); - if (decode1D.isChecked()) { - checked.add(decode1D); - } - if (decodeQR.isChecked()) { - checked.add(decodeQR); - } - if (decodeDataMatrix.isChecked()) { - checked.add(decodeDataMatrix); - } - boolean disable = checked.size() < 2; - CheckBoxPreference[] checkBoxPreferences = {decode1D, decodeQR, decodeDataMatrix}; - for (CheckBoxPreference pref : checkBoxPreferences) { - pref.setEnabled(!(disable && checked.contains(pref))); - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderResultPointCallback.java b/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderResultPointCallback.java deleted file mode 100644 index 9fa4169c3..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderResultPointCallback.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2009 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import com.google.zxing.ResultPoint; -import com.google.zxing.ResultPointCallback; - -final class ViewfinderResultPointCallback implements ResultPointCallback { - - private final ViewfinderView viewfinderView; - - ViewfinderResultPointCallback(ViewfinderView viewfinderView) { - this.viewfinderView = viewfinderView; - } - - @Override - public void foundPossibleResultPoint(ResultPoint point) { - viewfinderView.addPossibleResultPoint(point); - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderView.java b/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderView.java deleted file mode 100644 index 68c7f1f33..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/ViewfinderView.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android; - -import android.content.Context; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Rect; -import android.util.AttributeSet; -import android.view.View; - -import com.google.zxing.ResultPoint; -import com.google.zxing.client.android.camera.CameraManager; - -import java.util.ArrayList; -import java.util.List; - -import es.ugr.swad.swadroid.R; - -/** - * This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial - * transparency outside it, as well as the laser scanner animation and result points. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class ViewfinderView extends View { - - private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64}; - private static final long ANIMATION_DELAY = 80L; - private static final int CURRENT_POINT_OPACITY = 0xA0; - private static final int MAX_RESULT_POINTS = 20; - private static final int POINT_SIZE = 6; - - private CameraManager cameraManager; - private final Paint paint; - private Bitmap resultBitmap; - private final int maskColor; - private final int resultColor; - private final int frameColor; - private final int laserColor; - private final int resultPointColor; - private int scannerAlpha; - private List possibleResultPoints; - private List lastPossibleResultPoints; - - // This constructor is used when the class is built from an XML resource. - public ViewfinderView(Context context, AttributeSet attrs) { - super(context, attrs); - - // Initialize these once for performance rather than calling them every time in onDraw(). - paint = new Paint(Paint.ANTI_ALIAS_FLAG); - Resources resources = getResources(); - maskColor = resources.getColor(R.color.viewfinder_mask); - resultColor = resources.getColor(R.color.result_view); - frameColor = resources.getColor(R.color.viewfinder_frame); - laserColor = resources.getColor(R.color.viewfinder_laser); - resultPointColor = resources.getColor(R.color.possible_result_points); - scannerAlpha = 0; - possibleResultPoints = new ArrayList(5); - lastPossibleResultPoints = null; - } - - public void setCameraManager(CameraManager cameraManager) { - this.cameraManager = cameraManager; - } - - @Override - public void onDraw(Canvas canvas) { - Rect frame = cameraManager.getFramingRect(); - if (frame == null) { - return; - } - int width = canvas.getWidth(); - int height = canvas.getHeight(); - - // Draw the exterior (i.e. outside the framing rect) darkened - paint.setColor(resultBitmap != null ? resultColor : maskColor); - canvas.drawRect(0, 0, width, frame.top, paint); - canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint); - canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint); - canvas.drawRect(0, frame.bottom + 1, width, height, paint); - - if (resultBitmap != null) { - // Draw the opaque result bitmap over the scanning rectangle - paint.setAlpha(CURRENT_POINT_OPACITY); - canvas.drawBitmap(resultBitmap, null, frame, paint); - } else { - - // Draw a two pixel solid black border inside the framing rect - paint.setColor(frameColor); - canvas.drawRect(frame.left, frame.top, frame.right + 1, frame.top + 2, paint); - canvas.drawRect(frame.left, frame.top + 2, frame.left + 2, frame.bottom - 1, paint); - canvas.drawRect(frame.right - 1, frame.top, frame.right + 1, frame.bottom - 1, paint); - canvas.drawRect(frame.left, frame.bottom - 1, frame.right + 1, frame.bottom + 1, paint); - - // Draw a red "laser scanner" line through the middle to show decoding is active - paint.setColor(laserColor); - paint.setAlpha(SCANNER_ALPHA[scannerAlpha]); - scannerAlpha = (scannerAlpha + 1) % SCANNER_ALPHA.length; - int middle = frame.height() / 2 + frame.top; - canvas.drawRect(frame.left + 2, middle - 1, frame.right - 1, middle + 2, paint); - - Rect previewFrame = cameraManager.getFramingRectInPreview(); - float scaleX = frame.width() / (float) previewFrame.width(); - float scaleY = frame.height() / (float) previewFrame.height(); - - List currentPossible = possibleResultPoints; - List currentLast = lastPossibleResultPoints; - int frameLeft = frame.left; - int frameTop = frame.top; - if (currentPossible.isEmpty()) { - lastPossibleResultPoints = null; - } else { - possibleResultPoints = new ArrayList(5); - lastPossibleResultPoints = currentPossible; - paint.setAlpha(CURRENT_POINT_OPACITY); - paint.setColor(resultPointColor); - synchronized (currentPossible) { - for (ResultPoint point : currentPossible) { - canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), - frameTop + (int) (point.getY() * scaleY), - POINT_SIZE, paint); - } - } - } - if (currentLast != null) { - paint.setAlpha(CURRENT_POINT_OPACITY / 2); - paint.setColor(resultPointColor); - synchronized (currentLast) { - float radius = POINT_SIZE / 2.0f; - for (ResultPoint point : currentLast) { - canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX), - frameTop + (int) (point.getY() * scaleY), - radius, paint); - } - } - } - - // Request another update at the animation interval, but only repaint the laser line, - // not the entire viewfinder mask. - postInvalidateDelayed(ANIMATION_DELAY, - frame.left - POINT_SIZE, - frame.top - POINT_SIZE, - frame.right + POINT_SIZE, - frame.bottom + POINT_SIZE); - } - } - - public void drawViewfinder() { - Bitmap resultBitmap = this.resultBitmap; - this.resultBitmap = null; - if (resultBitmap != null) { - resultBitmap.recycle(); - } - invalidate(); - } - - /** - * Draw a bitmap with the result points highlighted instead of the live scanning display. - * - * @param barcode An image of the decoded barcode. - */ - public void drawResultBitmap(Bitmap barcode) { - resultBitmap = barcode; - invalidate(); - } - - public void addPossibleResultPoint(ResultPoint point) { - List points = possibleResultPoints; - synchronized (points) { - points.add(point); - int size = points.size(); - if (size > MAX_RESULT_POINTS) { - // trim it - points.subList(0, size - MAX_RESULT_POINTS / 2).clear(); - } - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/camera/AutoFocusCallback.java b/SWADroid/src/main/java/com/google/zxing/client/android/camera/AutoFocusCallback.java deleted file mode 100644 index 5df6729af..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/camera/AutoFocusCallback.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.camera; - -import android.hardware.Camera; -import android.os.Handler; -import android.os.Message; -import android.util.Log; - -final class AutoFocusCallback implements Camera.AutoFocusCallback { - - private static final String TAG = AutoFocusCallback.class.getSimpleName(); - - private static final long AUTOFOCUS_INTERVAL_MS = 1500L; - - private Handler autoFocusHandler; - private int autoFocusMessage; - - void setHandler(Handler autoFocusHandler, int autoFocusMessage) { - this.autoFocusHandler = autoFocusHandler; - this.autoFocusMessage = autoFocusMessage; - } - - @Override - public void onAutoFocus(boolean success, Camera camera) { - if (autoFocusHandler != null) { - Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success); - // Simulate continuous autofocus by sending a focus request every - // AUTOFOCUS_INTERVAL_MS milliseconds. - //Log.d(TAG, "Got auto-focus callback; requesting another"); - autoFocusHandler.sendMessageDelayed(message, AUTOFOCUS_INTERVAL_MS); - autoFocusHandler = null; - } else { - Log.d(TAG, "Got auto-focus callback, but no handler for it"); - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraConfigurationManager.java b/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraConfigurationManager.java deleted file mode 100644 index de2967c47..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraConfigurationManager.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.camera; - -import android.content.Context; -import android.content.SharedPreferences; -import android.graphics.Point; -import android.hardware.Camera; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.Display; -import android.view.WindowManager; - -import com.google.zxing.client.android.PreferencesActivity; - -import java.util.Collection; - -/** - * A class which deals with reading, parsing, and setting the camera parameters which are used to - * configure the camera hardware. - */ -final class CameraConfigurationManager { - - private static final String TAG = "CameraConfiguration"; - private static final int MIN_PREVIEW_PIXELS = 320 * 240; // small screen - private static final int MAX_PREVIEW_PIXELS = 800 * 480; // large/HD screen - - private final Context context; - private Point screenResolution; - private Point cameraResolution; - - CameraConfigurationManager(Context context) { - this.context = context; - } - - /** - * Reads, one time, values from the camera that are needed by the app. - */ - void initFromCameraParameters(Camera camera) { - Camera.Parameters parameters = camera.getParameters(); - WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - Display display = manager.getDefaultDisplay(); - int width = display.getWidth(); - int height = display.getHeight(); - // We're landscape-only, and have apparently seen issues with display thinking it's portrait - // when waking from sleep. If it's not landscape, assume it's mistaken and reverse them: - if (width < height) { - Log.i(TAG, "Display reports portrait orientation; assuming this is incorrect"); - int temp = width; - width = height; - height = temp; - } - screenResolution = new Point(width, height); - Log.i(TAG, "Screen resolution: " + screenResolution); - cameraResolution = findBestPreviewSizeValue(parameters, screenResolution, false); - Log.i(TAG, "Camera resolution: " + cameraResolution); - } - - void setDesiredCameraParameters(Camera camera) { - Camera.Parameters parameters = camera.getParameters(); - - if (parameters == null) { - Log.w(TAG, "Device error: no camera parameters are available. Proceeding without configuration."); - return; - } - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - - initializeTorch(parameters, prefs); - String focusMode = findSettableValue(parameters.getSupportedFocusModes(), - Camera.Parameters.FOCUS_MODE_AUTO, - Camera.Parameters.FOCUS_MODE_MACRO); - if (focusMode != null) { - parameters.setFocusMode(focusMode); - } - - parameters.setPreviewSize(cameraResolution.x, cameraResolution.y); - camera.setParameters(parameters); - } - - Point getCameraResolution() { - return cameraResolution; - } - - Point getScreenResolution() { - return screenResolution; - } - - void setTorch(Camera camera, boolean newSetting) { - Camera.Parameters parameters = camera.getParameters(); - doSetTorch(parameters, newSetting); - camera.setParameters(parameters); - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false); - if (currentSetting != newSetting) { - SharedPreferences.Editor editor = prefs.edit(); - editor.putBoolean(PreferencesActivity.KEY_FRONT_LIGHT, newSetting); - editor.commit(); - } - } - - private static void initializeTorch(Camera.Parameters parameters, SharedPreferences prefs) { - boolean currentSetting = prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false); - doSetTorch(parameters, currentSetting); - } - - private static void doSetTorch(Camera.Parameters parameters, boolean newSetting) { - String flashMode; - if (newSetting) { - flashMode = findSettableValue(parameters.getSupportedFlashModes(), - Camera.Parameters.FLASH_MODE_TORCH, - Camera.Parameters.FLASH_MODE_ON); - } else { - flashMode = findSettableValue(parameters.getSupportedFlashModes(), - Camera.Parameters.FLASH_MODE_OFF); - } - if (flashMode != null) { - parameters.setFlashMode(flashMode); - } - } - - private static Point findBestPreviewSizeValue(Camera.Parameters parameters, - Point screenResolution, - boolean portrait) { - Point bestSize = null; - int diff = Integer.MAX_VALUE; - for (Camera.Size supportedPreviewSize : parameters.getSupportedPreviewSizes()) { - int pixels = supportedPreviewSize.height * supportedPreviewSize.width; - if (pixels < MIN_PREVIEW_PIXELS || pixels > MAX_PREVIEW_PIXELS) { - continue; - } - int supportedWidth = portrait ? supportedPreviewSize.height : supportedPreviewSize.width; - int supportedHeight = portrait ? supportedPreviewSize.width : supportedPreviewSize.height; - int newDiff = Math.abs(screenResolution.x * supportedHeight - supportedWidth * screenResolution.y); - if (newDiff == 0) { - bestSize = new Point(supportedWidth, supportedHeight); - break; - } - if (newDiff < diff) { - bestSize = new Point(supportedWidth, supportedHeight); - diff = newDiff; - } - } - if (bestSize == null) { - Camera.Size defaultSize = parameters.getPreviewSize(); - bestSize = new Point(defaultSize.width, defaultSize.height); - } - return bestSize; - } - - private static String findSettableValue(Collection supportedValues, - String... desiredValues) { - Log.i(TAG, "Supported values: " + supportedValues); - String result = null; - if (supportedValues != null) { - for (String desiredValue : desiredValues) { - if (supportedValues.contains(desiredValue)) { - result = desiredValue; - break; - } - } - } - Log.i(TAG, "Settable value: " + result); - return result; - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraManager.java b/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraManager.java deleted file mode 100644 index a8c40cb92..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/camera/CameraManager.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.camera; - -import android.content.Context; -import android.content.SharedPreferences; -import android.graphics.Point; -import android.graphics.Rect; -import android.hardware.Camera; -import android.os.Handler; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.SurfaceHolder; - -import com.google.zxing.client.android.PlanarYUVLuminanceSource; -import com.google.zxing.client.android.PreferencesActivity; - -import java.io.IOException; - -/** - * This object wraps the Camera service object and expects to be the only one talking to it. The - * implementation encapsulates the steps needed to take preview-sized images, which are used for - * both preview and decoding. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class CameraManager { - - private static final String TAG = CameraManager.class.getSimpleName(); - - private static final int MIN_FRAME_WIDTH = 240; - private static final int MIN_FRAME_HEIGHT = 240; - private static final int MAX_FRAME_WIDTH = 600; - private static final int MAX_FRAME_HEIGHT = 400; - - private final Context context; - private final CameraConfigurationManager configManager; - private Camera camera; - private Rect framingRect; - private Rect framingRectInPreview; - private boolean initialized; - private boolean previewing; - private boolean reverseImage; - private int requestedFramingRectWidth; - private int requestedFramingRectHeight; - /** - * Preview frames are delivered here, which we pass on to the registered handler. Make sure to - * clear the handler so it will only receive one message. - */ - private final PreviewCallback previewCallback; - /** - * Autofocus callbacks arrive here, and are dispatched to the Handler which requested them. - */ - private final AutoFocusCallback autoFocusCallback; - - public CameraManager(Context context) { - this.context = context; - this.configManager = new CameraConfigurationManager(context); - previewCallback = new PreviewCallback(configManager); - autoFocusCallback = new AutoFocusCallback(); - } - - /** - * Opens the camera driver and initializes the hardware parameters. - * - * @param holder The surface object which the camera will draw preview frames into. - * @throws IOException Indicates the camera driver failed to open. - */ - public void openDriver(SurfaceHolder holder) throws IOException { - Camera theCamera = camera; - if (theCamera == null) { - theCamera = Camera.open(); - if (theCamera == null) { - throw new IOException(); - } - camera = theCamera; - } - theCamera.setPreviewDisplay(holder); - - if (!initialized) { - initialized = true; - configManager.initFromCameraParameters(theCamera); - if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) { - setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight); - requestedFramingRectWidth = 0; - requestedFramingRectHeight = 0; - } - } - configManager.setDesiredCameraParameters(theCamera); - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - reverseImage = prefs.getBoolean(PreferencesActivity.KEY_REVERSE_IMAGE, false); - } - - /** - * Closes the camera driver if still in use. - */ - public void closeDriver() { - if (camera != null) { - camera.release(); - camera = null; - // Make sure to clear these each time we close the camera, so that any scanning rect - // requested by intent is forgotten. - framingRect = null; - framingRectInPreview = null; - } - } - - /** - * Asks the camera hardware to begin drawing preview frames to the screen. - */ - public void startPreview() { - Camera theCamera = camera; - if (theCamera != null && !previewing) { - theCamera.startPreview(); - previewing = true; - } - } - - /** - * Tells the camera to stop drawing preview frames. - */ - public void stopPreview() { - if (camera != null && previewing) { - camera.stopPreview(); - previewCallback.setHandler(null, 0); - autoFocusCallback.setHandler(null, 0); - previewing = false; - } - } - - /** - * A single preview frame will be returned to the handler supplied. The data will arrive as byte[] - * in the message.obj field, with width and height encoded as message.arg1 and message.arg2, - * respectively. - * - * @param handler The handler to send the message to. - * @param message The what field of the message to be sent. - */ - public void requestPreviewFrame(Handler handler, int message) { - Camera theCamera = camera; - if (theCamera != null && previewing) { - previewCallback.setHandler(handler, message); - theCamera.setOneShotPreviewCallback(previewCallback); - } - } - - /** - * Asks the camera hardware to perform an autofocus. - * - * @param handler The Handler to notify when the autofocus completes. - * @param message The message to deliver. - */ - public void requestAutoFocus(Handler handler, int message) { - if (camera != null && previewing) { - autoFocusCallback.setHandler(handler, message); - try { - camera.autoFocus(autoFocusCallback); - } catch (RuntimeException re) { - // Have heard RuntimeException reported in Android 4.0.x+; continue? - Log.w(TAG, "Unexpected exception while focusing", re); - } - } - } - - /** - * Calculates the framing rect which the UI should draw to show the user where to place the - * barcode. This target helps with alignment as well as forces the user to hold the device - * far enough away to ensure the image will be in focus. - * - * @return The rectangle to draw on screen in window coordinates. - */ - public Rect getFramingRect() { - if (framingRect == null) { - if (camera == null) { - return null; - } - Point screenResolution = configManager.getScreenResolution(); - int width = screenResolution.x * 3 / 4; - if (width < MIN_FRAME_WIDTH) { - width = MIN_FRAME_WIDTH; - } else if (width > MAX_FRAME_WIDTH) { - width = MAX_FRAME_WIDTH; - } - int height = screenResolution.y * 3 / 4; - if (height < MIN_FRAME_HEIGHT) { - height = MIN_FRAME_HEIGHT; - } else if (height > MAX_FRAME_HEIGHT) { - height = MAX_FRAME_HEIGHT; - } - int leftOffset = (screenResolution.x - width) / 2; - int topOffset = (screenResolution.y - height) / 2; - framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); - Log.d(TAG, "Calculated framing rect: " + framingRect); - } - return framingRect; - } - - /** - * Like {@link #getFramingRect} but coordinates are in terms of the preview frame, - * not UI / screen. - */ - public Rect getFramingRectInPreview() { - if (framingRectInPreview == null) { - Rect framingRect = getFramingRect(); - if (framingRect == null) { - return null; - } - Rect rect = new Rect(framingRect); - Point cameraResolution = configManager.getCameraResolution(); - Point screenResolution = configManager.getScreenResolution(); - rect.left = rect.left * cameraResolution.x / screenResolution.x; - rect.right = rect.right * cameraResolution.x / screenResolution.x; - rect.top = rect.top * cameraResolution.y / screenResolution.y; - rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y; - framingRectInPreview = rect; - } - return framingRectInPreview; - } - - /** - * Allows third party apps to specify the scanning rectangle dimensions, rather than determine - * them automatically based on screen resolution. - * - * @param width The width in pixels to scan. - * @param height The height in pixels to scan. - */ - public void setManualFramingRect(int width, int height) { - if (initialized) { - Point screenResolution = configManager.getScreenResolution(); - if (width > screenResolution.x) { - width = screenResolution.x; - } - if (height > screenResolution.y) { - height = screenResolution.y; - } - int leftOffset = (screenResolution.x - width) / 2; - int topOffset = (screenResolution.y - height) / 2; - framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height); - Log.d(TAG, "Calculated manual framing rect: " + framingRect); - framingRectInPreview = null; - } else { - requestedFramingRectWidth = width; - requestedFramingRectHeight = height; - } - } - - /** - * A factory method to build the appropriate LuminanceSource object based on the format - * of the preview buffers, as described by Camera.Parameters. - * - * @param data A preview frame. - * @param width The width of the image. - * @param height The height of the image. - * @return A PlanarYUVLuminanceSource instance. - */ - public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) { - Rect rect = getFramingRectInPreview(); - if (rect == null) { - return null; - } - // Go ahead and assume it's YUV rather than die. - return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top, - rect.width(), rect.height(), reverseImage); - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/camera/PreviewCallback.java b/SWADroid/src/main/java/com/google/zxing/client/android/camera/PreviewCallback.java deleted file mode 100644 index 1e55493fa..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/camera/PreviewCallback.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2010 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.camera; - -import android.graphics.Point; -import android.hardware.Camera; -import android.os.Handler; -import android.os.Message; -import android.util.Log; - -final class PreviewCallback implements Camera.PreviewCallback { - - private static final String TAG = PreviewCallback.class.getSimpleName(); - - private final CameraConfigurationManager configManager; - private Handler previewHandler; - private int previewMessage; - - PreviewCallback(CameraConfigurationManager configManager) { - this.configManager = configManager; - } - - void setHandler(Handler previewHandler, int previewMessage) { - this.previewHandler = previewHandler; - this.previewMessage = previewMessage; - } - - @Override - public void onPreviewFrame(byte[] data, Camera camera) { - Point cameraResolution = configManager.getCameraResolution(); - Handler thePreviewHandler = previewHandler; - if (thePreviewHandler != null) { - Message message = thePreviewHandler.obtainMessage(previewMessage, cameraResolution.x, - cameraResolution.y, data); - message.sendToTarget(); - previewHandler = null; - } else { - Log.d(TAG, "Got preview callback, but no handler for it"); - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/encode/ContactEncoder.java b/SWADroid/src/main/java/com/google/zxing/client/android/encode/ContactEncoder.java deleted file mode 100644 index 639f48c9d..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/encode/ContactEncoder.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.encode; - -import java.util.Collection; -import java.util.HashSet; - -/** - * Implementations encode according to some scheme for encoding contact information, like VCard or - * MECARD. - * - * @author Sean Owen - */ -abstract class ContactEncoder { - - /** - * @return first, the best effort encoding of all data in the appropriate format; second, a - * display-appropriate version of the contact information - */ - abstract String[] encode(Iterable names, - String organization, - Iterable addresses, - Iterable phones, - Iterable emails, - String url, - String note); - - /** - * @return null if s is null or empty, or result of s.trim() otherwise - */ - static String trim(String s) { - if (s == null) { - return null; - } - String result = s.trim(); - return result.length() == 0 ? null : result; - } - - static void doAppend(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - String value, - Formatter fieldFormatter, - char terminator) { - String trimmed = trim(value); - if (trimmed != null) { - newContents.append(prefix).append(':').append(fieldFormatter.format(trimmed)).append(terminator); - newDisplayContents.append(trimmed).append('\n'); - } - } - - static void doAppendUpToUnique(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - Iterable values, - int max, - Formatter formatter, - Formatter fieldFormatter, - char terminator) { - if (values == null) { - return; - } - int count = 0; - Collection uniques = new HashSet(2); - for (String value : values) { - String trimmed = trim(value); - if (trimmed != null && !uniques.contains(trimmed)) { - newContents.append(prefix).append(':').append(fieldFormatter.format(trimmed)).append(terminator); - String display = formatter == null ? trimmed : formatter.format(trimmed); - newDisplayContents.append(display).append('\n'); - if (++count == max) { - break; - } - uniques.add(trimmed); - } - } - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/encode/Formatter.java b/SWADroid/src/main/java/com/google/zxing/client/android/encode/Formatter.java deleted file mode 100644 index 69f46dac2..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/encode/Formatter.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.encode; - -/** - * Encapsulates some simple formatting logic, to aid refactoring in {@link ContactEncoder}. - * - * @author Sean Owen - */ -interface Formatter { - - String format(String source); - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/encode/MECARDContactEncoder.java b/SWADroid/src/main/java/com/google/zxing/client/android/encode/MECARDContactEncoder.java deleted file mode 100644 index 56e7d4fc6..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/encode/MECARDContactEncoder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.encode; - -import android.telephony.PhoneNumberUtils; - -import java.util.regex.Pattern; - -/** - * Encodes contact information according to the MECARD format. - * - * @author Sean Owen - */ -final class MECARDContactEncoder extends ContactEncoder { - - private static final Pattern RESERVED_MECARD_CHARS = Pattern.compile("([\\\\:;])"); - private static final Pattern NEWLINE = Pattern.compile("\\n"); - private static final Pattern COMMA = Pattern.compile(","); - private static final Formatter MECARD_FIELD_FORMATTER = new Formatter() { - @Override - public String format(String source) { - return NEWLINE.matcher(RESERVED_MECARD_CHARS.matcher(source).replaceAll("\\\\$1")).replaceAll(""); - } - }; - private static final char TERMINATOR = ';'; - - @Override - public String[] encode(Iterable names, - String organization, - Iterable addresses, - Iterable phones, - Iterable emails, - String url, - String note) { - StringBuilder newContents = new StringBuilder(100); - StringBuilder newDisplayContents = new StringBuilder(100); - newContents.append("MECARD:"); - appendUpToUnique(newContents, newDisplayContents, "N", names, 1, new Formatter() { - @Override - public String format(String source) { - return source == null ? null : COMMA.matcher(source).replaceAll(""); - } - }); - append(newContents, newDisplayContents, "ORG", organization); - appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null); - appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE, new Formatter() { - @Override - public String format(String source) { - return PhoneNumberUtils.formatNumber(source); - } - }); - appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null); - append(newContents, newDisplayContents, "URL", url); - append(newContents, newDisplayContents, "NOTE", note); - newContents.append(';'); - return new String[]{newContents.toString(), newDisplayContents.toString()}; - } - - private static void append(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - String value) { - doAppend(newContents, newDisplayContents, prefix, value, MECARD_FIELD_FORMATTER, TERMINATOR); - } - - private static void appendUpToUnique(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - Iterable values, - int max, - Formatter formatter) { - doAppendUpToUnique(newContents, - newDisplayContents, - prefix, - values, - max, - formatter, - MECARD_FIELD_FORMATTER, - TERMINATOR); - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/encode/QRCodeEncoder.java b/SWADroid/src/main/java/com/google/zxing/client/android/encode/QRCodeEncoder.java deleted file mode 100644 index fd08dd689..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/encode/QRCodeEncoder.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (C) 2008 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.encode; - -import android.app.Activity; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Bundle; -import android.provider.ContactsContract; -import android.telephony.PhoneNumberUtils; -import android.util.Log; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.EncodeHintType; -import com.google.zxing.MultiFormatWriter; -import com.google.zxing.Result; -import com.google.zxing.WriterException; -import com.google.zxing.client.android.Contents; -import com.google.zxing.client.android.Intents; -import com.google.zxing.client.result.AddressBookParsedResult; -import com.google.zxing.client.result.ParsedResult; -import com.google.zxing.client.result.ResultParser; -import com.google.zxing.common.BitMatrix; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; - -import es.ugr.swad.swadroid.R; - -/** - * This class does the work of decoding the user's request and extracting all the data - * to be encoded in a barcode. - * - * @author dswitkin@google.com (Daniel Switkin) - */ -public final class QRCodeEncoder { - - private static final String TAG = QRCodeEncoder.class.getSimpleName(); - - private static final int WHITE = 0xFFFFFFFF; - private static final int BLACK = 0xFF000000; - - private final Activity activity; - private String contents; - private String displayContents; - private String title; - private BarcodeFormat format; - private final int dimension; - private final boolean useVCard; - - public QRCodeEncoder(Activity activity, Intent intent, int dimension, boolean useVCard) throws WriterException { - this.activity = activity; - this.dimension = dimension; - this.useVCard = useVCard; - String action = intent.getAction(); - if (action.equals(Intents.Encode.ACTION)) { - encodeContentsFromZXingIntent(intent); - } else if (action.equals(Intent.ACTION_SEND)) { - encodeContentsFromShareIntent(intent); - } - } - - String getContents() { - return contents; - } - - String getDisplayContents() { - return displayContents; - } - - String getTitle() { - return title; - } - - boolean isUseVCard() { - return useVCard; - } - - // It would be nice if the string encoding lived in the core ZXing library, - // but we use platform specific code like PhoneNumberUtils, so it can't. - private boolean encodeContentsFromZXingIntent(Intent intent) { - // Default to QR_CODE if no format given. - String formatString = intent.getStringExtra(Intents.Encode.FORMAT); - format = null; - if (formatString != null) { - try { - format = BarcodeFormat.valueOf(formatString); - } catch (IllegalArgumentException iae) { - // Ignore it then - } - } - if (format == null || format == BarcodeFormat.QR_CODE) { - String type = intent.getStringExtra(Intents.Encode.TYPE); - if (type == null || type.length() == 0) { - return false; - } - this.format = BarcodeFormat.QR_CODE; - encodeQRCodeContents(intent, type); - } else { - String data = intent.getStringExtra(Intents.Encode.DATA); - if (data != null && data.length() > 0) { - contents = data; - displayContents = data; - title = activity.getString(R.string.contents_text); - } - } - return contents != null && contents.length() > 0; - } - - // Handles send intents from multitude of Android applications - private void encodeContentsFromShareIntent(Intent intent) throws WriterException { - // Check if this is a plain text encoding, or contact - if (intent.hasExtra(Intent.EXTRA_STREAM)) { - encodeFromStreamExtra(intent); - } else { - encodeFromTextExtras(intent); - } - } - - private void encodeFromTextExtras(Intent intent) throws WriterException { - // Notice: Google Maps shares both URL and details in one text, bummer! - String theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_TEXT)); - if (theContents == null) { - theContents = ContactEncoder.trim(intent.getStringExtra("android.intent.extra.HTML_TEXT")); - // Intent.EXTRA_HTML_TEXT - if (theContents == null) { - theContents = ContactEncoder.trim(intent.getStringExtra(Intent.EXTRA_SUBJECT)); - if (theContents == null) { - String[] emails = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); - if (emails != null) { - theContents = ContactEncoder.trim(emails[0]); - } else { - theContents = "?"; - } - } - } - } - - // Trim text to avoid URL breaking. - if (theContents == null || theContents.length() == 0) { - throw new WriterException("Empty EXTRA_TEXT"); - } - contents = theContents; - // We only do QR code. - format = BarcodeFormat.QR_CODE; - if (intent.hasExtra(Intent.EXTRA_SUBJECT)) { - displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT); - } else if (intent.hasExtra(Intent.EXTRA_TITLE)) { - displayContents = intent.getStringExtra(Intent.EXTRA_TITLE); - } else { - displayContents = contents; - } - title = activity.getString(R.string.contents_text); - } - - // Handles send intents from the Contacts app, retrieving a contact as a VCARD. - private void encodeFromStreamExtra(Intent intent) throws WriterException { - format = BarcodeFormat.QR_CODE; - Bundle bundle = intent.getExtras(); - if (bundle == null) { - throw new WriterException("No extras"); - } - Uri uri = bundle.getParcelable(Intent.EXTRA_STREAM); - if (uri == null) { - throw new WriterException("No EXTRA_STREAM"); - } - byte[] vcard; - String vcardString; - try { - InputStream stream = activity.getContentResolver().openInputStream(uri); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buffer = new byte[2048]; - int bytesRead; - while ((bytesRead = stream.read(buffer)) > 0) { - baos.write(buffer, 0, bytesRead); - } - vcard = baos.toByteArray(); - vcardString = new String(vcard, 0, vcard.length, "UTF-8"); - } catch (IOException ioe) { - throw new WriterException(ioe); - } - Log.d(TAG, "Encoding share intent content:"); - Log.d(TAG, vcardString); - Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE); - ParsedResult parsedResult = ResultParser.parseResult(result); - if (!(parsedResult instanceof AddressBookParsedResult)) { - throw new WriterException("Result was not an address"); - } - encodeQRCodeContents((AddressBookParsedResult) parsedResult); - if (contents == null || contents.length() == 0) { - throw new WriterException("No content to encode"); - } - } - - private void encodeQRCodeContents(Intent intent, String type) { - if (type.equals(Contents.Type.TEXT)) { - String data = intent.getStringExtra(Intents.Encode.DATA); - if (data != null && data.length() > 0) { - contents = data; - displayContents = data; - title = activity.getString(R.string.contents_text); - } - } else if (type.equals(Contents.Type.EMAIL)) { - String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA)); - if (data != null) { - contents = "mailto:" + data; - displayContents = data; - title = activity.getString(R.string.contents_email); - } - } else if (type.equals(Contents.Type.PHONE)) { - String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA)); - if (data != null) { - contents = "tel:" + data; - displayContents = PhoneNumberUtils.formatNumber(data); - title = activity.getString(R.string.contents_phone); - } - } else if (type.equals(Contents.Type.SMS)) { - String data = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA)); - if (data != null) { - contents = "sms:" + data; - displayContents = PhoneNumberUtils.formatNumber(data); - title = activity.getString(R.string.contents_sms); - } - } else if (type.equals(Contents.Type.CONTACT)) { - - Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA); - if (bundle != null) { - - String name = bundle.getString(ContactsContract.Intents.Insert.NAME); - String organization = bundle.getString(ContactsContract.Intents.Insert.COMPANY); - String address = bundle.getString(ContactsContract.Intents.Insert.POSTAL); - Collection phones = new ArrayList(Contents.PHONE_KEYS.length); - for (int x = 0; x < Contents.PHONE_KEYS.length; x++) { - phones.add(bundle.getString(Contents.PHONE_KEYS[x])); - } - Collection emails = new ArrayList(Contents.EMAIL_KEYS.length); - for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) { - emails.add(bundle.getString(Contents.EMAIL_KEYS[x])); - } - String url = bundle.getString(Contents.URL_KEY); - String note = bundle.getString(Contents.NOTE_KEY); - - ContactEncoder mecardEncoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder(); - String[] encoded = mecardEncoder.encode(Collections.singleton(name), - organization, - Collections.singleton(address), - phones, - emails, - url, - note); - // Make sure we've encoded at least one field. - if (encoded[1].length() > 0) { - contents = encoded[0]; - displayContents = encoded[1]; - title = activity.getString(R.string.contents_contact); - } - - } - - } else if (type.equals(Contents.Type.LOCATION)) { - Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA); - if (bundle != null) { - // These must use Bundle.getFloat(), not getDouble(), it's part of the API. - float latitude = bundle.getFloat("LAT", Float.MAX_VALUE); - float longitude = bundle.getFloat("LONG", Float.MAX_VALUE); - if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) { - contents = "geo:" + latitude + ',' + longitude; - displayContents = latitude + "," + longitude; - title = activity.getString(R.string.contents_location); - } - } - } - } - - private void encodeQRCodeContents(AddressBookParsedResult contact) { - ContactEncoder encoder = useVCard ? new VCardContactEncoder() : new MECARDContactEncoder(); - String[] encoded = encoder.encode(toIterable(contact.getNames()), - contact.getOrg(), - toIterable(contact.getAddresses()), - toIterable(contact.getPhoneNumbers()), - toIterable(contact.getEmails()), - contact.getURL(), - null); - // Make sure we've encoded at least one field. - if (encoded[1].length() > 0) { - contents = encoded[0]; - displayContents = encoded[1]; - title = activity.getString(R.string.contents_contact); - } - } - - private static Iterable toIterable(String[] values) { - return values == null ? null : Arrays.asList(values); - } - - public Bitmap encodeAsBitmap() throws WriterException { - String contentsToEncode = contents; - if (contentsToEncode == null) { - return null; - } - Map hints = null; - String encoding = guessAppropriateEncoding(contentsToEncode); - if (encoding != null) { - hints = new EnumMap(EncodeHintType.class); - hints.put(EncodeHintType.CHARACTER_SET, encoding); - } - MultiFormatWriter writer = new MultiFormatWriter(); - BitMatrix result; - try { - result = writer.encode(contentsToEncode, format, dimension, dimension, hints); - } catch (IllegalArgumentException iae) { - // Unsupported format - return null; - } - int width = result.getWidth(); - int height = result.getHeight(); - int[] pixels = new int[width * height]; - for (int y = 0; y < height; y++) { - int offset = y * width; - for (int x = 0; x < width; x++) { - pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; - } - } - - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.setPixels(pixels, 0, width, 0, 0, width, height); - return bitmap; - } - - private static String guessAppropriateEncoding(CharSequence contents) { - // Very crude at the moment - for (int i = 0; i < contents.length(); i++) { - if (contents.charAt(i) > 0xFF) { - return "UTF-8"; - } - } - return null; - } - -} diff --git a/SWADroid/src/main/java/com/google/zxing/client/android/encode/VCardContactEncoder.java b/SWADroid/src/main/java/com/google/zxing/client/android/encode/VCardContactEncoder.java deleted file mode 100644 index 6daafb593..000000000 --- a/SWADroid/src/main/java/com/google/zxing/client/android/encode/VCardContactEncoder.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2011 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.zxing.client.android.encode; - -import android.telephony.PhoneNumberUtils; - -import java.util.regex.Pattern; - -/** - * Encodes contact information according to the vCard format. - * - * @author Sean Owen - */ -final class VCardContactEncoder extends ContactEncoder { - - private static final Pattern RESERVED_VCARD_CHARS = Pattern.compile("([\\\\,;])"); - private static final Pattern NEWLINE = Pattern.compile("\\n"); - private static final Formatter VCARD_FIELD_FORMATTER = new Formatter() { - @Override - public String format(String source) { - return NEWLINE.matcher(RESERVED_VCARD_CHARS.matcher(source).replaceAll("\\\\$1")).replaceAll(""); - } - }; - private static final char TERMINATOR = '\n'; - - @Override - public String[] encode(Iterable names, - String organization, - Iterable addresses, - Iterable phones, - Iterable emails, - String url, - String note) { - StringBuilder newContents = new StringBuilder(100); - StringBuilder newDisplayContents = new StringBuilder(100); - newContents.append("BEGIN:VCARD").append(TERMINATOR); - appendUpToUnique(newContents, newDisplayContents, "N", names, 1, null); - append(newContents, newDisplayContents, "ORG", organization); - appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null); - appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE, new Formatter() { - @Override - public String format(String source) { - return PhoneNumberUtils.formatNumber(source); - } - }); - appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null); - append(newContents, newDisplayContents, "URL", url); - append(newContents, newDisplayContents, "NOTE", note); - newContents.append("END:VCARD").append(TERMINATOR); - return new String[]{newContents.toString(), newDisplayContents.toString()}; - } - - private static void append(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - String value) { - doAppend(newContents, newDisplayContents, prefix, value, VCARD_FIELD_FORMATTER, TERMINATOR); - } - - private static void appendUpToUnique(StringBuilder newContents, - StringBuilder newDisplayContents, - String prefix, - Iterable values, - int max, - Formatter formatter) { - doAppendUpToUnique(newContents, - newDisplayContents, - prefix, - values, - max, - formatter, - VCARD_FIELD_FORMATTER, - TERMINATOR); - } - -} diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java index 66641ac68..f4bd598b3 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java @@ -60,22 +60,7 @@ public static enum TrackerName { private static HashMap mTrackers = new HashMap(); - /*static synchronized Tracker getTracker(Context context, TrackerName trackerId) { - if (!mTrackers.containsKey(trackerId)) { - - GoogleAnalytics analytics = GoogleAnalytics.getInstance(context); - Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(Config.ANALYTICS_API_KEY) - : (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker) - : analytics.newTracker(R.xml.ecommerce_tracker); - mTrackers.put(trackerId, t); - - } - return mTrackers.get(trackerId); - }*/ - private static boolean isTrackerEnabled(Context context) { - /*return (!Config.ANALYTICS_API_KEY.isEmpty() - && (GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS));*/ return (!Config.ANALYTICS_API_KEY.isEmpty()); } @@ -97,14 +82,6 @@ public static void initTracker(Context context) { if(isTrackerEnabled(context)) { GoogleAnalytics.getInstance(context).newTracker(Config.ANALYTICS_API_KEY); - /*Thread.UncaughtExceptionHandler exceptionHandler = new ExceptionReporter( - getTracker(context), // Currently used Tracker. - Thread.getDefaultUncaughtExceptionHandler(), // Current default uncaught exception handler. - context); // Context of the application. - - // Make exceptionHandler the new default uncaught exception handler. - Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);*/ - ExceptionReporter exceptionHandler = new ExceptionReporter( getTracker(context), @@ -140,7 +117,7 @@ public static void sendScreenView(Context context, String path) { t.setScreenName(path); // Send a screen view. - t.send(new HitBuilders.AppViewBuilder().build()); + t.send(new HitBuilders.ScreenViewBuilder().build()); Log.i(TAG, "ScreenView sent for screen " + path); } @@ -156,7 +133,7 @@ public static void sendScreenView(Context context, String path, String category, t.setScreenName(path); // Send a screen view. - t.send(new HitBuilders.AppViewBuilder().build()); + t.send(new HitBuilders.ScreenViewBuilder().build()); // This event will also be sent with &cd=Home%20Screen. // Build and send an Event. @@ -178,12 +155,6 @@ public static void sendException(Context context, Exception e, boolean fatal) { // Get tracker. Tracker t = getTracker(context); - // Build and send exception. - /*t.send(new HitBuilders.ExceptionBuilder() - .setDescription(e.getCause().toString()) - .setFatal(fatal) - .build());*/ - StandardExceptionParser exceptionParser = new StandardExceptionParser(context, null) { @Override diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageFactory.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageFactory.java index fd85efd88..88d1a7126 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageFactory.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageFactory.java @@ -32,6 +32,8 @@ * @author Juan Miguel Boyero Corral */ public class ImageFactory { + private static ImageLoader loader = ImageLoader.getInstance(); + /** * Initializes a cached image loader * @param ctx Application context @@ -45,7 +47,6 @@ public class ImageFactory { public static ImageLoader init(Context ctx, boolean cacheMemory, boolean cacheDisk, int imageEmpty, int imageFail, int imageLoading) { - ImageLoader loader = ImageLoader.getInstance(); Builder builder = new DisplayImageOptions.Builder(); DisplayImageOptions options; @@ -71,6 +72,10 @@ public static ImageLoader init(Context ctx, boolean cacheMemory, boolean cacheDi .defaultDisplayImageOptions(options) .build(); + if(loader.isInited()) { + loader.destroy(); + } + loader.init(config); return loader; @@ -88,7 +93,7 @@ public static ImageLoader init(Context ctx, boolean cacheMemory, boolean cacheDi public static void displayImage(Context ctx, String uri, ImageView imageView, boolean cacheMemory, boolean cacheDisk, int imageEmpty, int imageFail, int imageLoading) { - ImageLoader loader = init(ctx, cacheMemory, cacheDisk, imageEmpty, + init(ctx, cacheMemory, cacheDisk, imageEmpty, imageFail, imageLoading); loader.displayImage(uri, imageView); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java index 87ce3f3ff..84229ba30 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java @@ -26,17 +26,17 @@ import android.content.pm.ApplicationInfo; import android.net.Uri; import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import es.ugr.swad.swadroid.Constants; -import es.ugr.swad.swadroid.preferences.Preferences; -import es.ugr.swad.swadroid.preferences.PreferencesActivity; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.database.DataBaseHelper; +import es.ugr.swad.swadroid.preferences.Preferences; +import es.ugr.swad.swadroid.preferences.PreferencesActivity; /** * Superclass for add the options menu to all children classes of Activity @@ -45,7 +45,7 @@ * @author Antonio Aguilera Malagon * @author Helena Rodriguez Gijon */ -public class MenuActivity extends ActionBarActivity { +public class MenuActivity extends AppCompatActivity { /** * Application preferences */ diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java index ef3764ea7..0bd428567 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java @@ -26,18 +26,18 @@ import android.content.pm.ApplicationInfo; import android.net.Uri; import android.os.Bundle; -import android.support.v7.app.ActionBarActivity; +import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import es.ugr.swad.swadroid.Constants; -import es.ugr.swad.swadroid.preferences.Preferences; -import es.ugr.swad.swadroid.preferences.PreferencesActivity; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.SWADMain; import es.ugr.swad.swadroid.database.DataBaseHelper; +import es.ugr.swad.swadroid.preferences.Preferences; +import es.ugr.swad.swadroid.preferences.PreferencesActivity; /** * Superclass for add the options menu to all children classes of ExpandableListActivity @@ -46,7 +46,7 @@ * @author Antonio Aguilera Malagon * @author Helena Rodriguez Gijon */ -public class MenuExpandableListActivity extends ActionBarActivity { +public class MenuExpandableListActivity extends AppCompatActivity { /** * Application preferences */ diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java index b858cf057..258e14145 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java @@ -8,14 +8,20 @@ import android.widget.ImageView; import android.widget.Toast; +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; +import com.journeyapps.barcodescanner.BarcodeEncoder; + +import java.util.EnumMap; +import java.util.Map; import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.analytics.SWADroidTracker; import es.ugr.swad.swadroid.gui.MenuActivity; import es.ugr.swad.swadroid.modules.login.Login; -import es.ugr.swad.swadroid.utils.QR; public class GenerateQR extends MenuActivity { /** @@ -23,6 +29,21 @@ public class GenerateQR extends MenuActivity { */ private static final String TAG = Constants.APP_TAG + " GenerateQR"; + /** + * Code width + */ + private static final int CODE_WIDTH = 250; + + /** + * Code height + */ + private static final int CODE_HEIGHT = 250; + + /** + * Barcode Encoder + */ + private static BarcodeEncoder barcodeEncoder; + /* (non-Javadoc) * @see es.ugr.swad.swadroid.modules.Module#onCreate(android.os.Bundle) */ @@ -37,6 +58,8 @@ protected void onCreate(Bundle savedInstanceState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } + + barcodeEncoder = new BarcodeEncoder(); } /* (non-Javadoc) @@ -83,8 +106,18 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { private void generateQR() { try { + String qrContents = "@" + Login.getLoggedUser().getUserNickname(); ImageView qr_image = (ImageView) findViewById(R.id.qr_code_image); - Bitmap qrCode = QR.encode(this, "@" + Login.getLoggedUser().getUserNickname()); + Bitmap qrCode; + Map hintMap = new EnumMap(EncodeHintType.class); + + hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + + // Now with zxing version 3.2.1 you could change border size (white border size to just 1) + hintMap.put(EncodeHintType.MARGIN, 1); /* default = 4 */ + hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); + + qrCode = barcodeEncoder.encodeBitmap(qrContents, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hintMap); qr_image.setImageBitmap(qrCode); } catch (WriterException e) { error(TAG, e.getMessage(), e, true); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java new file mode 100644 index 000000000..f958b213c --- /dev/null +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java @@ -0,0 +1,196 @@ +package es.ugr.swad.swadroid.modules.rollcall; + +import android.media.MediaPlayer; +import android.os.Bundle; +import android.os.Handler; +import android.support.v7.app.AppCompatActivity; +import android.util.Log; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.zxing.ResultPoint; +import com.journeyapps.barcodescanner.BarcodeCallback; +import com.journeyapps.barcodescanner.BarcodeResult; +import com.journeyapps.barcodescanner.CompoundBarcodeView; + +import java.util.List; + +import es.ugr.swad.swadroid.Constants; +import es.ugr.swad.swadroid.R; +import es.ugr.swad.swadroid.database.DataBaseHelper; +import es.ugr.swad.swadroid.gui.ImageFactory; +import es.ugr.swad.swadroid.model.User; +import es.ugr.swad.swadroid.utils.Crypto; +import es.ugr.swad.swadroid.utils.Utils; + +/** + * This Activity performs continuous scanning, processing rollcalls whenever + * a barcode is scanned. + * + * @author Juan Miguel Boyero Corral + */ +public class ContinuousCaptureActivity extends AppCompatActivity { + + private static final String TAG = Constants.APP_TAG + " " + ContinuousCaptureActivity.class.getSimpleName(); + + /* + * Text size in scan window + */ + private static final int SCAN_TEXT_SIZE = 18; + + private static final long BULK_MODE_SCAN_DELAY_MS = 1000L; + + private static DataBaseHelper dbHelper; + private static Crypto crypto; + + private CompoundBarcodeView barcodeView; + private MediaPlayer mediaPlayer; + + private BarcodeCallback callback = new BarcodeCallback() { + @Override + public void barcodeResult(BarcodeResult result) { + handleDecode(result); + } + + @Override + public void possibleResultPoints(List resultPoints) { + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.continuous_scan); + + try { + //Initialize database + dbHelper = new DataBaseHelper(this); + crypto = new Crypto(this, dbHelper.getDBKey()); + } catch (Exception ex) { + Log.e(TAG, ex.getMessage(), ex); + } + + barcodeView = (CompoundBarcodeView) findViewById(R.id.barcode_scanner); + barcodeView.decodeContinuous(callback); + } + + @Override + protected void onResume() { + super.onResume(); + + barcodeView.resume(); + } + + @Override + protected void onPause() { + super.onPause(); + + barcodeView.pause(); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); + } + + /** + * A valid barcode has been found, so give an indication of success and show the results. + * + * @param result The contents of the barcode. + */ + public void handleDecode(BarcodeResult result) { + String messageResult; + int iconResult; + String qrContent = result.getText(); + boolean validContent = Utils.isValidNickname(qrContent); + User u = null; + + if (validContent) { + u = dbHelper.getUser("userNickname", crypto.encrypt(qrContent.substring(1))); + + if ((u != null) && dbHelper.isUserEnrolledEvent(UsersActivity.getEventCode(), "userCode", + String.valueOf(u.getId()))) { + Log.d(TAG, "isUserEnrolledEvent=" + dbHelper.isUserEnrolledEvent(UsersActivity.getEventCode(), "userCode", + crypto.encrypt(String.valueOf(u.getId())))); + //Mark student as present in the event + dbHelper.insertAttendance(u.getId(), UsersActivity.getEventCode(), true); + + //Mark event status as "pending" + dbHelper.updateEventStatus(UsersActivity.getEventCode(), "pending"); + + messageResult = getString(R.string.scan_valid_student); + iconResult = R.drawable.ok; + mediaPlayer = MediaPlayer.create(this, R.raw.beep); // Positive sound + + messageResult += "\n\n" + + getString(R.string.scan_id) + ": " + u.getUserID() + "\n" + + getString(R.string.scan_name) + ": " + u.getUserFirstname() + " " + + u.getUserSurname1() + " " + u.getUserSurname2(); + } else { + // There is no user with that nickname + messageResult = getString(R.string.scan_data_not_found); + iconResult = R.drawable.not_ok; + mediaPlayer = MediaPlayer.create(this, R.raw.klaxon); // Negative sound + } + } else { + // Not detected any valid ID or nickname + messageResult = getString(R.string.scan_not_valid_code); + iconResult = R.drawable.not_ok; + mediaPlayer = MediaPlayer.create(this, R.raw.klaxon); // Negative sound + } + + //Release media player when playback ends + mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { + public void onCompletion(MediaPlayer mMediaPlayer) { + mMediaPlayer.release(); + } + }); + + //Play selected sound + mediaPlayer.start(); + + // Show photo of student + LayoutInflater inflater = getLayoutInflater(); + View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); + ImageView image = (ImageView) layout.findViewById(R.id.image); + + if (u != null) { + ImageFactory.displayImage(getApplicationContext(), u.getUserPhoto(), image, true, true, + R.drawable.usr_bl, R.drawable.usr_bl, R.drawable.usr_bl); + } + + // Show appropriate icon + ImageView icon = (ImageView) layout.findViewById(R.id.icon); + icon.setImageResource(iconResult); + + // Show appropriate message + TextView toastText = (TextView) layout.findViewById(R.id.text); + toastText.setText(messageResult); + toastText.setGravity(Gravity.CENTER_VERTICAL); + toastText.setTextSize(SCAN_TEXT_SIZE); + + final Toast toast = new Toast(getApplicationContext()); + toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); + toast.setDuration(Toast.LENGTH_SHORT); + toast.setView(layout); + toast.show(); + + // Hide message after delay + if(BULK_MODE_SCAN_DELAY_MS < 2000L) { + new Handler().postDelayed(new Runnable() { + @Override + public void run() { + toast.cancel(); + } + }, BULK_MODE_SCAN_DELAY_MS); + } + } +} + diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java index e8510e79d..7d1980c9f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java @@ -21,7 +21,6 @@ package es.ugr.swad.swadroid.modules.rollcall; -import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; @@ -31,9 +30,6 @@ import android.os.Build; import android.os.Bundle; import android.os.Handler; -import android.support.annotation.NonNull; -import android.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.Menu; @@ -43,7 +39,7 @@ import android.widget.ListView; import android.widget.TextView; -import com.google.zxing.client.android.Intents; +import com.google.zxing.integration.android.IntentIntegrator; import java.util.List; @@ -78,11 +74,11 @@ public class UsersActivity extends MenuExpandableListActivity implements /** * Adapter for ListView of users */ - UsersCursorAdapter adapter; + private UsersCursorAdapter adapter; /** * Database cursor for Adapter of users */ - Cursor dbCursor; + private Cursor dbCursor; /** * Layout with "Pull to refresh" function */ @@ -90,11 +86,16 @@ public class UsersActivity extends MenuExpandableListActivity implements /** * TextView for the empty users message */ - TextView emptyUsersTextView; + private TextView emptyUsersTextView; /** * Flag for indicate if device has a rear camera available */ - boolean hasRearCam; + private boolean hasRearCam; + + /** + * Barcode scanner + */ + private IntentIntegrator integrator; /* (non-Javadoc) * @see es.ugr.swad.swadroid.MenuExpandableListActivity#onCreate(android.os.Bundle) @@ -117,16 +118,6 @@ public void onScrollStateChanged(AbsListView absListView, int scrollState) { public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - /*boolean enable = true; - if ((lvUsers != null) && (lvUsers.getChildCount() > 0)) { - - // check if the first item of the list is visible - boolean firstItemVisible = lvUsers.getFirstVisiblePosition() == 0; - // check if the top of the first item is visible - boolean topOfFirstItemVisible = lvUsers.getChildAt(0).getTop() == 0; - // enabling or disabling the refresh layout - enable = firstItemVisible && topOfFirstItemVisible; - }*/ boolean enable = (lvUsers != null) && (lvUsers.getChildCount() == 0); refreshLayout.setEnabled(enable); } @@ -144,6 +135,10 @@ public void onScroll(AbsListView absListView, int firstVisibleItem, eventCode = this.getIntent().getIntExtra("attendanceEventCode", 0); hasRearCam = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); + + integrator = new IntentIntegrator(this); + integrator.setCaptureActivity(ContinuousCaptureActivity.class); + integrator.setBeepEnabled(false); } /* (non-Javadoc) @@ -160,17 +155,7 @@ protected void onStart() { @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { - switch (requestCode) { - case Constants.ROLLCALL_USERS_DOWNLOAD_REQUEST_CODE: - refreshAdapter(); - break; - case Constants.ROLLCALL_USERS_SEND_REQUEST_CODE: - refreshAdapter(); - break; - case Constants.SCAN_QR_REQUEST_CODE: - refreshAdapter(); - break; - } + refreshAdapter(); } private void refreshAdapter() { @@ -280,10 +265,7 @@ private String getUsersCodes() { } private void scanQRCode() { - Intent activity = new Intent(Intents.Scan.ACTION); - activity.putExtra("SCAN_MODE", "QR_CODE_MODE,ONE_D_MODE"); - activity.putExtra("SCAN_FORMATS", "QR_CODE,ONE_D_FORMATS"); - startActivityForResult(activity, Constants.SCAN_QR_REQUEST_CODE); + integrator.initiateScan(); } @Override @@ -298,15 +280,7 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.action_scanQR: // Check if device has a rear camera if (hasRearCam) { - // check Android 6 permission - if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) - != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, - new String[]{Manifest.permission.CAMERA}, - Constants.PERMISSIONS_REQUEST_CAMERA); - } else { - scanQRCode(); - } + scanQRCode(); } else { //If the device has no rear camera available show error message error(TAG, getString(R.string.noCameraFound), null, false); @@ -370,16 +344,4 @@ public static int getEventCode() { return eventCode; } - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], - @NonNull int[] grantResults) { - switch (requestCode) { - case Constants.PERMISSIONS_REQUEST_CAMERA: { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - scanQRCode(); - } - } - } - } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java index 461fb5661..416f18467 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java @@ -142,28 +142,6 @@ public void onClick(View v) { notifyDataSetChanged(); } }); - /*holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - Cursor oldCursor; - - //Inserts attendance into database - dbHelper.insertAttendance(userCode, eventCode, isChecked); - - //Mark event status as "pending" - dbHelper.updateEventStatus(eventCode, "pending"); - - //Refresh ListView - dbCursor = dbHelper.getUsersEventCursor(eventCode); - if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD) { - oldCursor = swapCursor(dbCursor); - oldCursor.close(); - } else { - changeCursor(dbCursor); - } - notifyDataSetChanged(); - } - });*/ holder.image.setImageResource(R.drawable.usr_bl); if(userPhoto != null) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/QR.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/QR.java deleted file mode 100644 index b7e9271fc..000000000 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/QR.java +++ /dev/null @@ -1,47 +0,0 @@ -package es.ugr.swad.swadroid.utils; - -import android.app.Activity; -import android.content.Intent; -import android.graphics.Bitmap; -import android.util.DisplayMetrics; - -import com.google.zxing.BarcodeFormat; -import com.google.zxing.WriterException; -import com.google.zxing.client.android.Contents; -import com.google.zxing.client.android.Intents; -import com.google.zxing.client.android.encode.QRCodeEncoder; - -public class QR { - - public static Bitmap encode(Activity activity, String content) - throws WriterException { - - //Returns the size of the entire window, including status bar and title. - DisplayMetrics dm = new DisplayMetrics(); - activity.getWindowManager().getDefaultDisplay().getMetrics(dm); - - // Find screen size - /*WindowManager manager = (WindowManager) activity - .getSystemService(activity.WINDOW_SERVICE); - Display display = manager.getDefaultDisplay(); - Point point = new Point(); - display.getSize(point); - int width = point.x; - int height = point.y;*/ - int width = dm.widthPixels; - int height = dm.heightPixels; - int smallerDimension = width < height ? width : height; - //smallerDimension = smallerDimension * 3 / 4; - - Intent intent = new Intent(); - intent.setAction(Intents.Encode.ACTION); - intent.putExtra(Intents.Encode.FORMAT, BarcodeFormat.QR_CODE.toString()); - intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT); - intent.putExtra(Intents.Encode.DATA, content); - QRCodeEncoder qrcode = new QRCodeEncoder(activity, intent, - smallerDimension, false); - - return qrcode.encodeAsBitmap(); - } - -} diff --git a/SWADroid/src/main/res/layout/continuous_scan.xml b/SWADroid/src/main/res/layout/continuous_scan.xml new file mode 100644 index 000000000..c06bfca14 --- /dev/null +++ b/SWADroid/src/main/res/layout/continuous_scan.xml @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle index a10a7bc99..eb1a9aa20 100644 --- a/build.gradle +++ b/build.gradle @@ -4,8 +4,8 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:latest.release' - classpath 'org.ajoberstar:grgit:latest.release' + classpath 'com.android.tools.build:gradle:2.1.0' + classpath 'org.ajoberstar:grgit:1.7.0' } } From 88a5852a91b32bb98e7177d7d2b1301ed0007d66 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Tue, 7 Jun 2016 20:03:44 +0200 Subject: [PATCH 04/24] Updated Gradle plugin --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index eb1a9aa20..6caf4b926 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.1.0' + classpath 'com.android.tools.build:gradle:2.1.2' classpath 'org.ajoberstar:grgit:1.7.0' } } From 3bf0dea2b705baceff1e9f37d86e74c3b9f3a10b Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 8 Jun 2016 00:55:39 +0200 Subject: [PATCH 05/24] Updated README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e2fe2414b..da0156513 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ Copyright (C) 2010, Juan Miguel Boyero Corral [![Copyright and License](https://img.shields.io/badge/license-LGPLv3-green.svg?style=flat)](http://www.gnu.org/licenses/lgpl.html) SWADroid uses [Android DataFrameWork](http://code.google.com/p/androiddataframework/) library developed by [Javier Pérez Pacheco](http://www.javielinux.com/quiensoy.php) and licensed under [LGPLv3](http://www.gnu.org/licenses/lgpl.html). -[![Copyright and License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](http://www.opensource.org/licenses/mit-license.php) SWADroid uses [ksoap2-android](http://code.google.com/p/ksoap2-android) library developed by [Manfred Moser](https://github.com/mosabua) and licensed under [MIT](http://www.opensource.org/licenses/mit-license.php). +[![Copyright and License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](http://www.opensource.org/licenses/mit-license.php) SWADroid uses [ksoap2-android](https://github.com/simpligility/ksoap2-android) library developed by [Manfred Moser](https://github.com/mosabua) and licensed under [MIT](http://www.opensource.org/licenses/mit-license.php). -[![Copyright and License](https://img.shields.io/badge/license-Apache%202-green.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0) SWADroid uses [ZXing](http://code.google.com/p/zxing/) library developed by [Sean Owen](https://github.com/srowen) and licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). +[![Copyright and License](https://img.shields.io/badge/license-Apache%202-green.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0) SWADroid uses [ZXing Android Embedded](https://github.com/journeyapps/zxing-android-embedded) library developed by [journeyapps](https://github.com/journeyapps) and licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). [![Copyright and License](https://img.shields.io/badge/license-Apache%202-green.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0) SWADroid uses [Universal Image Loader](https://github.com/nostra13/Android-Universal-Image-Loader) library developed by [Sergey Tarasevich](https://github.com/nostra13) and licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). From 76696ff04410fd083edb3598a43d978c15b888c8 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Mon, 13 Jun 2016 23:07:15 +0200 Subject: [PATCH 06/24] Now it is mandatory to select a server on the login screen --- .../account/CreateAccountActivity.java | 91 ++++++++++--- .../swadroid/modules/login/LoginActivity.java | 124 +++++++++++++----- .../swadroid/preferences/Preferences.java | 8 +- .../src/main/res/layout/login_activity.xml | 2 +- SWADroid/src/main/res/values-es/servers.xml | 1 + SWADroid/src/main/res/values/servers.xml | 1 + 6 files changed, 164 insertions(+), 63 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java index d215b1ccd..569a9f1e3 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java @@ -22,6 +22,7 @@ import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; +import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; @@ -29,6 +30,7 @@ import android.util.Log; import android.view.KeyEvent; import android.view.View; +import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; @@ -72,7 +74,7 @@ public class CreateAccountActivity extends AppCompatActivity implements AdapterV private EditText mPasswordView; private EditText mServerTextView; private Spinner mServerView; - private ArrayAdapter serverAdapter; + private ArrayAdapter serverAdapter; @Override protected void onCreate(Bundle savedInstanceState) { @@ -93,8 +95,12 @@ protected void onCreate(Bundle savedInstanceState) { protected void onResume() { super.onResume(); - if(!mServerView.getSelectedItem().equals(Preferences.getServer())) { - setSelectedServer(Preferences.getServer()); + String server = Preferences.getServer(); + + if((server != null) && (!server.isEmpty()) && + !mServerView.getSelectedItem().equals(server)) { + + setSelectedServer(server); } } @@ -108,7 +114,9 @@ private void setupCreateAccountForm() { mNicknameView.setText(Preferences.getUserID()); mPasswordView = (EditText) findViewById(R.id.password); - mPasswordView.setText(""); + if (mPasswordView != null) { + mPasswordView.setText(""); + } mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { @@ -124,17 +132,37 @@ public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { mServerView = (Spinner) findViewById(R.id.serverSpinner); // Create an ArrayAdapter using the string array and a default spinner layout - serverAdapter = ArrayAdapter.createFromResource(this, - R.array.servers_array, android.R.layout.simple_spinner_item); + serverAdapter = new ArrayAdapter( + this, android.R.layout.simple_spinner_item, serversList) { + + @Override + public boolean isEnabled(int position){ + return position != 0; + } + + @Override + public View getDropDownView(int position, View convertView, + ViewGroup parent) { + + View view = super.getDropDownView(position, convertView, parent); + TextView tv = (TextView) view; + + if(position == 0) { + // Set the disable item text color + tv.setTextColor(Color.GRAY); + } + else { + tv.setTextColor(Color.BLACK); + } + return view; + } + }; // Specify the layout to use when the list of choices appears serverAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner mServerView.setAdapter(serverAdapter); mServerView.setOnItemSelectedListener(this); - if (serverAdapter.getItem(0).equals(Constants.SWAD_UGR_SERVER)) - mPasswordView.setError(getString(R.string.error_password_summaryUGR)); - mServerTextView = (EditText) findViewById(R.id.serverEditText); mServerTextView.setText(Preferences.getServer()); mServerTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() { @@ -164,12 +192,14 @@ public void onFocusChange(View v, boolean hasFocus) { mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message); - mCreateAccountButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - createAccount(); - } - }); + if (mCreateAccountButton != null) { + mCreateAccountButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + createAccount(); + } + }); + } } /** @@ -197,8 +227,10 @@ public void createAccount() { passwordValue = mPasswordView.getText().toString(); emailValue = mEmailView.getText().toString(); serverValue = mServerView.getSelectedItem().toString(); - - if(serverValue.contains(getString(R.string.otherMsg))) { + if(serverValue.equals(serversList.get(0))) { + spinnerSetError(getString(R.string.noServer)); + serverValue = ""; + } else if(serverValue.contains(getString(R.string.otherMsg))) { serverValue = mServerTextView.getText().toString().replaceFirst("^(http://|https://)",""); } @@ -373,14 +405,17 @@ public void onNothingSelected(AdapterView parent) { } private void setServer(int position) { - String serverValue = serverAdapter.getItem(position).toString(); + String serverValue = serverAdapter.getItem(position); //Reset password error mPasswordView.setError(null); - if (Constants.SWAD_UGR_SERVER.equals(serverValue)) - mPasswordView.setError(getString(R.string.error_password_summaryUGR)); - if(serverValue.contains(getString(R.string.otherMsg))) { + if (serverValue.isEmpty() || serverValue.equals(serversList.get(0))) { + spinnerSetError(getString(R.string.noServer)); + } else if (Constants.SWAD_UGR_SERVER.equals(serverValue)) { + mPasswordView.setError(getString(R.string.error_password_summaryUGR)); + Preferences.setServer(serverValue); + } else if(serverValue.contains(getString(R.string.otherMsg))) { mServerTextView.setText(Preferences.getServer()); mServerTextView.setVisibility(View.VISIBLE); } else { @@ -402,5 +437,19 @@ private void setSelectedServer(String server) { mServerView.setSelection(serverPosition); } + + private void spinnerSetError(String error) { + View selectedView = mServerView.getSelectedView(); + + if ((selectedView != null) && (selectedView instanceof TextView)) { + TextView selectedTextView = (TextView) selectedView; + + if ((error == null) || (error.isEmpty())) { + selectedTextView.setError(null); + } else { + selectedTextView.setError(error); + } + } + } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java index 022ac5925..0b415da1f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java @@ -31,6 +31,7 @@ import android.util.Log; import android.view.KeyEvent; import android.view.View; +import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; @@ -45,12 +46,12 @@ import java.util.List; import es.ugr.swad.swadroid.Constants; -import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.analytics.SWADroidTracker; import es.ugr.swad.swadroid.gui.DialogFactory; -import es.ugr.swad.swadroid.modules.password.RecoverPassword; import es.ugr.swad.swadroid.modules.account.CreateAccountActivity; +import es.ugr.swad.swadroid.modules.password.RecoverPassword; +import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.utils.Crypto; import es.ugr.swad.swadroid.utils.Utils; @@ -77,7 +78,7 @@ public class LoginActivity extends AppCompatActivity implements AdapterView.OnIt private View mLoginStatusView; private TextView mLoginStatusMessageView; private boolean mFromPreference = false; - private ArrayAdapter serverAdapter; + private ArrayAdapter serverAdapter; @Override protected void onCreate(Bundle savedInstanceState) { @@ -95,8 +96,12 @@ protected void onCreate(Bundle savedInstanceState) { protected void onResume() { super.onResume(); - if(!mServerView.getSelectedItem().equals(Preferences.getServer())) { - setSelectedServer(Preferences.getServer()); + String server = Preferences.getServer(); + + if((server != null) && (!server.isEmpty()) && + !mServerView.getSelectedItem().equals(server)) { + + setSelectedServer(server); } } @@ -112,7 +117,9 @@ private void setupLoginForm() { mIDView.setText(Preferences.getUserID()); mPasswordView = (EditText) findViewById(R.id.password); - mPasswordView.setText(""); + if (mPasswordView != null) { + mPasswordView.setText(""); + } mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { @@ -153,37 +160,65 @@ public void onFocusChange(View v, boolean hasFocus) { mServerView = (Spinner) findViewById(R.id.serverSpinner); // Create an ArrayAdapter using the string array and a default spinner layout - serverAdapter = ArrayAdapter.createFromResource(this, - R.array.servers_array, android.R.layout.simple_spinner_item); + serverAdapter = new ArrayAdapter( + this, android.R.layout.simple_spinner_item, serversList) { + + @Override + public boolean isEnabled(int position){ + return position != 0; + } + + @Override + public View getDropDownView(int position, View convertView, + ViewGroup parent) { + + View view = super.getDropDownView(position, convertView, parent); + TextView tv = (TextView) view; + + if(position == 0) { + // Set the disable item text color + tv.setTextColor(Color.GRAY); + } + else { + tv.setTextColor(Color.BLACK); + } + return view; + } + }; // Specify the layout to use when the list of choices appears serverAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner mServerView.setAdapter(serverAdapter); mServerView.setOnItemSelectedListener(this); - if (serverAdapter.getItem(0).equals(Constants.SWAD_UGR_SERVER)) - mPasswordView.setError(getString(R.string.error_password_summaryUGR)); - mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message); - mSignInButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - attemptLogin(); - } - }); - mLostPasswordButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - recoverPasswordDialog(); - } - }); - mCreateAccountButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - createAccount(); - } - }); + if (mSignInButton != null) { + mSignInButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + attemptLogin(); + } + }); + } + + if (mLostPasswordButton != null) { + mLostPasswordButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + recoverPasswordDialog(); + } + }); + } + + if (mCreateAccountButton != null) { + mCreateAccountButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + createAccount(); + } + }); + } } /** @@ -204,6 +239,7 @@ public void attemptLogin() { mIDView.setError(null); mPasswordView.setError(null); mServerTextView.setError(null); + spinnerSetError(null); boolean cancel = false; View focusView = null; @@ -213,7 +249,10 @@ public void attemptLogin() { passwordValue = mPasswordView.getText().toString(); serverValue = mServerView.getSelectedItem().toString(); - if(serverValue.contains(getString(R.string.otherMsg))) { + if(serverValue.equals(serversList.get(0))) { + spinnerSetError(getString(R.string.noServer)); + serverValue = ""; + } else if(serverValue.contains(getString(R.string.otherMsg))) { serverValue = mServerTextView.getText().toString().replaceFirst("^(http://|https://)",""); } @@ -440,14 +479,17 @@ public void onNothingSelected(AdapterView parent) { } private void setServer(int position) { - String serverValue = serverAdapter.getItem(position).toString(); + String serverValue = serverAdapter.getItem(position); //Reset password error mPasswordView.setError(null); - if (Constants.SWAD_UGR_SERVER.equals(serverValue)) - mPasswordView.setError(getString(R.string.error_password_summaryUGR)); - if(serverValue.contains(getString(R.string.otherMsg))) { + if (serverValue.isEmpty() || serverValue.equals(serversList.get(0))) { + spinnerSetError(getString(R.string.noServer)); + } else if (Constants.SWAD_UGR_SERVER.equals(serverValue)) { + mPasswordView.setError(getString(R.string.error_password_summaryUGR)); + Preferences.setServer(serverValue); + } else if(serverValue.contains(getString(R.string.otherMsg))) { mServerTextView.setText(Preferences.getServer()); mServerTextView.setVisibility(View.VISIBLE); } else { @@ -469,4 +511,18 @@ private void setSelectedServer(String server) { mServerView.setSelection(serverPosition); } + + private void spinnerSetError(String error) { + View selectedView = mServerView.getSelectedView(); + + if ((selectedView != null) && (selectedView instanceof TextView)) { + TextView selectedTextView = (TextView) selectedView; + + if ((error == null) || (error.isEmpty())) { + selectedTextView.setError(null); + } else { + selectedTextView.setError(error); + } + } + } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java index 0b10d5040..d1fd8a05c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java @@ -242,13 +242,7 @@ public static void setUserPassword(String userPassword) { * @return Server URL */ public static String getServer() { - String server = prefs.getString(SERVERPREF, Constants.DEFAULT_SERVER); - - if(server.equals("")) { - server = Constants.DEFAULT_SERVER; - } - - return server; + return prefs.getString(SERVERPREF, null); } /** diff --git a/SWADroid/src/main/res/layout/login_activity.xml b/SWADroid/src/main/res/layout/login_activity.xml index f8ad4b8bc..77a08a866 100644 --- a/SWADroid/src/main/res/layout/login_activity.xml +++ b/SWADroid/src/main/res/layout/login_activity.xml @@ -89,7 +89,7 @@ android:layout_toRightOf="@+id/serverTextView" android:layout_toEndOf="@id/serverTextView" android:layout_below="@id/password" - android:layout_alignTop="@+id/serverTextView" /> + android:layout_alignTop="@+id/serverTextView"/> + [Elegir uno] swad.ugr.es openswad.org Otro… diff --git a/SWADroid/src/main/res/values/servers.xml b/SWADroid/src/main/res/values/servers.xml index ae8bc3f46..42ec9bc89 100644 --- a/SWADroid/src/main/res/values/servers.xml +++ b/SWADroid/src/main/res/values/servers.xml @@ -1,6 +1,7 @@ + [Select one] swad.ugr.es openswad.org Other… From 25f106a1e91e0e62c8a21ad2c0f80bdefc6292d4 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Mon, 13 Jun 2016 23:33:59 +0200 Subject: [PATCH 07/24] Updated permissions in Manifest --- SWADroid/src/main/AndroidManifest.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SWADroid/src/main/AndroidManifest.xml b/SWADroid/src/main/AndroidManifest.xml index b6a10314f..8d7868721 100644 --- a/SWADroid/src/main/AndroidManifest.xml +++ b/SWADroid/src/main/AndroidManifest.xml @@ -5,10 +5,10 @@ - - - - + + + + From 72e2793f0b3b1890f18826f982d77128c7c6dc86 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 15 Jun 2016 20:14:09 +0200 Subject: [PATCH 08/24] Updated Android SDK to v24 --- SWADroid/build.gradle | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/SWADroid/build.gradle b/SWADroid/build.gradle index 21283ab7c..9fa6e7ee6 100644 --- a/SWADroid/build.gradle +++ b/SWADroid/build.gradle @@ -7,8 +7,8 @@ ext { } android { - compileSdkVersion 23 - buildToolsVersion "23.0.3" + compileSdkVersion 24 + buildToolsVersion "24" dexOptions { maxProcessCount=2 @@ -21,7 +21,7 @@ android { versionName gitVersionName minSdkVersion 9 - targetSdkVersion 23 + targetSdkVersion 24 android.applicationVariants.all { variant -> def appName @@ -56,8 +56,8 @@ android { } dependencies { - compile 'com.android.support:support-v4:23.4.0' - compile 'com.android.support:appcompat-v7:23.4.0' + compile 'com.android.support:support-v4:24.0.0' + compile 'com.android.support:appcompat-v7:24.0.0' compile 'com.google.android.gms:play-services-analytics:9.0.2' compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.1' compile 'commons-io:commons-io:2.5' From 53284447ca84cee6158e22ae69d7a120f4eb846c Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 15 Jun 2016 21:29:18 +0200 Subject: [PATCH 09/24] Show a warning on Marks screen if student ID has not yet been verified by the teacher or there are no marks currently available. Closes #209 --- .../com/android/dataframework/Entity.java | 4 +- .../android/dataframework/EntityCursor.java | 6 +- .../dataframework/core/DataFrameworkCore.java | 7 +-- .../java/es/ugr/swad/swadroid/SWADMain.java | 2 +- .../swadroid/analytics/SWADroidTracker.java | 2 +- .../swadroid/database/DataBaseHelper.java | 22 ++++---- .../modules/downloads/DirectoryNavigator.java | 25 +++++---- .../modules/downloads/DownloadsManager.java | 55 +++++++++++++------ .../swad/swadroid/modules/marks/GetMarks.java | 2 +- .../modules/tests/TestsConfigDownload.java | 2 +- .../swadroid/ssl/EasySSLSocketFactory.java | 12 ++-- .../webservices/IWebserviceClient.java | 8 +-- SWADroid/src/main/res/layout/navigation.xml | 3 +- SWADroid/src/main/res/values-es/strings.xml | 1 + SWADroid/src/main/res/values/strings.xml | 1 + 15 files changed, 83 insertions(+), 69 deletions(-) diff --git a/SWADroid/src/main/java/com/android/dataframework/Entity.java b/SWADroid/src/main/java/com/android/dataframework/Entity.java index 3bfd21afb..3f7ff212b 100644 --- a/SWADroid/src/main/java/com/android/dataframework/Entity.java +++ b/SWADroid/src/main/java/com/android/dataframework/Entity.java @@ -588,7 +588,7 @@ public boolean save() { Iterator> it = mMultilanguagesAttributes.entrySet().iterator(); while (it.hasNext()) { - Entry e = (Entry)it.next(); + Entry e = it.next(); args.put(e.getKey().toString(), e.getValue().toString()); } @@ -659,7 +659,7 @@ public void loadFromXml(String xml) try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); - XmlPullParser x = (XmlPullParser)factory.newPullParser(); + XmlPullParser x = factory.newPullParser(); x.setInput(new StringReader(xml)); int eventType = x.getEventType(); diff --git a/SWADroid/src/main/java/com/android/dataframework/EntityCursor.java b/SWADroid/src/main/java/com/android/dataframework/EntityCursor.java index c2bff9018..ecbf4faa2 100644 --- a/SWADroid/src/main/java/com/android/dataframework/EntityCursor.java +++ b/SWADroid/src/main/java/com/android/dataframework/EntityCursor.java @@ -456,11 +456,7 @@ public class EntityIterator implements Iterator { @Override public boolean hasNext() { - if (mCursor.isLast() || mCursor.isAfterLast()){ - return false; - }else{ - return true; - } + return !(mCursor.isLast() || mCursor.isAfterLast()); } @Override diff --git a/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java b/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java index 9b6c2f098..491edf601 100644 --- a/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java +++ b/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java @@ -139,10 +139,7 @@ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) } private boolean add(int version, int oldVersion, int newVersion) { - if (version>oldVersion && version<=newVersion) - return true; - else - return false; + return version > oldVersion && version <= newVersion; } } @@ -361,7 +358,7 @@ public void backup(String file, boolean forceBackup) throws XmlPullParserExcepti public void restore(String file) throws XmlPullParserException, IOException { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); - XmlPullParser x = (XmlPullParser)factory.newPullParser(); + XmlPullParser x = factory.newPullParser(); x.setInput(new FileReader(file)); insertXML(x); } catch (IOException e) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java index bcb143703..e032b6932 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java @@ -447,7 +447,7 @@ private void createMenu() { if (listCourses.size() != 0) { Course courseSelected; if (Courses.getSelectedCourseCode() != -1) { - courseSelected = (Course) dbHelper.getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(Courses.getSelectedCourseCode())); + courseSelected = dbHelper.getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(Courses.getSelectedCourseCode())); } else { int lastSelected = Preferences.getLastCourseSelected(); if (lastSelected != -1 && lastSelected < listCourses.size()) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java index f4bd598b3..99f310074 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java @@ -52,7 +52,7 @@ public class SWADroidTracker { * storing them all in Application object helps ensure that they are created only once per * application instance. */ - public static enum TrackerName { + public enum TrackerName { APP_TRACKER, // Tracker used only in this app. GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking. ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company. diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java index 123497e22..7e568e16d 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java @@ -325,7 +325,7 @@ private T createObjectByTable(String table, Entity ent) { Utils.parseStringBool(ent.getString("seenRemote"))); } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTIONS)) { id = ent.getInt("id"); - PairTable q = (PairTable) getRow(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod", Long.toString(id)); + PairTable q = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod", Long.toString(id)); if (q != null) { o = new TestQuestion(id, @@ -340,7 +340,7 @@ private T createObjectByTable(String table, Entity ent) { } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_ANSWERS)) { id = ent.getId(); int ansInd = ent.getInt("ansInd"); - PairTable a = (PairTable) getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod", Long.toString(id)); + PairTable a = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod", Long.toString(id)); if (a != null) { o = new TestAnswer(id, @@ -354,7 +354,7 @@ private T createObjectByTable(String table, Entity ent) { } } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_TAGS)) { id = ent.getInt("tagCod"); - TestTag t = (TestTag) getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS, "tagCod", Long.toString(id)); + TestTag t = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS, "tagCod", Long.toString(id)); if (t != null) { o = new TestTag(id, @@ -725,7 +725,7 @@ public Group getGroup(long groupId) { List rows = db.getEntityList(table, "id = " + groupId); Group g = null; if (rows != null) - g = (Group) createObjectByTable(table, rows.get(0)); + g = createObjectByTable(table, rows.get(0)); return g; } @@ -828,7 +828,7 @@ public List getUserLoggedGroups(long courseCode) { List groups = new ArrayList(); if (!groupCodes.isEmpty()) { for (Long groupCode : groupCodes) { - Group g = (Group) getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCode)); + Group g = getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCode)); if (g.isMember()) groups.add(g); } } @@ -862,7 +862,7 @@ public Cursor getPracticeGroups(long courseCode) { */ public boolean isUserEnrolledCourse(String userID, long selectedCourseCode) { boolean enrolled = false; - User u = (User) getRow(DataBaseHelper.DB_TABLE_USERS, "userID", userID); + User u = getRow(DataBaseHelper.DB_TABLE_USERS, "userID", userID); if (u != null) { String sentencia = "SELECT userCode AS _id, crsCod" + @@ -898,7 +898,7 @@ public List getGroups(long courseCode, String... filter) { List groups = new ArrayList(groupCodes.getCount()); while (groupCodes.moveToNext()) { - Group group = (Group) this.getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCodes.getInt(0))); + Group group = this.getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCodes.getInt(0))); groups.add(group); } return groups; @@ -1146,7 +1146,7 @@ public boolean insertGroup(Group g, long courseCode) { //update all the relationship long groupCode = g.getId(); rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_COURSES, "grpCod =" + groupCode); - Course course = (Course) getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(courseCode)); + Course course = getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(courseCode)); //course code is a foreign key. Therefore, to avoid a database error, //it should not insert/modify rows in the relationship table if the course does not exists @@ -1187,7 +1187,7 @@ public boolean insertGroup(Group g, long courseCode) { */ public boolean insertGroupType(GroupType gt) { boolean returnValue = true; - GroupType row = (GroupType) getRow(DataBaseHelper.DB_TABLE_GROUP_TYPES, "id", String.valueOf(gt.getId())); + GroupType row = getRow(DataBaseHelper.DB_TABLE_GROUP_TYPES, "id", String.valueOf(gt.getId())); if (row == null) { insertEntity(DataBaseHelper.DB_TABLE_GROUP_TYPES, gt); } else { @@ -1742,7 +1742,7 @@ public boolean updateGroup(long groupCode, long courseCode, Group currentGroup, insertEntity(DataBaseHelper.DB_TABLE_GROUPS, currentGroup, ent); rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_COURSES, "grpCod =" + groupCode); - Course course = (Course) getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(courseCode)); + Course course = getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(courseCode)); //course code is a foreign key. Therefore, to avoid a database error, //it should not insert/modify rows in the relationship table if the course does not exists if (course != null) { @@ -1758,7 +1758,7 @@ public boolean updateGroup(long groupCode, long courseCode, Group currentGroup, } else returnValue = false; if (groupTypeCode.length > 0) { - GroupType groupType = (GroupType) getRow(DataBaseHelper.DB_TABLE_GROUP_TYPES, "id", String.valueOf(groupTypeCode[0])); + GroupType groupType = getRow(DataBaseHelper.DB_TABLE_GROUP_TYPES, "id", String.valueOf(groupTypeCode[0])); //group type code is a foreign key. Therefore, to avoid a database error, //it should not insert/modify rows in the relationship table if the group type does not exists if (groupType != null) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java index 4986b0ece..a08cb5c8a 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java @@ -206,18 +206,19 @@ private List getItems(Node node) { String tag = data.getNodeName(); Node firstChild = data.getFirstChild(); if (firstChild != null) { - if (tag.equals("code")) { - fileCode = Long.valueOf(firstChild.getNodeValue()); - } else if (tag.equals("size")) { - size = Integer.parseInt(firstChild.getNodeValue()); - } else if (tag.equals("time")) { - time = Long.valueOf(firstChild.getNodeValue()); - } else if (tag.equals("license")) { - license = firstChild.getNodeValue(); - } else if (tag.equals("publisher")) { - publisher = firstChild.getNodeValue(); - } else if (tag.equals("photo")) { - photo = firstChild.getNodeValue(); + switch (tag) { + case "code": + case "time": + time = Long.valueOf(firstChild.getNodeValue()); + break; + case "license": + case "publisher": + case "photo": + photo = firstChild.getNodeValue(); + break; + case "size": + size = Integer.parseInt(firstChild.getNodeValue()); + break; } } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java index 7bf9354dc..0e313a548 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java @@ -118,7 +118,7 @@ public class DownloadsManager extends MenuActivity { */ private boolean refresh = false; - private TextView noConnectionText; + private TextView messageText; private GridView grid; private TextView currentPathText; @@ -139,7 +139,7 @@ public class DownloadsManager extends MenuActivity { /** * Indicates if the menu no connection is visible */ - private boolean noConnectionView = false; + private boolean messageView = false; /** * Indicates that the current state should be saved in case the activity is brought to background */ @@ -212,7 +212,7 @@ protected void onCreate(Bundle savedInstanceState) { this.tree = savedInstanceState.getString("tree"); String path = savedInstanceState.getString("path"); this.navigator = new DirectoryNavigator(getApplicationContext(), this.tree); - if (path.equals("/")) { + if ("/".equals(path)) { int firstBar = path.indexOf('/', 0); int nextBar = path.indexOf('/', firstBar + 1); while (nextBar != -1) { @@ -231,7 +231,7 @@ protected void onCreate(Bundle savedInstanceState) { downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode", Constants.DOCUMENTS_AREA_CODE); - noConnectionText = (TextView) this.findViewById(R.id.noConnectionText); + messageText = (TextView) this.findViewById(R.id.messageText); grid = (GridView) this.findViewById(R.id.gridview); grid.setOnItemClickListener((new OnItemClickListener() { @@ -355,7 +355,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { setMainView(); } else { refresh = false; - if (!noConnectionView) + if (!messageView) refresh(); else setMainView(); @@ -411,14 +411,16 @@ public void onClick(DialogInterface dialog, int id) { } } - /** * Having connection is mandatory for the Download Module. * Therefore when there is not connection, the grid of nodes is disabled and instead it is showed an info messages */ private void setNoConnectionView() { - noConnectionView = true; - noConnectionText.setVisibility(View.VISIBLE); + messageView = true; + + messageText.setText(R.string.noConnectionMsg); + messageText.setVisibility(View.VISIBLE); + grid.setVisibility(View.GONE); this.findViewById(R.id.groupSpinner).setVisibility(View.GONE); @@ -427,18 +429,36 @@ private void setNoConnectionView() { this.saveState = true; this.previousConnection = false; + } + + /** + * Having connection is mandatory for the Download Module. + * Therefore when there is not connection, the grid of nodes is disabled and instead it is showed an info messages + */ + private void setNoMarksView() { + messageView = true; + + messageText.setText(R.string.noMarksMsg); + messageText.setVisibility(View.VISIBLE); + + grid.setVisibility(View.GONE); + this.findViewById(R.id.groupSpinner).setVisibility(View.GONE); + + getSupportActionBar().setSubtitle(Courses.getSelectedCourseShortName()); + + this.saveState = true; + this.previousConnection = true; } /** * This method set the grid of nodes visible and paints the directory tree in its root node */ private void setMainView() { - - noConnectionText.setVisibility(View.GONE); + messageText.setVisibility(View.GONE); grid.setVisibility(View.VISIBLE); - noConnectionView = false; + messageView = false; currentPathText = (TextView) this.findViewById(R.id.path); @@ -447,6 +467,13 @@ private void setMainView() { navigator = new DirectoryNavigator(getApplicationContext(), tree); items = navigator .goToRoot(); + + /* Show a message if there are no marks currently available + * or the student ID has not been verified by the teacher + */ + if(items.isEmpty()) { + setNoMarksView(); + } } else { items = navigator.goToCurrentDirectory(); } @@ -588,11 +615,7 @@ private int checkMediaAvailability() { * @return False if not downloaded, True otherwise. */ private boolean isDownloaded(File f) { - if (f.exists() && f.length() == fileSize) { - return true; - } else { - return false; - } + return f.exists() && f.length() == fileSize; } /** diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/GetMarks.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/GetMarks.java index bd376c190..fff2431cb 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/GetMarks.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/GetMarks.java @@ -151,7 +151,7 @@ protected void requestService() @Override protected void postConnect() { AlertDialog errorDialog; - String errorMsg = getString(R.string.errorBadFileCodeMsg);; + String errorMsg = getString(R.string.errorBadFileCodeMsg); if(hasError) { errorDialog = DialogFactory.createErrorDialog(this, TAG, errorMsg, null, false, false, new DialogInterface.OnClickListener() { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java index 73b7d2527..4a7bcfe90 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java @@ -124,7 +124,7 @@ protected void requestService() throws Exception { Integer defQuestions = Integer.valueOf(soap.getProperty("defQuestions").toString()); Integer maxQuestions = Integer.valueOf(soap.getProperty("maxQuestions").toString()); String feedback = soap.getProperty("feedback").toString(); - Test tDB = (Test) dbHelper.getRow(DataBaseHelper.DB_TABLE_TEST_CONFIG, "id", + Test tDB = dbHelper.getRow(DataBaseHelper.DB_TABLE_TEST_CONFIG, "id", Long.toString(Courses.getSelectedCourseCode())); //If exists a test configuration for this course, remove from database diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java index abbcc4802..6ccffeb14 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java @@ -77,8 +77,7 @@ public Socket connectSocket(Socket sock, int localPort, HttpParams params) - throws IOException, UnknownHostException, ConnectTimeoutException - { + throws IOException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); @@ -121,9 +120,7 @@ public boolean isSecure(Socket socket) throws IllegalArgumentException { public Socket createSocket(Socket socket, String host, int port, - boolean autoClose) throws IOException, - UnknownHostException - { + boolean autoClose) throws IOException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } @@ -154,15 +151,14 @@ public String[] getSupportedCipherSuites() { } @Override - public Socket createSocket(String host, int port) throws IOException, - UnknownHostException { + public Socket createSocket(String host, int port) throws IOException { return getSSLContext().getSocketFactory().createSocket(host, port); } @Override public Socket createSocket(String host, int port, InetAddress localHost, - int localPort) throws IOException, UnknownHostException { + int localPort) throws IOException { return getSSLContext().getSocketFactory().createSocket(host, port, localHost, localPort); } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/IWebserviceClient.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/IWebserviceClient.java index 2d74378aa..9b847752d 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/IWebserviceClient.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/IWebserviceClient.java @@ -25,11 +25,11 @@ * */ public interface IWebserviceClient { - public void createRequest(); + void createRequest(); - public void addParam(String param, Object value); + void addParam(String param, Object value); - public void setMETHOD_NAME(String METHOD_NAME); + void setMETHOD_NAME(String METHOD_NAME); - public Object getResult(); + Object getResult(); } diff --git a/SWADroid/src/main/res/layout/navigation.xml b/SWADroid/src/main/res/layout/navigation.xml index 9e12d4bb0..0943013d3 100644 --- a/SWADroid/src/main/res/layout/navigation.xml +++ b/SWADroid/src/main/res/layout/navigation.xml @@ -11,12 +11,11 @@ Nuevo favorito a mis mensajes sociales Nueva compartición de mis mensajes sociales Nueva mención + No hay calificaciones disponibles o el DNI del estudiante no ha sido verificado por el profesor \ No newline at end of file diff --git a/SWADroid/src/main/res/values/strings.xml b/SWADroid/src/main/res/values/strings.xml index 2e0c3e3bc..0ca180cad 100644 --- a/SWADroid/src/main/res/values/strings.xml +++ b/SWADroid/src/main/res/values/strings.xml @@ -324,5 +324,6 @@ Fav to one of my social publishings Sharing of one of my social posts Mention to me in a social publishing + No marks currently available or the student ID has not been verified by the teacher \ No newline at end of file From 735577e345b712a3e30dcad5064ec1d987b9a286 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 15 Jun 2016 21:34:55 +0200 Subject: [PATCH 10/24] Request camera permission on RollCall module --- .../modules/rollcall/UsersActivity.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java index 7d1980c9f..4f2a50b69 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java @@ -21,6 +21,7 @@ package es.ugr.swad.swadroid.modules.rollcall; +import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; @@ -30,6 +31,9 @@ import android.os.Build; import android.os.Bundle; import android.os.Handler; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; +import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.Menu; @@ -280,7 +284,15 @@ public boolean onOptionsItemSelected(MenuItem item) { case R.id.action_scanQR: // Check if device has a rear camera if (hasRearCam) { - scanQRCode(); + // check Android 6 permission + if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.CAMERA}, + Constants.PERMISSIONS_REQUEST_CAMERA); + } else { + scanQRCode(); + } } else { //If the device has no rear camera available show error message error(TAG, getString(R.string.noCameraFound), null, false); @@ -344,4 +356,17 @@ public static int getEventCode() { return eventCode; } + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], + @NonNull int[] grantResults) { + switch (requestCode) { + case Constants.PERMISSIONS_REQUEST_CAMERA: { + if (grantResults.length > 0 + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + scanQRCode(); + } + } + } + } + } From ce027a4d12c26e013decd2b76ea71399fc59d8af Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Wed, 15 Jun 2016 23:38:57 +0200 Subject: [PATCH 11/24] Closes #209 --- .../modules/downloads/DownloadsManager.java | 37 +++++++++++++------ SWADroid/src/main/res/values-es/strings.xml | 4 +- SWADroid/src/main/res/values/strings.xml | 4 +- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java index 0e313a548..b9080b43d 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java @@ -432,13 +432,31 @@ private void setNoConnectionView() { } /** - * Having connection is mandatory for the Download Module. - * Therefore when there is not connection, the grid of nodes is disabled and instead it is showed an info messages + * Documents: + * + * Show a warning on Documents screen if there are no documents currently available. + * + * Marks: + * + * Show a warning on Marks screen if student ID has not yet been verified by the teacher or + * there are no marks currently available. */ - private void setNoMarksView() { + private void setNoDocumentsView() { + int resNoDocuments; + + if(downloadsAreaCode == Constants.MARKS_AREA_CODE) { + if (Login.getCurrentUserRole() == Constants.STUDENT_TYPE_CODE) + resNoDocuments = R.string.noMarksStudentMsg; + else { + resNoDocuments = R.string.noMarksTeacherMsg; + } + } else { + resNoDocuments = R.string.noDocumentsMsg; + } + messageView = true; - messageText.setText(R.string.noMarksMsg); + messageText.setText(resNoDocuments); messageText.setVisibility(View.VISIBLE); grid.setVisibility(View.GONE); @@ -468,11 +486,8 @@ private void setMainView() { items = navigator .goToRoot(); - /* Show a message if there are no marks currently available - * or the student ID has not been verified by the teacher - */ if(items.isEmpty()) { - setNoMarksView(); + setNoDocumentsView(); } } else { items = navigator.goToCurrentDirectory(); @@ -771,15 +786,15 @@ private void setupActionBar() { } switch (downloadsAreaCode) { - case 1: + case Constants.DOCUMENTS_AREA_CODE: setTitle(R.string.documentsDownloadModuleLabel); getSupportActionBar().setIcon(R.drawable.folder); break; - case 2: + case Constants.SHARE_AREA_CODE: setTitle(R.string.sharedsDownloadModuleLabel); getSupportActionBar().setIcon(R.drawable.folder_users); break; - case 3: + case Constants.MARKS_AREA_CODE: setTitle(R.string.marksModuleLabel); getSupportActionBar().setIcon(R.drawable.grades); break; diff --git a/SWADroid/src/main/res/values-es/strings.xml b/SWADroid/src/main/res/values-es/strings.xml index dd11bd5d9..4f4fccf37 100644 --- a/SWADroid/src/main/res/values-es/strings.xml +++ b/SWADroid/src/main/res/values-es/strings.xml @@ -315,6 +315,8 @@ Nuevo favorito a mis mensajes sociales Nueva compartición de mis mensajes sociales Nueva mención - No hay calificaciones disponibles o el DNI del estudiante no ha sido verificado por el profesor + No hay calificaciones disponibles o el DNI del estudiante no ha sido verificado por el profesor + No hay calificaciones disponibles + No hay documentos disponibles \ No newline at end of file diff --git a/SWADroid/src/main/res/values/strings.xml b/SWADroid/src/main/res/values/strings.xml index 0ca180cad..b7e944563 100644 --- a/SWADroid/src/main/res/values/strings.xml +++ b/SWADroid/src/main/res/values/strings.xml @@ -324,6 +324,8 @@ Fav to one of my social publishings Sharing of one of my social posts Mention to me in a social publishing - No marks currently available or the student ID has not been verified by the teacher + No marks currently available or the student ID has not been verified by the teacher + No marks currently available + No documents currently available \ No newline at end of file From 289d8baf4909a5c72625628c20da5c59e4c906cb Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Sun, 19 Jun 2016 22:08:52 +0200 Subject: [PATCH 12/24] Reordered the server list --- SWADroid/src/main/res/values-es/servers.xml | 2 +- SWADroid/src/main/res/values/servers.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/SWADroid/src/main/res/values-es/servers.xml b/SWADroid/src/main/res/values-es/servers.xml index 018aaec1d..d0d11ae13 100644 --- a/SWADroid/src/main/res/values-es/servers.xml +++ b/SWADroid/src/main/res/values-es/servers.xml @@ -2,8 +2,8 @@ [Elegir uno] - swad.ugr.es openswad.org + swad.ugr.es Otro… \ No newline at end of file diff --git a/SWADroid/src/main/res/values/servers.xml b/SWADroid/src/main/res/values/servers.xml index 42ec9bc89..690b21ace 100644 --- a/SWADroid/src/main/res/values/servers.xml +++ b/SWADroid/src/main/res/values/servers.xml @@ -2,8 +2,8 @@ [Select one] - swad.ugr.es openswad.org + swad.ugr.es Other… \ No newline at end of file From 001ef17e87e75ef705ae643806ad7ca877d5c6b1 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Sun, 19 Jun 2016 22:39:09 +0200 Subject: [PATCH 13/24] Restored 1 second delay when scanning QR codes --- .../rollcall/ContinuousCaptureActivity.java | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java index f958b213c..3e6876174 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java @@ -44,18 +44,46 @@ public class ContinuousCaptureActivity extends AppCompatActivity { */ private static final int SCAN_TEXT_SIZE = 18; + /** + * Scan delay + */ private static final long BULK_MODE_SCAN_DELAY_MS = 1000L; + /** + * Database helper + */ private static DataBaseHelper dbHelper; + + /** + * Cryptographic helper + */ private static Crypto crypto; + /** + * Code view + */ private CompoundBarcodeView barcodeView; - private MediaPlayer mediaPlayer; + /** + * Callback function called when a code is scanned + */ private BarcodeCallback callback = new BarcodeCallback() { + private long lastTimestamp = 0; + @Override public void barcodeResult(BarcodeResult result) { - handleDecode(result); + long currentTime = System.currentTimeMillis(); + long diffLastTimestamp = currentTime - lastTimestamp; + + if (result.getText() != null) { + if(diffLastTimestamp < BULK_MODE_SCAN_DELAY_MS) { + Log.d(TAG, "Too soon after the last barcode - ignore: " + diffLastTimestamp + " ms"); + return; + } + + handleDecode(result); + lastTimestamp = currentTime; + } } @Override @@ -112,6 +140,7 @@ public void handleDecode(BarcodeResult result) { boolean validContent = Utils.isValidNickname(qrContent); User u = null; + MediaPlayer mediaPlayer; if (validContent) { u = dbHelper.getUser("userNickname", crypto.encrypt(qrContent.substring(1))); From f8ad546f64bda3d41b97a50abcf46b6f12737b59 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Tue, 28 Jun 2016 19:38:47 +0200 Subject: [PATCH 14/24] Updated play-services-analytics dependency --- SWADroid/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SWADroid/build.gradle b/SWADroid/build.gradle index 9fa6e7ee6..f7d7c60af 100644 --- a/SWADroid/build.gradle +++ b/SWADroid/build.gradle @@ -58,7 +58,7 @@ android { dependencies { compile 'com.android.support:support-v4:24.0.0' compile 'com.android.support:appcompat-v7:24.0.0' - compile 'com.google.android.gms:play-services-analytics:9.0.2' + compile 'com.google.android.gms:play-services-analytics:9.2.0' compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.1' compile 'commons-io:commons-io:2.5' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' From 8105c638f1abef68ba28a6eb44daa377543c773f Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Fri, 1 Jul 2016 17:22:13 +0200 Subject: [PATCH 15/24] Replaced deprecated getColor method --- .../EnrollmentExpandableListAdapter.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java index 30808f71e..5a87be939 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java @@ -20,6 +20,7 @@ import android.content.Context; import android.graphics.Typeface; +import android.support.v4.content.ContextCompat; import android.support.v4.util.LongSparseArray; import android.view.LayoutInflater; import android.view.View; @@ -138,9 +139,9 @@ public View getChildView(int groupPosition, int childPosition, boolean isCurrentMember = realMembership.get(groupTypeCode)[childPosition]; if (isCurrentMember) { - holder.linearLayout.setBackgroundColor(context.getResources().getColor(R.color.lightskyblue)); + holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.lightskyblue)); } else { - holder.linearLayout.setBackgroundColor(context.getResources().getColor(android.R.color.white)); + holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.white)); } @@ -171,30 +172,30 @@ public View getChildView(int groupPosition, int childPosition, if ((open != 0 && freeSpot) || role == Constants.TEACHER_TYPE_CODE) { //Teachers can enroll even on closed groups holder.checkBox.setEnabled(true); - holder.checkBox.setTextColor(context.getResources().getColor(android.R.color.black)); + holder.checkBox.setTextColor(ContextCompat.getColor(context, android.R.color.black)); holder.imagePadlock.setEnabled(true); holder.nStudentText.setEnabled(true); - holder.nStudentText.setTextColor(context.getResources().getColor(R.color.sgilight_gray_32)); + holder.nStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); holder.maxStudentText.setEnabled(true); - holder.maxStudentText.setTextColor(context.getResources().getColor(R.color.sgilight_gray_32)); + holder.maxStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); holder.radioButton.setEnabled(true); - holder.radioButton.setTextColor(context.getResources().getColor(android.R.color.black)); + holder.radioButton.setTextColor(ContextCompat.getColor(context, android.R.color.black)); holder.linearLayout.setEnabled(true); holder.vacantsText.setEnabled(true); - holder.vacantsText.setTextColor(context.getResources().getColor(R.color.sgilight_gray_32)); + holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); } else { holder.checkBox.setEnabled(false); - holder.checkBox.setTextColor(context.getResources().getColor(R.color.sgilight_gray)); + holder.checkBox.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); holder.imagePadlock.setEnabled(false); holder.nStudentText.setEnabled(false); - holder.nStudentText.setTextColor(context.getResources().getColor(R.color.sgilight_gray)); + holder.nStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); holder.maxStudentText.setEnabled(false); - holder.maxStudentText.setTextColor(context.getResources().getColor(R.color.sgilight_gray)); + holder.maxStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); holder.radioButton.setEnabled(false); - holder.radioButton.setTextColor(context.getResources().getColor(R.color.sgilight_gray)); + holder.radioButton.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); holder.linearLayout.setEnabled(false); holder.vacantsText.setEnabled(false); - holder.vacantsText.setTextColor(context.getResources().getColor(R.color.sgilight_gray)); + holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); } //for multiple inscriptions the groups should be checkboxes to allow multiple choice //otherwise the groups should be radio button to allow just a single choice @@ -229,7 +230,7 @@ public View getChildView(int groupPosition, int childPosition, holder.maxStudentText.setText(context.getString(R.string.maxStudent) + ": " + String.valueOf(maxStudents)); holder.vacantsText.setText(context.getString(R.string.vacants) + ": " + String.valueOf(vacants)); if (vacants == 0) { - holder.vacantsText.setTextColor(context.getResources().getColor(R.color.sgi_salmon)); + holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgi_salmon)); holder.vacantsText.setTypeface(null, Typeface.BOLD); } else holder.vacantsText.setTypeface(null, Typeface.NORMAL); From 16c6a1cc25ca2c80f9fa1c9b83de7708c2639d5d Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Fri, 1 Jul 2016 17:24:15 +0200 Subject: [PATCH 16/24] Remove blue background color for selected groups in Enrollment module --- .../groups/EnrollmentExpandableListAdapter.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java index 5a87be939..48e27ff43 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java @@ -136,14 +136,7 @@ public View getChildView(int groupPosition, int childPosition, ArrayList children = this.children.get(groupTypeCode); Group group = children.get(childPosition); - - boolean isCurrentMember = realMembership.get(groupTypeCode)[childPosition]; - if (isCurrentMember) { - holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.lightskyblue)); - } else { - holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.white)); - } - + holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.white)); //Data from Group String groupName = group.getGroupName(); @@ -152,7 +145,7 @@ public View getChildView(int groupPosition, int childPosition, int open = group.getOpen(); int member = group.getMember(); - // Para porde hacer click en el checkbox + // To click the checkbox Group g = (Group) getChild(groupPosition, childPosition); holder.checkBox.setTag(g); From d98148c06d93023b92a62d24c6601f2d4cc83e89 Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Fri, 1 Jul 2016 17:43:28 +0200 Subject: [PATCH 17/24] Refactored code in Enrollment module --- .../EnrollmentExpandableListAdapter.java | 58 +++++++------------ .../swadroid/modules/groups/GroupTypes.java | 2 +- .../swad/swadroid/modules/groups/Groups.java | 8 +-- .../modules/groups/MyGroupsManager.java | 2 +- .../swadroid/modules/groups/SendMyGroups.java | 15 +++-- 5 files changed, 31 insertions(+), 54 deletions(-) diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java index 48e27ff43..0080919cc 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/EnrollmentExpandableListAdapter.java @@ -48,13 +48,14 @@ * There are two kind of layout: one for the groups and one for the children * * @author Helena Rodriguez Gijon + * @author Juan Miguel Boyero Corral */ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter { private LongSparseArray> children = null; private ArrayList groups = null; - private final LongSparseArray realMembership = new LongSparseArray(); + private final LongSparseArray realMembership = new LongSparseArray<>(); private int role = -1; private int layoutGroup = 0; @@ -148,14 +149,9 @@ public View getChildView(int groupPosition, int childPosition, // To click the checkbox Group g = (Group) getChild(groupPosition, childPosition); holder.checkBox.setTag(g); - - boolean freeSpot = false; - if (maxStudents != -1) { - if (group.getCurrentStudents() < maxStudents) - freeSpot = true; - } else { //if maxStudent == -1, there is not limit of students in this groups - freeSpot = true; - } + + //if maxStudent == -1, there is not limit of students in this groups + boolean freeSpot = ((maxStudents == -1) || (group.getCurrentStudents() < maxStudents)); if (open != 0) { holder.imagePadlock.setImageResource(R.drawable.padlock_green); @@ -163,33 +159,29 @@ public View getChildView(int groupPosition, int childPosition, holder.imagePadlock.setImageResource(R.drawable.padlock_red); } - if ((open != 0 && freeSpot) || role == Constants.TEACHER_TYPE_CODE) { //Teachers can enroll even on closed groups - holder.checkBox.setEnabled(true); + boolean canEnroll = ((open != 0 && freeSpot) || role == Constants.TEACHER_TYPE_CODE); + if(canEnroll) { holder.checkBox.setTextColor(ContextCompat.getColor(context, android.R.color.black)); - holder.imagePadlock.setEnabled(true); - holder.nStudentText.setEnabled(true); holder.nStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); - holder.maxStudentText.setEnabled(true); holder.maxStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); - holder.radioButton.setEnabled(true); holder.radioButton.setTextColor(ContextCompat.getColor(context, android.R.color.black)); - holder.linearLayout.setEnabled(true); - holder.vacantsText.setEnabled(true); holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray_32)); } else { - holder.checkBox.setEnabled(false); holder.checkBox.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); - holder.imagePadlock.setEnabled(false); - holder.nStudentText.setEnabled(false); holder.nStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); - holder.maxStudentText.setEnabled(false); holder.maxStudentText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); - holder.radioButton.setEnabled(false); holder.radioButton.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); - holder.linearLayout.setEnabled(false); - holder.vacantsText.setEnabled(false); holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgilight_gray)); } + + holder.checkBox.setEnabled(canEnroll); + holder.imagePadlock.setEnabled(canEnroll); + holder.nStudentText.setEnabled(canEnroll); + holder.maxStudentText.setEnabled(canEnroll); + holder.radioButton.setEnabled(canEnroll); + holder.linearLayout.setEnabled(canEnroll); + holder.vacantsText.setEnabled(canEnroll); + //for multiple inscriptions the groups should be checkboxes to allow multiple choice //otherwise the groups should be radio button to allow just a single choice //Teachers can enroll in multiple groups even if the enrollment type for the group type is single @@ -197,25 +189,15 @@ public View getChildView(int groupPosition, int childPosition, holder.checkBox.setVisibility(View.GONE); holder.radioButton.setVisibility(View.VISIBLE); - holder.radioButton.setText(groupName); - if (member != 0) { - holder.radioButton.setChecked(true); - } else { - holder.radioButton.setChecked(false); - } } else { //multiple inscriptions : holder.checkBox.setVisibility(View.VISIBLE); holder.radioButton.setVisibility(View.GONE); - - holder.checkBox.setText(groupName); - if (member != 0) { - holder.checkBox.setChecked(true); - } else { - holder.checkBox.setChecked(false); - } } + holder.checkBox.setText(groupName); + holder.checkBox.setChecked(member != 0); + holder.nStudentText.setText(context.getString(R.string.numStudent) + ": " + String.valueOf(students)); if (maxStudents != -1) { @@ -372,7 +354,7 @@ public String getChosenGroupCodesAsString() { } public ArrayList getChosenGroupCodes() { - ArrayList groupCodes = new ArrayList(); + ArrayList groupCodes = new ArrayList<>(); Long key; for (int i = 0; i < children.size(); i++) { key = children.keyAt(i); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java index 2fde92bef..1a6075ae3 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java @@ -88,7 +88,7 @@ protected void requestService() throws Exception { if (result != null) { //Stores groups data returned by webservice response - List groupsSWAD = new ArrayList(); + List groupsSWAD = new ArrayList<>(); ArrayList res = new ArrayList((Vector) result); SoapObject soap = (SoapObject) res.get(1); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java index 1982040d6..fba63507f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java @@ -50,10 +50,6 @@ * @author Antonio Aguilera Malagon */ public class Groups extends Module { - /** - * Groups counter - */ - private int numGroups; /** * Course code */ @@ -124,11 +120,11 @@ protected void requestService() throws Exception { if (result != null) { //Stores groups data returned by webservice response - List groupsSWAD = new ArrayList(); + List groupsSWAD = new ArrayList<>(); ArrayList res = new ArrayList((Vector) result); SoapObject soap = (SoapObject) res.get(1); - numGroups = soap.getPropertyCount(); + int numGroups = soap.getPropertyCount(); for (int i = 0; i < numGroups; i++) { SoapObject pii = (SoapObject) soap.getProperty(i); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java index c3a0f9739..10a8301aa 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java @@ -263,7 +263,7 @@ protected void onStop() { } private LongSparseArray> getHashMapGroups(ArrayList groupTypes) { - LongSparseArray> children = new LongSparseArray>(); + LongSparseArray> children = new LongSparseArray<>(); for (Model groupType : groupTypes) { long groupTypeCode = groupType.getId(); ArrayList groups = (ArrayList) dbHelper.getGroupsOfType(groupTypeCode); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java index 332b9d9b9..bcce4bb6c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java @@ -60,12 +60,6 @@ public class SendMyGroups extends Module { * String that contains group codes separated with comma */ private String myGroups = null; - /** - * Indicates if the enrollments are done or not - * 0 - if the enrollments are not done - * other than 0 - if they are correctly done - */ - private int success = 0; /** * Groups tag name for Logcat */ @@ -119,9 +113,14 @@ protected void requestService() throws Exception { ArrayList res = new ArrayList((Vector) result); SoapPrimitive soapP = (SoapPrimitive) res.get(0); - success = Integer.parseInt(soapP.toString()); + /* + Indicates if the enrollments are done or not + 0 - if the enrollments are not done + other than 0 - if they are correctly done + */ + int success = Integer.parseInt(soapP.toString()); if (success != 0) { - List groupsSWAD = new ArrayList(); + List groupsSWAD = new ArrayList<>(); SoapObject soapO = (SoapObject) res.get(2); int propertyCount = soapO.getPropertyCount(); From d4b74b5b1d728915f6a153912b4e8a9c474f752f Mon Sep 17 00:00:00 2001 From: Juan Miguel Boyero Corral Date: Fri, 1 Jul 2016 19:18:34 +0200 Subject: [PATCH 18/24] Fixed lint issues --- .../android/dataframework/DataFramework.java | 4 +- .../com/android/dataframework/Entity.java | 117 +++-- .../dataframework/EntityEditActivity.java | 2 +- .../dataframework/core/DataFrameworkCore.java | 6 +- .../com/android/dataframework/core/Table.java | 7 +- .../java/es/ugr/swad/swadroid/SWADMain.java | 137 +++--- .../swadroid/analytics/SWADroidTracker.java | 14 +- .../swadroid/database/DataBaseHelper.java | 403 ++++++++++-------- .../ugr/swad/swadroid/gui/DialogFactory.java | 2 +- .../gui/ImageExpandableListAdapter.java | 4 +- .../swad/swadroid/gui/ImageListAdapter.java | 4 +- .../ugr/swad/swadroid/gui/MenuActivity.java | 20 +- .../gui/MenuExpandableListActivity.java | 20 +- .../gui/SwipeListViewTouchListener.java | 6 +- .../swadroid/gui/widget/NumberPicker.java | 6 +- .../es/ugr/swad/swadroid/model/Event.java | 4 +- .../es/ugr/swad/swadroid/model/Group.java | 4 +- .../es/ugr/swad/swadroid/model/PairTable.java | 2 +- .../java/es/ugr/swad/swadroid/model/Test.java | 265 ++++++------ .../ugr/swad/swadroid/model/TestQuestion.java | 6 +- .../es/ugr/swad/swadroid/model/TestTag.java | 2 +- .../java/es/ugr/swad/swadroid/model/User.java | 2 +- .../es/ugr/swad/swadroid/modules/Module.java | 41 +- .../account/CreateAccountActivity.java | 4 +- .../swadroid/modules/courses/Courses.java | 6 +- .../modules/downloads/DirectoryNavigator.java | 18 +- .../modules/downloads/DownloadManager.java | 36 +- .../modules/downloads/DownloadsManager.java | 6 +- .../downloads/FileDownloaderAsyncTask.java | 15 +- .../swadroid/modules/downloads/GetFile.java | 5 +- .../swadroid/modules/groups/GroupTypes.java | 2 +- .../swad/swadroid/modules/groups/Groups.java | 2 +- .../modules/groups/MyGroupsManager.java | 6 +- .../swadroid/modules/groups/SendMyGroups.java | 2 +- .../modules/information/Information.java | 6 +- .../swad/swadroid/modules/login/Login.java | 2 +- .../swadroid/modules/login/LoginActivity.java | 6 +- .../swad/swadroid/modules/marks/Marks.java | 4 +- .../swadroid/modules/messages/Messages.java | 8 +- .../swadroid/modules/notices/Notices.java | 2 +- .../modules/notifications/Notifications.java | 42 +- .../NotificationsExpandableListAdapter.java | 10 +- .../NotificationsSyncAdapterService.java | 59 +-- .../swad/swadroid/modules/qr/GenerateQR.java | 4 +- .../rollcall/ContinuousCaptureActivity.java | 2 +- .../modules/rollcall/EventsCursorAdapter.java | 13 +- .../modules/rollcall/EventsDownload.java | 4 +- .../swadroid/modules/rollcall/Rollcall.java | 21 +- .../modules/rollcall/UsersActivity.java | 10 +- .../modules/rollcall/UsersCursorAdapter.java | 1 - .../modules/rollcall/UsersDownload.java | 2 +- .../swadroid/modules/rollcall/UsersSend.java | 2 +- .../tests/AnswerTypesArrayAdapter.java | 5 +- .../tests/CheckedAnswersArrayAdapter.java | 9 +- .../modules/tests/TagsArrayAdapter.java | 4 +- .../swad/swadroid/modules/tests/Tests.java | 13 +- .../modules/tests/TestsConfigDownload.java | 2 +- .../swadroid/modules/tests/TestsMake.java | 29 +- .../modules/tests/TestsQuestionsDownload.java | 2 +- .../swadroid/preferences/Preferences.java | 8 +- .../preferences/PreferencesActivity.java | 13 +- .../swadroid/ssl/EasySSLSocketFactory.java | 2 - .../swadroid/ssl/EasyX509TrustManager.java | 2 +- .../swad/swadroid/ssl/SecureConnection.java | 5 +- .../swadroid/sync/AccountAuthenticator.java | 2 +- .../swadroid/sync/PeriodicSyncReceiver.java | 4 +- .../es/ugr/swad/swadroid/sync/SyncUtils.java | 2 +- .../es/ugr/swad/swadroid/utils/Crypto.java | 2 +- .../swad/swadroid/utils/DateTimeUtils.java | 20 +- .../es/ugr/swad/swadroid/utils/Utils.java | 21 +- .../swad/swadroid/webservices/SOAPClient.java | 2 +- .../main/res/layout/dialog_filter_list.xml | 4 +- .../src/main/res/layout/users_listview.xml | 6 +- 73 files changed, 784 insertions(+), 751 deletions(-) diff --git a/SWADroid/src/main/java/com/android/dataframework/DataFramework.java b/SWADroid/src/main/java/com/android/dataframework/DataFramework.java index ad22f78d1..f15405237 100644 --- a/SWADroid/src/main/java/com/android/dataframework/DataFramework.java +++ b/SWADroid/src/main/java/com/android/dataframework/DataFramework.java @@ -47,7 +47,7 @@ public class DataFramework { private int mOpenInstances = 0; - private ArrayList mTables = new ArrayList
(); + private ArrayList
mTables = new ArrayList<>(); private DataFrameworkCore mCore; @@ -210,7 +210,7 @@ public ArrayList getEntityList(String table, String where, String orderb String[] fields = getTable(table).getFieldsToArray(); Cursor c = getCursor(table, fields, where, null, null, null, orderby, limit); - ArrayList aux = new ArrayList(); + ArrayList aux = new ArrayList<>(); c.moveToFirst(); while (!c.isAfterLast()) { diff --git a/SWADroid/src/main/java/com/android/dataframework/Entity.java b/SWADroid/src/main/java/com/android/dataframework/Entity.java index 3f7ff212b..2741075a7 100644 --- a/SWADroid/src/main/java/com/android/dataframework/Entity.java +++ b/SWADroid/src/main/java/com/android/dataframework/Entity.java @@ -46,7 +46,6 @@ import java.io.IOException; import java.io.StringReader; import java.util.HashMap; -import java.util.Iterator; import java.util.Map.Entry; public class Entity { @@ -54,8 +53,8 @@ public class Entity { private String mTable; private long mId = -1; private long mForceId = -1; - protected HashMap mAttributes = new HashMap(); - protected HashMap mMultilanguagesAttributes = new HashMap(); + protected HashMap mAttributes = new HashMap<>(); + protected HashMap mMultilanguagesAttributes = new HashMap<>(); /** * Devuelve el siguiente _id @@ -104,7 +103,7 @@ public String getTable() { * @return true si es una actualizacion */ public boolean isUpdate() { - return (mId < 0)?false:true; + return mId >= 0; } /** @@ -113,7 +112,7 @@ public boolean isUpdate() { * @return true si es una nuevo registro */ public boolean isInsert() { - return (mId < 0)?true:false; + return (mId < 0); } /** @@ -162,8 +161,7 @@ public String getString(String name) */ public int getDrawableIdentifier(String name) { - int id = DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null); - return id; + return DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null); } /** @@ -190,8 +188,7 @@ public BitmapDrawable getBitmapDrawable(String name) { int id = DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null); java.io.InputStream is = DataFramework.getInstance().getContext().getResources().openRawResource(id); - BitmapDrawable bmd = new BitmapDrawable(BitmapFactory.decodeStream(is)); - return bmd; + return new BitmapDrawable(BitmapFactory.decodeStream(is)); } /** @@ -276,19 +273,18 @@ public String toString() { String[] arString = DataFramework.getInstance().getTable(mTable).getToString().split("%"); String out = ""; - for (int i=0; i attribs = mAttributes; // Para reducir el acceso al heap. Object[] attributeNames = attribs.keySet().toArray(); int attributeCount = attributeNames.length; - - for (int i = 0; i < attributeCount; i++) - { - String attributeName = attributeNames[i].toString(); + + for (Object attributeName1 : attributeNames) { + String attributeName = attributeName1.toString(); Field f = getTableObject().getField(attributeName); - - int indexField; - if (f.getType().equals("multilanguage")) { - indexField = c.getColumnIndexOrThrow(attributeName + "_" + DataFramework.getInstance().getCurrentLanguage()); - } else { - indexField = c.getColumnIndexOrThrow(attributeName); - } - - if (f.getType().equals("text") || f.getType().equals("multilanguage") || f.getType().equals("string-identifier") || f.getType().equals("drawable-identifier")){ - attribs.put(attributeName, c.getString(indexField)); - }else if (f.getType().equals("int")){ - attribs.put(attributeName, c.getLong(indexField)); - }else if (f.getType().equals("foreign-key")){ - attribs.put(attributeName, c.getLong(indexField)); - }else if (f.getType().equals("real")){ - attribs.put(attributeName, c.getDouble(indexField)); - }else{ - attribs.put(attributeName, c.getString(indexField)); + + int indexField; + if (f.getType().equals("multilanguage")) { + indexField = c.getColumnIndexOrThrow(attributeName + "_" + DataFramework.getInstance().getCurrentLanguage()); + } else { + indexField = c.getColumnIndexOrThrow(attributeName); + } + + switch (f.getType()) { + case "text": + case "multilanguage": + case "string-identifier": + case "drawable-identifier": + attribs.put(attributeName, c.getString(indexField)); + break; + case "int": + attribs.put(attributeName, c.getLong(indexField)); + break; + case "foreign-key": + attribs.put(attributeName, c.getLong(indexField)); + break; + case "real": + attribs.put(attributeName, c.getDouble(indexField)); + break; + default: + attribs.put(attributeName, c.getString(indexField)); + break; } } } @@ -585,11 +589,9 @@ public boolean save() { } } } - - Iterator> it = mMultilanguagesAttributes.entrySet().iterator(); - while (it.hasNext()) { - Entry e = it.next(); - args.put(e.getKey().toString(), e.getValue().toString()); + + for (Entry e : mMultilanguagesAttributes.entrySet()) { + args.put(e.getKey(), e.getValue().toString()); } if (isInsert()) { @@ -636,15 +638,13 @@ private String getXml() String result = "\n"; result += "\n"; - - for (int i = 0; i < attributeCount; i++) - { - if (!isNull(attributeNames[i].toString())) - { - result += "\n"; - } - } + + for (Object attributeName : attributeNames) { + if (!isNull(attributeName.toString())) { + result += "\n"; + } + } result += "\n"; return result; @@ -682,14 +682,11 @@ public void loadFromXml(String xml) eventType = x.next(); } - } catch (XmlPullParserException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { + } catch (XmlPullParserException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } - } + } } diff --git a/SWADroid/src/main/java/com/android/dataframework/EntityEditActivity.java b/SWADroid/src/main/java/com/android/dataframework/EntityEditActivity.java index 1f4ad7141..ace8b9c9c 100644 --- a/SWADroid/src/main/java/com/android/dataframework/EntityEditActivity.java +++ b/SWADroid/src/main/java/com/android/dataframework/EntityEditActivity.java @@ -122,7 +122,7 @@ protected void onSaveInstanceState(Bundle outState) { protected Map getAttributeViews() { - Map views = new HashMap(); + Map views = new HashMap<>(); View mainView = findViewById(getMainViewId()); Table table = new Table(getTableName()); diff --git a/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java b/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java index 491edf601..7b030973b 100644 --- a/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java +++ b/SWADroid/src/main/java/com/android/dataframework/core/DataFrameworkCore.java @@ -59,7 +59,7 @@ public class DataFrameworkCore { private String mPackage = ""; - private ArrayList mLanguages = new ArrayList(); + private ArrayList mLanguages = new ArrayList<>(); private String mCurrentLanguage; private SQLiteDatabase mDb; @@ -322,13 +322,13 @@ public void backup(String file, boolean forceBackup) throws XmlPullParserExcepti int fieldCount = fields.size(); while (!c.isAfterLast()) { - osw.append("\n"); + osw.append("\n"); for (int j = 0; j < fieldCount; j++) { Field field = fields.get(j); if (c.getString(c.getColumnIndex(field.getName()))!=null) - osw.append("\n"); + osw.append("\n"); } osw.append("\n"); diff --git a/SWADroid/src/main/java/com/android/dataframework/core/Table.java b/SWADroid/src/main/java/com/android/dataframework/core/Table.java index fae81eee4..c6d985381 100644 --- a/SWADroid/src/main/java/com/android/dataframework/core/Table.java +++ b/SWADroid/src/main/java/com/android/dataframework/core/Table.java @@ -36,7 +36,7 @@ public class Table { private String mName; private String mToString; - private ArrayList mFields = new ArrayList(); + private ArrayList mFields = new ArrayList<>(); private int mNewInVersion; private boolean mBackup; @@ -128,8 +128,7 @@ public String getSQLAddField (Field field) { public String getSQLDeleteTable () { - String out = "DROP TABLE IF EXISTS " + mName; - return out; + return "DROP TABLE IF EXISTS " + mName; } /** @@ -154,7 +153,7 @@ public String[] getFieldsToArray() ArrayList fields = mFields; int fieldCount = fields.size(); - ArrayList aux = new ArrayList(); + ArrayList aux = new ArrayList<>(); aux.add(DataFramework.KEY_ID); for (int i = 0; i < fieldCount; i++) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java index e032b6932..1e2a6bb10 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/SWADMain.java @@ -29,6 +29,7 @@ import android.database.Cursor; import android.os.Build; import android.os.Bundle; +import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.Menu; @@ -60,15 +61,15 @@ import es.ugr.swad.swadroid.model.Course; import es.ugr.swad.swadroid.model.Model; import es.ugr.swad.swadroid.modules.courses.Courses; -import es.ugr.swad.swadroid.modules.qr.GenerateQR; -import es.ugr.swad.swadroid.modules.login.Login; -import es.ugr.swad.swadroid.modules.notices.Notices; import es.ugr.swad.swadroid.modules.downloads.DownloadsManager; import es.ugr.swad.swadroid.modules.groups.MyGroupsManager; import es.ugr.swad.swadroid.modules.information.Information; +import es.ugr.swad.swadroid.modules.login.Login; import es.ugr.swad.swadroid.modules.login.LoginActivity; import es.ugr.swad.swadroid.modules.messages.Messages; +import es.ugr.swad.swadroid.modules.notices.Notices; import es.ugr.swad.swadroid.modules.notifications.Notifications; +import es.ugr.swad.swadroid.modules.qr.GenerateQR; import es.ugr.swad.swadroid.modules.rollcall.Rollcall; import es.ugr.swad.swadroid.modules.tests.Tests; import es.ugr.swad.swadroid.preferences.Preferences; @@ -87,14 +88,6 @@ * @author Jose Antonio Guerrero Aviles */ public class SWADMain extends MenuExpandableListActivity { - /** - * Application preferences - */ - Preferences prefs; - /** - * SSL connection - */ - SecureConnection conn; /** * Array of strings for main ListView */ @@ -118,7 +111,7 @@ public class SWADMain extends MenuExpandableListActivity { /** * SWADMain tag name for Logcat */ - public static final String TAG = Constants.APP_TAG; + private static final String TAG = Constants.APP_TAG; /** * Indicates if it is the first run @@ -136,10 +129,10 @@ public class SWADMain extends MenuExpandableListActivity { private TextView mBirthdayTextView; private ExpandableListView mExpandableListView; private ImageExpandableListAdapter mExpandableListAdapter; - private final ArrayList> mHeaderData = new ArrayList>(); - private final ArrayList>> mChildData = new ArrayList>>(); - private final ArrayList> mMessagesData = new ArrayList>(); - private final ArrayList> mUsersData = new ArrayList>(); + private final ArrayList> mHeaderData = new ArrayList<>(); + private final ArrayList>> mChildData = new ArrayList<>(); + private final ArrayList> mMessagesData = new ArrayList<>(); + private final ArrayList> mUsersData = new ArrayList<>(); /** * Gets the database helper * @@ -152,7 +145,7 @@ public static DataBaseHelper getDbHelper() { /** * Shows initial dialog after application upgrade. */ - public void showUpgradeDialog(Context context) { + private void showUpgradeDialog(Context context) { AlertDialog alertDialog = DialogFactory.createWebViewDialog(context, R.string.changelogTitle, R.raw.changes); @@ -177,7 +170,10 @@ public void onCreate(Bundle icicle) { //Initialize preferences - prefs = new Preferences(this); + /* + Application preferences + */ + Preferences prefs = new Preferences(this); try { @@ -187,8 +183,11 @@ public void onCreate(Bundle icicle) { * If Android API < 11 (HONEYCOMB) add SSL certificates manually */ if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { - conn = new SecureConnection(); - conn.initSecureConnection(this); + /* + SSL connection + */ + SecureConnection conn = new SecureConnection(); + conn.initSecureConnection(); //conn.initUntrustedSecureConnection(); Log.i(TAG, "Android API < 11 (HONEYCOMB). Adding SSL certificates manually"); } else { @@ -226,7 +225,7 @@ public void onCreate(Bundle icicle) { } currentRole = -1; } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } @@ -295,7 +294,7 @@ private void firstRun(int currentVersion) { */ private void upgradeApp(int lastVersion, int currentVersion) throws NoSuchAlgorithmException { showUpgradeDialog(this); - dbHelper.upgradeDB(this); + dbHelper.upgradeDB(); if(lastVersion < 52) { //Encrypts users table @@ -391,7 +390,7 @@ private void createSpinnerAdapter() { */ private void cleanSpinner() { Spinner spinner = (Spinner) this.findViewById(R.id.spinner); - ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, new String[]{getString(R.string.clickToGetCourses)}); + ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{getString(R.string.clickToGetCourses)}); spinner.setAdapter(adapter); spinner.setOnTouchListener(Spinner_OnTouch); } @@ -497,30 +496,30 @@ private void createBaseMenu() { // 3- Messages // 4- Enrollment // 5- Users - final HashMap courses = new HashMap(); + final HashMap courses = new HashMap<>(); courses.put(NAME, getString(R.string.course)); - courses.put(IMAGE, getResources().getDrawable(R.drawable.crs)); + courses.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.crs)); mHeaderData.add(courses); - final HashMap evaluation = new HashMap(); + final HashMap evaluation = new HashMap<>(); evaluation.put(NAME, getString(R.string.evaluation)); - evaluation.put(IMAGE, getResources().getDrawable(R.drawable.ass)); + evaluation.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.ass)); mHeaderData.add(evaluation); - final HashMap users = new HashMap(); + final HashMap users = new HashMap<>(); users.put(NAME, getString(R.string.users)); - users.put(IMAGE, getResources().getDrawable(R.drawable.users)); + users.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.users)); mHeaderData.add(users); - final HashMap messages = new HashMap(); + final HashMap messages = new HashMap<>(); messages.put(NAME, getString(R.string.messages)); - messages.put(IMAGE, getResources().getDrawable(R.drawable.msg)); + messages.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.msg)); mHeaderData.add(messages); - final ArrayList> courseData = new ArrayList>(); + final ArrayList> courseData = new ArrayList<>(); mChildData.add(courseData); - final ArrayList> evaluationData = new ArrayList>(); + final ArrayList> evaluationData = new ArrayList<>(); mChildData.add(evaluationData); mChildData.add(mUsersData); @@ -530,90 +529,90 @@ private void createBaseMenu() { //Course category //Introduction - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.introductionModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.info)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.info)); courseData.add(map); //Teaching Guide - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.teachingguideModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.file)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.file)); courseData.add(map); //Syllabus (lectures) - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.syllabusLecturesModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.syllabus)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.syllabus)); courseData.add(map); //Syllabus (practicals) - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.syllabusPracticalsModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.lab)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.lab)); courseData.add(map); //Documents - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.documentsDownloadModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.folder)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.folder)); courseData.add(map); //Shared area - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.sharedsDownloadModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.folder_users)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.folder_users)); courseData.add(map); //Bibliography - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.bibliographyModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.book)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.book)); courseData.add(map); //FAQs - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.faqsModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.faq)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.faq)); courseData.add(map); //Links - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.linksModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.link)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.link)); courseData.add(map); //Evaluation category //Assessment system - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.assessmentModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.info)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.info)); evaluationData.add(map); //Test - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.testsModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.test)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.test)); evaluationData.add(map); //Marks - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.marksModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.grades)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.grades)); evaluationData.add(map); //Users category //Groups - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.myGroupsModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.my_groups)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.my_groups)); mUsersData.add(map); //Generate QR code - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.generateQRModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.qr)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.qr)); mUsersData.add(map); //Messages category //Notifications - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.notificationsModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.notif)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.notif)); mMessagesData.add(map); //Messages - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.messagesModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.msg_write)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.msg_write)); mMessagesData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter( @@ -651,15 +650,15 @@ private void changeToStudentMenu() { */ private void changeToTeacherMenu() { if (currentRole == Constants.STUDENT_TYPE_CODE) { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put(NAME, getString(R.string.noticesModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.note)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.note)); mMessagesData.add(map); - map = new HashMap(); + map = new HashMap<>(); map.put(NAME, getString(R.string.rollcallModuleLabel)); - map.put(IMAGE, getResources().getDrawable(R.drawable.roll_call)); + map.put(IMAGE, ContextCompat.getDrawable(this, R.drawable.roll_call)); mUsersData.add(map); mExpandableListAdapter = new ImageExpandableListAdapter(this, mHeaderData, diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java index 99f310074..5cf079e93 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/analytics/SWADroidTracker.java @@ -44,7 +44,7 @@ public class SWADroidTracker { /** * SWADroidTracker tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " SWADroidTracker"; + private static final String TAG = Constants.APP_TAG + " SWADroidTracker"; /** * Enum used to identify the tracker that needs to be used for tracking. * @@ -58,9 +58,9 @@ public enum TrackerName { ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company. } - private static HashMap mTrackers = new HashMap(); + private static HashMap mTrackers = new HashMap<>(); - private static boolean isTrackerEnabled(Context context) { + private static boolean isTrackerEnabled() { return (!Config.ANALYTICS_API_KEY.isEmpty()); } @@ -79,7 +79,7 @@ private static synchronized Tracker getTracker(Context context) { public static void initTracker(Context context) { // Initialize a tracker using a Google Analytics property ID. - if(isTrackerEnabled(context)) { + if(isTrackerEnabled()) { GoogleAnalytics.getInstance(context).newTracker(Config.ANALYTICS_API_KEY); ExceptionReporter exceptionHandler = @@ -108,7 +108,7 @@ public String getDescription(String threadName, Throwable t) { } public static void sendScreenView(Context context, String path) { - if(isTrackerEnabled(context)) { + if(isTrackerEnabled()) { // Get tracker. Tracker t = getTracker(context); @@ -124,7 +124,7 @@ public static void sendScreenView(Context context, String path) { } public static void sendScreenView(Context context, String path, String category, String action, String label) { - if(isTrackerEnabled(context)) { + if(isTrackerEnabled()) { // Get tracker. Tracker t = getTracker(context); @@ -151,7 +151,7 @@ public static void sendScreenView(Context context, String path, String category, } public static void sendException(Context context, Exception e, boolean fatal) { - if(isTrackerEnabled(context)) { + if(isTrackerEnabled()) { // Get tracker. Tracker t = getTracker(context); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java index 7e568e16d..7bf5342cd 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/database/DataBaseHelper.java @@ -89,7 +89,7 @@ public class DataBaseHelper { /** * Indicates if there are changes on db */ - public static boolean dbCleaned = false; + private static boolean dbCleaned = false; /** * Table name for courses */ @@ -242,29 +242,37 @@ private Pair selectParamsPairTable(String table) { String firstParam = null; String secondParam = null; - if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE)) { - firstParam = "qstCod"; - secondParam = "crsCod"; - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS)) { - firstParam = "qstCod"; - secondParam = "ansCod"; - } else if (table.equals(DataBaseHelper.DB_TABLE_USERS_COURSES)) { - firstParam = "userCode"; - secondParam = "crsCod"; - } else if (table.equals(DataBaseHelper.DB_TABLE_GROUPS_COURSES)) { - firstParam = "grpCod"; - secondParam = "crsCod"; - } else if (table.equals(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES)) { - firstParam = "grpTypCod"; - secondParam = "grpCod"; - } else if (table.equals(DataBaseHelper.DB_TABLE_EVENTS_COURSES)) { - firstParam = "eventCode"; - secondParam = "crsCod"; - } else { - Log.e("selectParamsPairTable", "Table " + table + " not exists"); - } - - return new Pair(firstParam, secondParam); + switch (table) { + case DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE: + firstParam = "qstCod"; + secondParam = "crsCod"; + break; + case DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS: + firstParam = "qstCod"; + secondParam = "ansCod"; + break; + case DataBaseHelper.DB_TABLE_USERS_COURSES: + firstParam = "userCode"; + secondParam = "crsCod"; + break; + case DataBaseHelper.DB_TABLE_GROUPS_COURSES: + firstParam = "grpCod"; + secondParam = "crsCod"; + break; + case DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES: + firstParam = "grpTypCod"; + secondParam = "grpCod"; + break; + case DataBaseHelper.DB_TABLE_EVENTS_COURSES: + firstParam = "eventCode"; + secondParam = "crsCod"; + break; + default: + Log.e("selectParamsPairTable", "Table " + table + " not exists"); + break; + } + + return new Pair<>(firstParam, secondParam); } /** @@ -291,144 +299,158 @@ private T createObjectByTable(String table, Entity ent) { Pair params; long id; - if (table.equals(DataBaseHelper.DB_TABLE_COURSES)) { - o = new Course(ent.getInt("id"), - ent.getInt("userRole"), - ent.getString("shortName"), - ent.getString("fullName")); - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE) || - table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS) || - table.equals(DataBaseHelper.DB_TABLE_USERS_COURSES) || - table.equals(DataBaseHelper.DB_TABLE_GROUPS_COURSES) || - table.equals(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES) || - table.equals(DataBaseHelper.DB_TABLE_EVENTS_COURSES)) { - - params = selectParamsPairTable(table); - - o = new PairTable(table, - ent.getInt(params.getFirst()), - ent.getInt(params.getSecond())); - } else if (table.equals(DataBaseHelper.DB_TABLE_NOTIFICATIONS)) { - o = new SWADNotification(ent.getInt("notifCode"), - ent.getInt("eventCode"), - crypto.decrypt(ent.getString("eventType")), - ent.getLong("eventTime"), - crypto.decrypt(ent.getString("userSurname1")), - crypto.decrypt(ent.getString("userSurname2")), - crypto.decrypt(ent.getString("userFirstname")), - crypto.decrypt(ent.getString("userPhoto")), - crypto.decrypt(ent.getString("location")), - crypto.decrypt(ent.getString("summary")), - ent.getInt("status"), - crypto.decrypt(ent.getString("content")), - Utils.parseStringBool(ent.getString("seenLocal")), - Utils.parseStringBool(ent.getString("seenRemote"))); - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTIONS)) { - id = ent.getInt("id"); - PairTable q = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod", Long.toString(id)); - - if (q != null) { - o = new TestQuestion(id, - (Integer) q.getFirst(), - ent.getString("stem"), - ent.getString("ansType"), - Utils.parseStringBool(ent.getString("shuffle")), - ent.getString("feedback")); - } else { - o = null; - } - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_ANSWERS)) { - id = ent.getId(); - int ansInd = ent.getInt("ansInd"); - PairTable a = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod", Long.toString(id)); - - if (a != null) { - o = new TestAnswer(id, - ansInd, - (Integer) a.getFirst(), - Utils.parseStringBool(ent.getString("correct")), - ent.getString("answer"), - ent.getString("answerFeedback")); - } else { - o = null; - } - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_TAGS)) { - id = ent.getInt("tagCod"); - TestTag t = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS, "tagCod", Long.toString(id)); - - if (t != null) { - o = new TestTag(id, - t.getQstCodList(), - ent.getString("tagTxt"), + switch (table) { + case DataBaseHelper.DB_TABLE_COURSES: + o = new Course(ent.getInt("id"), + ent.getInt("userRole"), + ent.getString("shortName"), + ent.getString("fullName")); + break; + case DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE: + case DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS: + case DataBaseHelper.DB_TABLE_USERS_COURSES: + case DataBaseHelper.DB_TABLE_GROUPS_COURSES: + case DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES: + case DataBaseHelper.DB_TABLE_EVENTS_COURSES: + + params = selectParamsPairTable(table); + + o = new PairTable<>(table, + ent.getInt(params.getFirst()), + ent.getInt(params.getSecond())); + break; + case DataBaseHelper.DB_TABLE_NOTIFICATIONS: + o = new SWADNotification(ent.getInt("notifCode"), + ent.getInt("eventCode"), + crypto.decrypt(ent.getString("eventType")), + ent.getLong("eventTime"), + crypto.decrypt(ent.getString("userSurname1")), + crypto.decrypt(ent.getString("userSurname2")), + crypto.decrypt(ent.getString("userFirstname")), + crypto.decrypt(ent.getString("userPhoto")), + crypto.decrypt(ent.getString("location")), + crypto.decrypt(ent.getString("summary")), + ent.getInt("status"), + crypto.decrypt(ent.getString("content")), + Utils.parseStringBool(ent.getString("seenLocal")), + Utils.parseStringBool(ent.getString("seenRemote"))); + break; + case DataBaseHelper.DB_TABLE_TEST_QUESTIONS: + id = ent.getInt("id"); + PairTable q = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTIONS_COURSE, "qstCod", Long.toString(id)); + + if (q != null) { + o = new TestQuestion(id, + (Integer) q.getFirst(), + ent.getString("stem"), + ent.getString("ansType"), + Utils.parseStringBool(ent.getString("shuffle")), + ent.getString("feedback")); + } else { + o = null; + } + break; + case DataBaseHelper.DB_TABLE_TEST_ANSWERS: + id = ent.getId(); + int ansInd = ent.getInt("ansInd"); + PairTable a = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_ANSWERS, "ansCod", Long.toString(id)); + + if (a != null) { + o = new TestAnswer(id, + ansInd, + (Integer) a.getFirst(), + Utils.parseStringBool(ent.getString("correct")), + ent.getString("answer"), + ent.getString("answerFeedback")); + } else { + o = null; + } + break; + case DataBaseHelper.DB_TABLE_TEST_TAGS: + id = ent.getInt("tagCod"); + TestTag t = getRow(DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS, "tagCod", Long.toString(id)); + + if (t != null) { + o = new TestTag(id, + t.getQstCodList(), + ent.getString("tagTxt"), + ent.getInt("tagInd")); + } else { + o = null; + } + break; + case DataBaseHelper.DB_TABLE_TEST_CONFIG: + o = new Test(ent.getInt("id"), + ent.getInt("min"), + ent.getInt("def"), + ent.getInt("max"), + ent.getString("feedback"), + ent.getLong("editTime")); + break; + case DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS: + ArrayList l = new ArrayList<>(); + l.add(ent.getInt("qstCod")); + o = new TestTag(ent.getInt("tagCod"), + l, + null, ent.getInt("tagInd")); - } else { - o = null; - } - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_CONFIG)) { - o = new Test(ent.getInt("id"), - ent.getInt("min"), - ent.getInt("def"), - ent.getInt("max"), - ent.getString("feedback"), - ent.getLong("editTime")); - } else if (table.equals(DataBaseHelper.DB_TABLE_TEST_QUESTION_TAGS)) { - ArrayList l = new ArrayList(); - l.add(ent.getInt("qstCod")); - o = new TestTag(ent.getInt("tagCod"), - l, - null, - ent.getInt("tagInd")); - } else if (table.equals(DataBaseHelper.DB_TABLE_USERS)) { - try { - o = new User(ent.getInt("userCode"), - null, // wsKey - ent.getString("userID"), - ent.getString("userNickname"), - ent.getString("userSurname1"), - ent.getString("userSurname2"), - ent.getString("userFirstname"), - ent.getString("photoPath"), - null, //userBirthday - ent.getInt("userRole")); - } catch (ParseException e) { - //Send exception details to Google Analytics - SWADroidTracker.sendException(mCtx, e, false); - } - } else if (table.equals(DataBaseHelper.DB_TABLE_USERS_ATTENDANCES)) { - o = new UserAttendance(ent.getInt("userCode"), - ent.getInt("eventCode"), - Utils.parseIntBool(ent.getInt("present"))); - } else if (table.equals(DataBaseHelper.DB_TABLE_EVENTS_ATTENDANCES)) { - o = new Event(ent.getLong("id"), - Utils.parseIntBool(ent.getInt("hidden")), - crypto.decrypt(ent.getString("userSurname1")), - crypto.decrypt(ent.getString("userSurname2")), - crypto.decrypt(ent.getString("userFirstName")), - crypto.decrypt(ent.getString("userPhoto")), - ent.getLong("startTime"), - ent.getLong("endTime"), - Utils.parseIntBool(ent.getInt("commentsTeachersVisible")), - crypto.decrypt(ent.getString("title")), - crypto.decrypt(ent.getString("text")), - crypto.decrypt(ent.getString("groups")), - crypto.decrypt(ent.getString("status"))); - } else if (table.equals(DataBaseHelper.DB_TABLE_GROUPS)) { - long groupTypeCode = getGroupTypeCodeFromGroup(ent.getLong("id")); - o = new Group(ent.getLong("id"), - ent.getString("groupName"), - groupTypeCode, - ent.getInt("maxStudents"), - ent.getInt("open"), - ent.getInt("students"), - ent.getInt("fileZones"), - ent.getInt("member")); - } else if (table.equals(DataBaseHelper.DB_TABLE_GROUP_TYPES)) { - o = new GroupType(ent.getLong("id"), - ent.getString("groupTypeName"), - ent.getLong("courseCode"), - ent.getInt("mandatory"), - ent.getInt("multiple"), - ent.getLong("openTime")); + break; + case DataBaseHelper.DB_TABLE_USERS: + try { + o = new User(ent.getInt("userCode"), + null, // wsKey + ent.getString("userID"), + ent.getString("userNickname"), + ent.getString("userSurname1"), + ent.getString("userSurname2"), + ent.getString("userFirstname"), + ent.getString("photoPath"), + null, //userBirthday + ent.getInt("userRole")); + } catch (ParseException e) { + //Send exception details to Google Analytics + SWADroidTracker.sendException(mCtx, e, false); + } + break; + case DataBaseHelper.DB_TABLE_USERS_ATTENDANCES: + o = new UserAttendance(ent.getInt("userCode"), + ent.getInt("eventCode"), + Utils.parseIntBool(ent.getInt("present"))); + break; + case DataBaseHelper.DB_TABLE_EVENTS_ATTENDANCES: + o = new Event(ent.getLong("id"), + Utils.parseIntBool(ent.getInt("hidden")), + crypto.decrypt(ent.getString("userSurname1")), + crypto.decrypt(ent.getString("userSurname2")), + crypto.decrypt(ent.getString("userFirstName")), + crypto.decrypt(ent.getString("userPhoto")), + ent.getLong("startTime"), + ent.getLong("endTime"), + Utils.parseIntBool(ent.getInt("commentsTeachersVisible")), + crypto.decrypt(ent.getString("title")), + crypto.decrypt(ent.getString("text")), + crypto.decrypt(ent.getString("groups")), + crypto.decrypt(ent.getString("status"))); + break; + case DataBaseHelper.DB_TABLE_GROUPS: + long groupTypeCode = getGroupTypeCodeFromGroup(ent.getLong("id")); + o = new Group(ent.getLong("id"), + ent.getString("groupName"), + groupTypeCode, + ent.getInt("maxStudents"), + ent.getInt("open"), + ent.getInt("students"), + ent.getInt("fileZones"), + ent.getInt("member")); + break; + case DataBaseHelper.DB_TABLE_GROUP_TYPES: + o = new GroupType(ent.getLong("id"), + ent.getString("groupTypeName"), + ent.getLong("courseCode"), + ent.getInt("mandatory"), + ent.getInt("multiple"), + ent.getLong("openTime")); + break; } return (T) o; @@ -441,7 +463,7 @@ private T createObjectByTable(String table, Entity ent) { * @return A list of Model's subclass objects */ public List getAllRows(String table) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(table); T row; @@ -463,7 +485,7 @@ public List getAllRows(String table) { * @return A list of Model's subclass objects */ public List getAllRows(String table, String where, String orderby) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(table, where, orderby); T row; @@ -576,7 +598,7 @@ public User getUser(String fieldName, Object fieldValue) { * @return A list of User's id */ public List getUsersCourse(long courseCode) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_USERS_COURSES, "crsCod = '" + courseCode + "'"); if (rows != null) { @@ -594,7 +616,7 @@ public List getUsersCourse(long courseCode) { * @return A list of User's id */ public List getUserIdsEvent(int eventCode) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_USERS_ATTENDANCES, "eventCode = '" + eventCode + "'"); if (rows != null) { @@ -612,7 +634,7 @@ public List getUserIdsEvent(int eventCode) { * @return A list of @link{UserAttendance} related to the selected event */ public List getUsersEvent(int eventCode) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_USERS_ATTENDANCES, "eventCode = '" + eventCode + "'"); if (rows != null) { @@ -657,7 +679,7 @@ public Cursor getUsersEventCursor(int eventCode) { * @return A list of Event */ public List getEventsCourse(long crsCod) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_EVENTS_COURSES, "crsCod = '" + crsCod + "'"); if (rows != null) { @@ -736,7 +758,7 @@ public Group getGroup(long groupId) { * @return A list of group codes belonging to the selected course */ public List getGroupCodesCourse(long courseCode) { - List result = new ArrayList(); + List result = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_COURSES, "crsCod = '" + courseCode + "'"); if (rows != null) { @@ -755,7 +777,7 @@ public List getGroupCodesCourse(long courseCode) { * @return List of Groups */ public List getGroupsOfType(long groupTypeCode) { - List groups = new ArrayList(); + List groups = new ArrayList<>(); List groupCodes = getGroupsCodesOfType(groupTypeCode); if (!groupCodes.isEmpty()) { for (Long groupCode : groupCodes) { @@ -807,7 +829,7 @@ long getGroupTypeCodeFromGroup(long groupCode) { * @return List of group codes */ private List getGroupsCodesOfType(long groupTypeCode) { - List groupCodes = new ArrayList(); + List groupCodes = new ArrayList<>(); List rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, "grpTypCod = '" + groupTypeCode + "'"); if (rows != null) { for (Entity row : rows) { @@ -825,7 +847,7 @@ private List getGroupsCodesOfType(long groupTypeCode) { */ public List getUserLoggedGroups(long courseCode) { List groupCodes = getGroupCodesCourse(courseCode); - List groups = new ArrayList(); + List groups = new ArrayList<>(); if (!groupCodes.isEmpty()) { for (Long groupCode : groupCodes) { Group g = getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCode)); @@ -891,16 +913,19 @@ public boolean isUserEnrolledCourse(String userID, long selectedCourseCode) { * @param courseCode Course code to be referenced * @return Cursor access to the groups */ - public List getGroups(long courseCode, String... filter) { + public List getGroups(long courseCode) { String select = "SELECT grpCod FROM " + DataBaseHelper.DB_TABLE_GROUPS_COURSES + " WHERE crsCod = " + courseCode + ";"; Cursor groupCodes = db.getDB().rawQuery(select, null); - List groups = new ArrayList(groupCodes.getCount()); + List groups = new ArrayList<>(groupCodes.getCount()); while (groupCodes.moveToNext()) { Group group = this.getRow(DataBaseHelper.DB_TABLE_GROUPS, "id", String.valueOf(groupCodes.getInt(0))); groups.add(group); } + + groupCodes.close(); + return groups; } @@ -1152,7 +1177,7 @@ public boolean insertGroup(Group g, long courseCode) { //it should not insert/modify rows in the relationship table if the course does not exists if (course != null) { if (rows.isEmpty()) { - PairTable pair = new PairTable(DataBaseHelper.DB_TABLE_GROUPS_COURSES, g.getId(), courseCode); + PairTable pair = new PairTable<>(DataBaseHelper.DB_TABLE_GROUPS_COURSES, g.getId(), courseCode); insertPairTable(pair); } else { rows.get(0).setValue("crsCod", courseCode); @@ -1169,9 +1194,9 @@ public boolean insertGroup(Group g, long courseCode) { //if(groupType != null){ rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, "grpCod=" + groupCode); if (rows.isEmpty()) { - insertPairTable(new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode, groupCode)); + insertPairTable(new PairTable<>(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode, groupCode)); } else { - PairTable prev = new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, rows.get(0).getValue("grpTypCod"), rows.get(0).getValue("grpCod")); + PairTable prev = new PairTable<>(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, rows.get(0).getValue("grpTypCod"), rows.get(0).getValue("grpCod")); PairTable current = new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode, groupCode); updatePairTable(prev, current); } @@ -1199,9 +1224,9 @@ public boolean insertGroupType(GroupType gt) { public boolean insertCollection(String table, List currentModels, long... courseCode) { boolean result = true; Collection modelsDB = getAllRows(table); - List newModels = new ArrayList(); - List obsoleteModel = new ArrayList(); - List modifiedModel = new ArrayList(); + List newModels = new ArrayList<>(); + List obsoleteModel = new ArrayList<>(); + List modifiedModel = new ArrayList<>(); beginTransaction(); @@ -1764,10 +1789,10 @@ public boolean updateGroup(long groupCode, long courseCode, Group currentGroup, if (groupType != null) { rows = db.getEntityList(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, "grpCod=" + groupCode); if (!rows.isEmpty()) { - insertPairTable(new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode[0], groupCode)); + insertPairTable(new PairTable<>(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode[0], groupCode)); } else { - PairTable prev = new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, rows.get(0).getValue("grpTypCod"), rows.get(0).getValue("grpCod")); + PairTable prev = new PairTable<>(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, rows.get(0).getValue("grpTypCod"), rows.get(0).getValue("grpCod")); PairTable current = new PairTable(DataBaseHelper.DB_TABLE_GROUPS_GROUPTYPES, groupTypeCode[0], groupCode); updatePairTable(prev, current); @@ -1925,7 +1950,7 @@ public List getOrderedCourseTags(long selectedCourseCode) { String orderBy = "T.tagTxt ASC"; String groupBy = "T.id"; Cursor dbCursor = db.getDB().query(tables, columns, where, null, groupBy, null, orderBy); - List result = new ArrayList(); + List result = new ArrayList<>(); List qstCodList; int idOld = -1; TestTag t = null; @@ -1934,7 +1959,7 @@ public List getOrderedCourseTags(long selectedCourseCode) { int id = dbCursor.getInt(0); if (id != idOld) { - qstCodList = new ArrayList(); + qstCodList = new ArrayList<>(); String tagTxt = dbCursor.getString(1); qstCodList.add(dbCursor.getInt(2)); @@ -1949,6 +1974,8 @@ public List getOrderedCourseTags(long selectedCourseCode) { } } + dbCursor.close(); + return result; } @@ -1969,7 +1996,7 @@ public List getRandomCourseQuestionsByTagAndAnswerType(long select String orderby = " ORDER BY RANDOM()"; String limit = " LIMIT " + maxQuestions; Cursor dbCursorQuestions, dbCursorAnswers; - List result = new ArrayList(); + List result = new ArrayList<>(); List answers; int tagsListSize = tagsList.size(); int answerTypesListSize = answerTypesList.size(); @@ -2022,7 +2049,7 @@ public List getRandomCourseQuestionsByTagAndAnswerType(long select where = " WHERE Q.qstCod=" + qstCod + " AND Q.ansCod=A._id"; dbCursorAnswers = db.getDB().rawQuery(select + tables + where + orderby, null); - answers = new ArrayList(); + answers = new ArrayList<>(); while (dbCursorAnswers.moveToNext()) { long ansCod = dbCursorAnswers.getLong(0); int ansInd = dbCursorAnswers.getInt(1); @@ -2035,8 +2062,12 @@ public List getRandomCourseQuestionsByTagAndAnswerType(long select q.setAnswers(answers); result.add(q); + + dbCursorAnswers.close(); } + dbCursorQuestions.close(); + return result; } @@ -2263,7 +2294,7 @@ public void initializeDB() { /** * Upgrades the database structure */ - public void upgradeDB(Context context) { + public void upgradeDB() { int dbVersion = db.getDB().getVersion(); /* * Modify database keeping data: diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/DialogFactory.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/DialogFactory.java index 57ac07aa5..ef45950e6 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/DialogFactory.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/DialogFactory.java @@ -80,7 +80,7 @@ public static AlertDialog createWebViewDialog(Context context, int titleId, int in_s.read(b); String content = new String(b, "UTF-8");*/ - String content = IOUtils.toString(in_s); + String content = IOUtils.toString(in_s, "UTF-8"); IOUtils.closeQuietly(in_s); WebView webview = (WebView) promptsView.findViewById(R.id.webview_dialog); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageExpandableListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageExpandableListAdapter.java index 099249cd8..f5ebff5f4 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageExpandableListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageExpandableListAdapter.java @@ -196,12 +196,12 @@ public boolean addChild(int groupPosition, int childPosition, HashMap group, ArrayList> childs) { if (groupPosition >= getGroupCount()) { groupData.add(groupPosition, group); - final ArrayList> groupData = new ArrayList>(); + final ArrayList> groupData = new ArrayList<>(); childData.add(groupPosition, groupData); childData.get(groupPosition).addAll(childs); } else { groupData.add(getGroupCount(), group); - final ArrayList> groupData = new ArrayList>(); + final ArrayList> groupData = new ArrayList<>(); childData.add(getGroupCount() - 1, groupData); childData.get(getGroupCount() - 1).addAll(childs); } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageListAdapter.java index c00f372b7..6b0b8977d 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/ImageListAdapter.java @@ -15,7 +15,7 @@ public class ImageListAdapter extends ArrayAdapter { - Context context; + private Context context; public ImageListAdapter(Context context, int resourceId, List items) { @@ -30,7 +30,7 @@ private class ViewHolder { } public View getView(int position, View convertView, ViewGroup parent) { - ViewHolder holder = null; + ViewHolder holder; ImageListItem imageListItem = getItem(position); LayoutInflater mInflater = (LayoutInflater) context diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java index 84229ba30..3dafd3740 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuActivity.java @@ -49,7 +49,7 @@ public class MenuActivity extends AppCompatActivity { /** * Application preferences */ - Preferences prefs; + private Preferences prefs; /** * Database Helper. */ @@ -73,7 +73,7 @@ public void onClick(DialogInterface dialog, int id) { /** * Listener for clean database dialog */ - OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { + private OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); @@ -88,7 +88,7 @@ public void onClick(DialogInterface dialog, int id) { /** * Shows Preferences screen */ - void viewPreferences() { + private void viewPreferences() { Intent settingsActivity = new Intent(this, PreferencesActivity.class); startActivity(settingsActivity); } @@ -96,7 +96,7 @@ void viewPreferences() { /** * Shares the application through the Android sharing options */ - void shareApplication() { + private void shareApplication() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "SWADroid"); @@ -108,7 +108,7 @@ void shareApplication() { /** * Rates the application in Android Market */ - void rateApplication() { + private void rateApplication() { Intent rateIntent = new Intent(Intent.ACTION_VIEW); rateIntent.setData(Uri.parse(getString(R.string.marketURL))); startActivity(rateIntent); @@ -118,7 +118,7 @@ void rateApplication() { /** * Deletes all data from database */ - void cleanDatabase() { + private void cleanDatabase() { AlertDialog cleanDBDialog = DialogFactory.createWarningDialog(this, -1, R.string.areYouSure, @@ -138,7 +138,7 @@ void cleanDatabase() { * * @param message Error message to show. */ - protected void error(String tag, String message, Exception ex, boolean sendException) { + protected void error(String message, Exception ex, boolean sendException) { DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); @@ -154,7 +154,7 @@ public void onClick(DialogInterface dialog, int id) { /** * Shows a dialog. */ - public void showDialog(int title, int message) { + protected void showDialog(int title, int message) { AlertDialog dialog = DialogFactory.createNeutralDialog(this, -1, title, message, R.string.close_dialog, null); dialog.show(); } @@ -208,7 +208,7 @@ protected void onCreate(Bundle savedInstanceState) { getPackageName(), 0); isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0); } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } @@ -232,7 +232,7 @@ protected void onResume() { try { dbHelper = new DataBaseHelper(this); } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java index 0bd428567..919614f7d 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/MenuExpandableListActivity.java @@ -50,7 +50,7 @@ public class MenuExpandableListActivity extends AppCompatActivity { /** * Application preferences */ - Preferences prefs; + private Preferences prefs; /** * Database Helper. */ @@ -58,7 +58,7 @@ public class MenuExpandableListActivity extends AppCompatActivity { /** * Application debuggable flag */ - protected static boolean isDebuggable; + private static boolean isDebuggable; /** * Class Module's tag name for Logcat */ @@ -78,7 +78,7 @@ public void onClick(DialogInterface dialog, int id) { /** * Listener for clean database dialog */ - OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { + private OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dbHelper.cleanTables(); Preferences.setLastCourseSelected(0); @@ -94,7 +94,7 @@ public void onClick(DialogInterface dialog, int id) { /** * Shows Preferences screen */ - protected void viewPreferences() { + private void viewPreferences() { Intent settingsActivity = new Intent(this, PreferencesActivity.class); startActivity(settingsActivity); } @@ -102,7 +102,7 @@ protected void viewPreferences() { /** * Shares the application through the Android sharing options */ - void shareApplication() { + private void shareApplication() { Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "SWADroid"); @@ -114,7 +114,7 @@ void shareApplication() { /** * Rates the application in Android Market */ - void rateApplication() { + private void rateApplication() { Intent rateIntent = new Intent(Intent.ACTION_VIEW); rateIntent.setData(Uri.parse(getString(R.string.marketURL))); startActivity(rateIntent); @@ -124,7 +124,7 @@ void rateApplication() { /** * Deletes all data from database */ - void cleanDatabase() { + private void cleanDatabase() { AlertDialog cleanDBDialog = DialogFactory.createWarningDialog(this, -1, @@ -145,7 +145,7 @@ void cleanDatabase() { * * @param message Error message to show. */ - protected void error(String tag, String message, Exception ex, boolean sendException) { + protected void error(String message, Exception ex, boolean sendException) { DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); @@ -223,7 +223,7 @@ protected void onCreate(Bundle savedInstanceState) { isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0); isSWADMain = this instanceof SWADMain; } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } @@ -247,7 +247,7 @@ protected void onResume() { try { dbHelper = new DataBaseHelper(this); } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/SwipeListViewTouchListener.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/SwipeListViewTouchListener.java index b5cc514e9..1dcee4783 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/SwipeListViewTouchListener.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/SwipeListViewTouchListener.java @@ -60,7 +60,7 @@ public class SwipeListViewTouchListener implements View.OnTouchListener { private boolean dismissRight = true; // Transient properties - private List < PendingSwipeData > mPendingSwipes = new ArrayList < PendingSwipeData > (); + private List < PendingSwipeData > mPendingSwipes = new ArrayList<>(); private int mDismissAnimationRefCount = 0; private float mDownX; private boolean mSwiping; @@ -107,7 +107,7 @@ public interface OnSwipeCallback { * @param callback The callback to trigger when the user has indicated that she would like to * dismiss one or more list items. */ - public SwipeListViewTouchListener(ListView listView, OnSwipeCallback callback) { + private SwipeListViewTouchListener(ListView listView, OnSwipeCallback callback) { ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); mSlop = vc.getScaledTouchSlop(); mMinFlingVelocity = vc.getScaledMinimumFlingVelocity(); @@ -139,7 +139,7 @@ public SwipeListViewTouchListener(ListView listView, OnSwipeCallback callback, b * * @param enabled Whether or not to watch for gestures. */ - public void setEnabled(boolean enabled) { + private void setEnabled(boolean enabled) { mPaused = !enabled; } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/widget/NumberPicker.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/widget/NumberPicker.java index eeb1eccd0..c109d0c96 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/widget/NumberPicker.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/gui/widget/NumberPicker.java @@ -224,7 +224,7 @@ private String formatNumber(int value) { : String.valueOf(value); } - void changeCurrent(int current) { + private void changeCurrent(int current) { // Wrap around the values if we go past the start or end if (current > mEnd) { @@ -239,13 +239,13 @@ void changeCurrent(int current) { updateView(); } - void notifyChange() { + private void notifyChange() { if (mListener != null) { mListener.onChanged(this, mPrevious, mCurrent); } } - void updateView() { + private void updateView() { /* If we don't have displayed values then use the * current number else find the correct value in the diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Event.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Event.java index 347a55244..455e240ca 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Event.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Event.java @@ -25,8 +25,8 @@ import org.ksoap2.serialization.PropertyInfo; import java.util.ArrayList; -import java.util.Arrays; import java.util.Calendar; +import java.util.Collections; import java.util.Hashtable; import java.util.List; @@ -220,7 +220,7 @@ public void setGroups(String groups) { } public List getGroupsList() { - return new ArrayList(Arrays.asList(groups)); + return new ArrayList(Collections.singletonList(groups)); } public void setGroupsList(List groups) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Group.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Group.java index 3fba01409..54371cb5b 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Group.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Group.java @@ -366,9 +366,7 @@ public boolean equals(Object obj) { return false; if (groupTypeCode != other.groupTypeCode) return false; - if (maxStudents != other.maxStudents) - return false; - return students == other.students && open == other.open && fileZones == other.fileZones && member == other.member; + return maxStudents == other.maxStudents && students == other.students && open == other.open && fileZones == other.fileZones && member == other.member; } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/PairTable.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/PairTable.java index 503e84181..c45f29ad7 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/PairTable.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/PairTable.java @@ -46,7 +46,7 @@ public class PairTable extends Model { */ public PairTable(String table, FIRST first, SECOND second) { super(0); - this.values = new Pair(first, second); + this.values = new Pair<>(first, second); this.table = table; } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Test.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Test.java index e9ab1f2f2..acedc542c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Test.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/Test.java @@ -127,7 +127,7 @@ public Test(long selectedCourseCode, int min, int def, int max, String feedback) this.max = max; this.feedback = feedback; this.totalScore = 0; - this.questionsScore = new ArrayList(); + this.questionsScore = new ArrayList<>(); } /** @@ -342,7 +342,7 @@ public void setEvaluated(boolean evaluated) { /** * Initializes questions's score and total score */ - void prepareEvaluation() { + private void prepareEvaluation() { evaluated = false; totalScore = 0; questionsScore.clear(); @@ -404,143 +404,150 @@ public void evaluate() { correctUserAnswers = 0; errors = 0; - if (answerType.equals("float")) { - a = la.get(0); - - userAnswerText = a.getUserAnswer(); - if (!userAnswerText.equals("")) { - userFloatAnswer = Float.valueOf(userAnswerText); - minFloatRange = Float.valueOf(a.getAnswer()); - maxFloatRange = Float.valueOf(la.get(1).getAnswer()); - a.setCorrectAnswered((userFloatAnswer >= minFloatRange) && (userFloatAnswer <= maxFloatRange)); - } - - if (a.isCorrectAnswered()) { - correctUserAnswers++; - } else { - errors++; - } - - if (userAnswerText.equals("")) { - score = (float) 0; - } else { - score = correctUserAnswers / (float) totalAnswers; - } - } else if (answerType.equals("TF")) { - a = la.get(0); - - userAnswerText = a.getUserAnswer(); - if (a.getCorrect()) { + switch (answerType) { + case "float": + a = la.get(0); + + userAnswerText = a.getUserAnswer(); + if (!userAnswerText.equals("")) { + userFloatAnswer = Float.valueOf(userAnswerText); + minFloatRange = Float.valueOf(a.getAnswer()); + maxFloatRange = Float.valueOf(la.get(1).getAnswer()); + a.setCorrectAnswered((userFloatAnswer >= minFloatRange) && (userFloatAnswer <= maxFloatRange)); + } + + if (a.isCorrectAnswered()) { + correctUserAnswers++; + } else { + errors++; + } + + if (userAnswerText.equals("")) { + score = (float) 0; + } else { + score = correctUserAnswers / (float) totalAnswers; + } + break; + case "TF": + a = la.get(0); + + userAnswerText = a.getUserAnswer(); + if (a.getCorrect()) { + a.setCorrectAnswered(a.getAnswer().equals(a.getUserAnswer())); + } else { + a.setCorrectAnswered(!a.getAnswer().equals(a.getUserAnswer())); + } + + if (a.isCorrectAnswered()) { + correctUserAnswers++; + } else { + errors++; + } + + if (userAnswerText.equals("")) { + score = (float) 0; + } else { + score = (float) (correctUserAnswers - errors); + } + break; + case "int": + a = la.get(0); + userAnswerText = a.getUserAnswer(); a.setCorrectAnswered(a.getAnswer().equals(a.getUserAnswer())); - } else { - a.setCorrectAnswered(!a.getAnswer().equals(a.getUserAnswer())); - } - - if (a.isCorrectAnswered()) { - correctUserAnswers++; - } else { - errors++; - } - - if (userAnswerText.equals("")) { - score = (float) 0; - } else { - score = (float) (correctUserAnswers - errors); - } - } else if (answerType.equals("int")) { - a = la.get(0); - userAnswerText = a.getUserAnswer(); - a.setCorrectAnswered(a.getAnswer().equals(a.getUserAnswer())); - - if (a.isCorrectAnswered()) { - correctUserAnswers++; - } else { - errors++; - } - - if (userAnswerText.equals("")) { - score = (float) 0; - } else { - score = correctUserAnswers / (float) totalAnswers; - } - } else if (answerType.equals("text")) { - a = la.get(0); - userAnswerText = prepareString(a.getUserAnswer()); - a.setCorrectAnswered(false); - - for (TestAnswer ans : la) { - answerText = prepareString(ans.getAnswer()); - - if (userAnswerText.equalsIgnoreCase(answerText)) { - a.setCorrectAnswered(true); - break; + + if (a.isCorrectAnswered()) { + correctUserAnswers++; + } else { + errors++; + } + + if (userAnswerText.equals("")) { + score = (float) 0; + } else { + score = correctUserAnswers / (float) totalAnswers; } - } - - if (a.isCorrectAnswered()) { - correctUserAnswers++; - } else { - errors++; - } - - if (userAnswerText.equals("")) { - score = (float) 0; - } else { - score = correctUserAnswers / (float) totalAnswers; - } - } else if (answerType.equals("uniqueChoice")) { - totalAnswers = la.size(); - a = la.get(0); - a.setCorrectAnswered(false); - - for (TestAnswer ans : la) { - if (ans.getCorrect() && ans.getAnswer().equals(a.getUserAnswer())) { - a.setCorrectAnswered(true); - break; + break; + case "text": + a = la.get(0); + userAnswerText = prepareString(a.getUserAnswer()); + a.setCorrectAnswered(false); + + for (TestAnswer ans : la) { + answerText = prepareString(ans.getAnswer()); + + if (userAnswerText.equalsIgnoreCase(answerText)) { + a.setCorrectAnswered(true); + break; + } } - } - - if (a.isCorrectAnswered()) { - correctUserAnswers++; - } else { - errors++; - } - - if (a.getUserAnswer().equals("")) { - score = (float) 0; - } else { - score = correctUserAnswers - (errors / ((float) totalAnswers - 1)); - } - } else { - noneSelected = true; - totalAnswers = la.size(); - for (TestAnswer ans : la) { - if (ans.getCorrect()) { - trueAnswers++; - if (ans.getUserAnswer().equals("Y")) { - correctUserAnswers++; - noneSelected = false; - }/* else { - errors++; - }*/ + + if (a.isCorrectAnswered()) { + correctUserAnswers++; + } else { + errors++; + } + + if (userAnswerText.equals("")) { + score = (float) 0; + } else { + score = correctUserAnswers / (float) totalAnswers; + } + break; + case "uniqueChoice": + totalAnswers = la.size(); + a = la.get(0); + a.setCorrectAnswered(false); + + for (TestAnswer ans : la) { + if (ans.getCorrect() && ans.getAnswer().equals(a.getUserAnswer())) { + a.setCorrectAnswered(true); + break; + } + } + + if (a.isCorrectAnswered()) { + correctUserAnswers++; } else { - falseAnswers++; - if (ans.getUserAnswer().equals("Y")) { + errors++; + } + + if (a.getUserAnswer().equals("")) { + score = (float) 0; + } else { + score = correctUserAnswers - (errors / ((float) totalAnswers - 1)); + } + break; + default: + noneSelected = true; + totalAnswers = la.size(); + for (TestAnswer ans : la) { + if (ans.getCorrect()) { + trueAnswers++; + if (ans.getUserAnswer().equals("Y")) { + correctUserAnswers++; + noneSelected = false; + }/* else { errors++; - noneSelected = false; + }*/ + } else { + falseAnswers++; + if (ans.getUserAnswer().equals("Y")) { + errors++; + noneSelected = false; + } } } - } - if (noneSelected) { - score = (float) 0; - } else { - if (falseAnswers == 0) { - score = correctUserAnswers / (float) totalAnswers; + if (noneSelected) { + score = (float) 0; } else { - score = (correctUserAnswers / (float) trueAnswers) - (errors / (float) falseAnswers); + if (falseAnswers == 0) { + score = correctUserAnswers / (float) totalAnswers; + } else { + score = (correctUserAnswers / (float) trueAnswers) - (errors / (float) falseAnswers); + } } - } + break; } questionsScore.set(i, score * CORRECT_ANSWER_SCORE); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestQuestion.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestQuestion.java index e76829bce..8f86ac280 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestQuestion.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestQuestion.java @@ -87,7 +87,7 @@ public TestQuestion(long id, String stem, String anstype, boolean shuffle, Strin this.stem = stem; this.answerType = anstype; this.shuffle = shuffle; - this.answers = new ArrayList(); + this.answers = new ArrayList<>(); this.feedback = feedback; } @@ -105,7 +105,7 @@ public TestQuestion(long id, long selectedCourseCode, String stem, String anstyp this.stem = stem; this.answerType = anstype; this.shuffle = shuffle; - this.answers = new ArrayList(); + this.answers = new ArrayList<>(); this.feedback = feedback; } @@ -223,7 +223,7 @@ public void setFeedback(String feedback) { * @return Correct test's answer */ public List getCorrectAnswers() { - List corrects = new ArrayList(); + List corrects = new ArrayList<>(); TestAnswer current; for (TestAnswer answer : this.answers) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestTag.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestTag.java index 745871413..42cefcd29 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestTag.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/TestTag.java @@ -221,7 +221,7 @@ public Integer getQstCod(int i) { */ public void addQstCod(Integer qstCod) { if (this.qstCodList == null) { - this.qstCodList = new ArrayList(); + this.qstCodList = new ArrayList<>(); } this.qstCodList.add(qstCod); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/User.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/User.java index f8cdc4e98..865978bee 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/model/User.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/model/User.java @@ -248,7 +248,7 @@ public Calendar getUserBirthday() { * * @param userBirthday User birthday. */ - public void setUserBirthday(String userBirthday) throws ParseException { + private void setUserBirthday(String userBirthday) throws ParseException { if((userBirthday != null) && !userBirthday.equals("00000000")) { this.userBirthday = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/Module.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/Module.java index f53a56537..61c34093a 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/Module.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/Module.java @@ -162,7 +162,7 @@ protected void onCreate(Bundle savedInstanceState) { // Recover the launched async task if the activity is re-created connect = (Connect) getLastNonConfigurationInstance(); if (connect != null) { - connect.activity = new WeakReference(this); + connect.activity = new WeakReference<>(this); } } @@ -327,7 +327,7 @@ public Connect(Module activity, boolean show, this.progressDescription = progressDescription; this.progressTitle = progressTitle; showDialog = show; - this.activity = new WeakReference(activity); + this.activity = new WeakReference<>(activity); this.e = null; progressDialog = new ProgressDialog(Module.this); } @@ -390,21 +390,26 @@ protected void onPostExecute(Void unused) { if (e.getClass() == SoapFault.class) { SoapFault es = (SoapFault) e; - if (es.faultstring.equals("Bad log in")) { - errorMsg = getString(R.string.errorBadLoginMsg); - sendException = false; - } else if (es.faultstring.equals("Bad web service key")) { - errorMsg = getString(R.string.errorBadLoginMsg); - sendException = false; - - // Force logout and reset password (this will show again - // the login screen) - Login.setLogged(false); - Preferences.setUserPassword(""); - } else if (es.faultstring.equals("Unknown application key")) { - errorMsg = getString(R.string.errorBadAppKeyMsg); - } else { - errorMsg = "Server error: " + es.getMessage(); + switch (es.faultstring) { + case "Bad log in": + errorMsg = getString(R.string.errorBadLoginMsg); + sendException = false; + break; + case "Bad web service key": + errorMsg = getString(R.string.errorBadLoginMsg); + sendException = false; + + // Force logout and reset password (this will show again + // the login screen) + Login.setLogged(false); + Preferences.setUserPassword(""); + break; + case "Unknown application key": + errorMsg = getString(R.string.errorBadAppKeyMsg); + break; + default: + errorMsg = "Server error: " + es.getMessage(); + break; } } else if ((e.getClass() == TimeoutException.class) || (e.getClass() == SocketTimeoutException.class)) { errorMsg = getString(R.string.errorTimeoutMsg); @@ -439,7 +444,7 @@ protected void onPostExecute(Void unused) { } // Request finalized with errors - error(TAG, errorMsg, e, sendException); + error(errorMsg, e, sendException); setResult(RESULT_CANCELED); // Launch database rollback diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java index 569a9f1e3..5dbde5abb 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/account/CreateAccountActivity.java @@ -59,7 +59,7 @@ */ public class CreateAccountActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { - public static final String TAG = Constants.APP_TAG + " CreateAccountActivity"; + private static final String TAG = Constants.APP_TAG + " CreateAccountActivity"; private static List serversList; @@ -205,7 +205,7 @@ public void onClick(View view) { /** * Creates a new account */ - public void createAccount() { + private void createAccount() { SWADroidTracker.sendScreenView(getApplicationContext(), "SWADroid CreateAccount"); Intent intent; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/courses/Courses.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/courses/Courses.java index ca4dde386..0d2064cd5 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/courses/Courses.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/courses/Courses.java @@ -135,9 +135,9 @@ protected void requestService() if (result != null) { //Stores courses data returned by webservice response List coursesDB = dbHelper.getAllRows(DataBaseHelper.DB_TABLE_COURSES); - List coursesSWAD = new ArrayList(); - List newCourses = new ArrayList(); - List obsoleteCourses = new ArrayList(); + List coursesSWAD = new ArrayList<>(); + List newCourses = new ArrayList<>(); + List obsoleteCourses = new ArrayList<>(); //List modifiedCourses = new ArrayList(); ArrayList res = new ArrayList((Vector) result); SoapObject soap = (SoapObject) res.get(1); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java index a08cb5c8a..85cd4a2c4 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DirectoryNavigator.java @@ -58,7 +58,7 @@ public class DirectoryNavigator { /** * Application context */ - public Context mContext; + private Context mContext; /** * Constructor. @@ -67,7 +67,7 @@ public class DirectoryNavigator { */ public DirectoryNavigator(Context ctx, String fileXML) { this.XMLinfo = fileXML; - this.path = new ArrayList(); + this.path = new ArrayList<>(); this.mContext = ctx; } @@ -84,7 +84,7 @@ public ArrayList goToSubDirectory(String subDirectory) throws Inv Node node = goToDirectory(); - currentItems = new ArrayList(getItems(node)); + currentItems = new ArrayList<>(getItems(node)); return currentItems; } @@ -109,7 +109,7 @@ public ArrayList goToSubDirectory(int directoryPosition) throws I Node node = goToDirectory(); - currentItems = new ArrayList(getItems(node)); + currentItems = new ArrayList<>(getItems(node)); return currentItems; } @@ -127,7 +127,7 @@ public ArrayList goToParentDirectory() throws InvalidPathExceptio path.remove(path.size() - 1); Node node = goToDirectory(); - currentItems = new ArrayList(getItems(node)); + currentItems = new ArrayList<>(getItems(node)); } return currentItems; @@ -144,7 +144,7 @@ public ArrayList refresh(String fileXML) throws InvalidPathExcept Node node = goToDirectory(); - currentItems = new ArrayList(getItems(node)); + currentItems = new ArrayList<>(getItems(node)); return currentItems; } @@ -159,7 +159,7 @@ public ArrayList goToRoot() throws InvalidPathException { Node node = goToDirectory(); - currentItems = new ArrayList(getItems(node)); + currentItems = new ArrayList<>(getItems(node)); return currentItems; } @@ -170,7 +170,7 @@ public ArrayList goToRoot() throws InvalidPathException { * @return Return a list of items of the directory passed as parameter. */ private List getItems(Node node) { - List items = new ArrayList(); + List items = new ArrayList<>(); NodeList childs = node.getChildNodes(); @@ -316,7 +316,7 @@ public void addToPath(String directory) { * @param name Name of the node located on the current directory. * @return null in case it does not exists any node with the given name */ - DirectoryItem getDirectoryItem(String name) { + private DirectoryItem getDirectoryItem(String name) { DirectoryItem node = null; boolean found = false; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadManager.java index 81ee084fc..f1ffa7020 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadManager.java @@ -308,9 +308,9 @@ public class DownloadManager { Downloads.Impl._DATA, }; - private static final Set LONG_COLUMNS = new HashSet( + private static final Set LONG_COLUMNS = new HashSet<>( Arrays.asList(COLUMN_ID, COLUMN_TOTAL_SIZE_BYTES, COLUMN_STATUS, COLUMN_REASON, - COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP)); + COLUMN_BYTES_DOWNLOADED_SO_FAR, COLUMN_LAST_MODIFIED_TIMESTAMP)); /** * This class contains all the information necessary to request a new download. The URI is the @@ -335,7 +335,7 @@ public static class Request { private Uri mUri; private Uri mDestinationUri; - private List> mRequestHeaders = new ArrayList>(); + private List> mRequestHeaders = new ArrayList<>(); private CharSequence mTitle; private CharSequence mDescription; private boolean mShowNotification = true; @@ -637,12 +637,15 @@ public Query orderBy(String column, int direction) { throw new IllegalArgumentException("Invalid direction: " + direction); } - if (column.equals(COLUMN_LAST_MODIFIED_TIMESTAMP)) { - mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; - } else if (column.equals(COLUMN_TOTAL_SIZE_BYTES)) { - mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES; - } else { - throw new IllegalArgumentException("Cannot order by " + column); + switch (column) { + case COLUMN_LAST_MODIFIED_TIMESTAMP: + mOrderByColumn = Downloads.COLUMN_LAST_MODIFICATION; + break; + case COLUMN_TOTAL_SIZE_BYTES: + mOrderByColumn = Downloads.COLUMN_TOTAL_BYTES; + break; + default: + throw new IllegalArgumentException("Cannot order by " + column); } mOrderDirection = direction; return this; @@ -654,8 +657,7 @@ public Query orderBy(String column, int direction) { * @return the Cursor returned by ContentResolver.query() */ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { - Uri uri = baseUri; - List selectionParts = new ArrayList(); + List selectionParts = new ArrayList<>(); String[] selectionArgs = null; if (mIds != null) { @@ -664,7 +666,7 @@ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { } if (mStatusFlags != null) { - List parts = new ArrayList(); + List parts = new ArrayList<>(); if ((mStatusFlags & STATUS_PENDING) != 0) { parts.add(statusClause("=", Downloads.STATUS_PENDING)); } @@ -698,7 +700,7 @@ Cursor runQuery(ContentResolver resolver, String[] projection, Uri baseUri) { String orderDirection = (mOrderDirection == ORDER_ASCENDING ? "ASC" : "DESC"); String orderBy = mOrderByColumn + " " + orderDirection; - return resolver.query(uri, projection, selection, selectionArgs, orderBy); + return resolver.query(baseUri, projection, selection, selectionArgs, orderBy); } private String joinStrings(String joiner, Iterable parts) { @@ -755,8 +757,7 @@ public void setAccessAllDownloads(boolean accessAllDownloads) { public long enqueue(Request request) { ContentValues values = request.toContentValues(mPackageName); Uri downloadUri = mResolver.insert(Downloads.CONTENT_URI, values); - long id = Long.parseLong(downloadUri.getLastPathSegment()); - return id; + return Long.parseLong(downloadUri.getLastPathSegment()); } /** @@ -826,8 +827,7 @@ public ParcelFileDescriptor openDownloadedFile(long id) throws FileNotFoundExcep * @hide */ public void restartDownload(long... ids) { - Cursor cursor = query(new Query().setFilterById(ids)); - try { + try (Cursor cursor = query(new Query().setFilterById(ids))) { for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { int status = cursor.getInt(cursor.getColumnIndex(COLUMN_STATUS)); if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) { @@ -835,8 +835,6 @@ public void restartDownload(long... ids) { + cursor.getLong(cursor.getColumnIndex(COLUMN_ID))); } } - } finally { - cursor.close(); } ContentValues values = new ContentValues(); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java index b9080b43d..bad56751e 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/DownloadsManager.java @@ -543,14 +543,14 @@ private void loadGroupsSpinner(List currentGroups) { Spinner groupsSpinner = (Spinner) this.findViewById(R.id.groupSpinner); groupsSpinner.setVisibility(View.VISIBLE); - ArrayList spinnerNames = new ArrayList(currentGroups.size() + 1); + ArrayList spinnerNames = new ArrayList<>(currentGroups.size() + 1); spinnerNames.add(getString(R.string.course) + "-" + Courses.getSelectedCourseShortName()); for (Group g : currentGroups) { GroupType gType = dbHelper.getGroupTypeFromGroup(g.getId()); spinnerNames.add(getString(R.string.group) + "-" + gType.getGroupTypeName() + " " + g.getGroupName()); } - ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerNames); + ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, spinnerNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); groupsSpinner.setAdapter(adapter); groupsSpinner.setOnItemSelectedListener(new onGroupSelectedListener()); @@ -664,7 +664,7 @@ private void downloadFile(String directory, String url, long fileSize) { // Check if external storage is available int storageState = checkMediaAvailability(); if (storageState == 2) { - new FileDownloaderAsyncTask(this, this.chosenNodeName, fileSize) + new FileDownloaderAsyncTask(this, this.chosenNodeName) .execute(directory, url); } else { Toast.makeText(this, R.string.sdCardBusyTitle, Toast.LENGTH_LONG).show(); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/FileDownloaderAsyncTask.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/FileDownloaderAsyncTask.java index 5ff0023b1..ed006c6de 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/FileDownloaderAsyncTask.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/FileDownloaderAsyncTask.java @@ -42,9 +42,7 @@ public class FileDownloaderAsyncTask extends AsyncTask { private final Context mContext; - private URL url; private String fileName = ""; - private boolean downloadSuccess = true; /** * Downloads tag name for Logcat @@ -52,7 +50,7 @@ public class FileDownloaderAsyncTask extends AsyncTask private static final String TAG = Constants.APP_TAG + " Downloads"; - public FileDownloaderAsyncTask(Context context, String fileName, long fileSize) { + public FileDownloaderAsyncTask(Context context, String fileName) { this.fileName = fileName; this.mContext = context; } @@ -63,8 +61,14 @@ public FileDownloaderAsyncTask(Context context, String fileName, long fileSize) * params[1] - url of file to download * */ protected Boolean doInBackground(String... params) { + URL url; + boolean downloadSuccess; try { url = new URL(params[1]); + + String titleNotification = mContext.getString(R.string.notificationDownloadTitle); //Initial text that appears in the status bar + String descriptionNotification = fileName; + downloadSuccess = DownloadFactory.downloadFile(mContext, url.toString(), fileName, titleNotification, descriptionNotification); } catch (MalformedURLException e) { Log.e(TAG, "Incorrect URL", e); @@ -72,13 +76,8 @@ protected Boolean doInBackground(String... params) { SWADroidTracker.sendException(mContext, e, false); downloadSuccess = false; - return false; } - String titleNotification = mContext.getString(R.string.notificationDownloadTitle); //Initial text that appears in the status bar - String descriptionNotification = fileName; - downloadSuccess = DownloadFactory.downloadFile(mContext, url.toString(), fileName, titleNotification, descriptionNotification); - return downloadSuccess; } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/GetFile.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/GetFile.java index 38085a054..b3d48c6e7 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/GetFile.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/downloads/GetFile.java @@ -39,8 +39,7 @@ * Module to get information of a file located in SWAD * @see getFile * - * @param fileCode It indicates the file which information is requested - * @return link temporal URL to download the file + * Return link temporal URL to download the file * * @author Helena Rodriguez Gijon */ @@ -81,7 +80,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java index 1a6075ae3..f15a54c12 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/GroupTypes.java @@ -66,7 +66,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java index fba63507f..1d937370c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/Groups.java @@ -86,7 +86,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java index 10a8301aa..e5b2b6172 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/MyGroupsManager.java @@ -58,7 +58,7 @@ public class MyGroupsManager extends MenuExpandableListActivity { /** * Tests tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " Groups Manager"; + private static final String TAG = Constants.APP_TAG + " Groups Manager"; /** * Course code of current selected course */ @@ -181,7 +181,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { /** * Shows informative dialog on successful enrollment */ - void showSuccessfulEnrollmentDialog() { + private void showSuccessfulEnrollmentDialog() { AlertDialog dialog = DialogFactory.createNeutralDialog(this, -1, R.string.resultEnrollment, @@ -195,7 +195,7 @@ void showSuccessfulEnrollmentDialog() { /** * Shows informative dialog on failed enrollment */ - void showFailedEnrollmentDialog() { + private void showFailedEnrollmentDialog() { AlertDialog dialog = DialogFactory.createNeutralDialog(this, -1, R.string.resultEnrollment, diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java index bcce4bb6c..057e6d310 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/groups/SendMyGroups.java @@ -87,7 +87,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/information/Information.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/information/Information.java index 98be8a26b..dfc71ad0f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/information/Information.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/information/Information.java @@ -28,7 +28,7 @@ */ public class Information extends Module { - public static final String TAG = Constants.APP_TAG + " Information"; + private static final String TAG = Constants.APP_TAG + " Information"; /** * Information Type. String with the type of information (none, HTML, plain @@ -49,7 +49,7 @@ public class Information extends Module { /** * Webview to show course's information */ - WebView webview; + private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { @@ -155,7 +155,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/Login.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/Login.java index c794dec36..d3cd7d1d3 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/Login.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/Login.java @@ -64,7 +64,7 @@ public class Login extends Module { /** * Login tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " Login"; + private static final String TAG = Constants.APP_TAG + " Login"; /* (non-Javadoc) * @see android.app.Activity#onCreate() diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java index 0b415da1f..e8678f638 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/login/LoginActivity.java @@ -64,7 +64,7 @@ */ public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { - public static final String TAG = Constants.APP_TAG + " LoginActivity"; + private static final String TAG = Constants.APP_TAG + " LoginActivity"; private static List serversList; @@ -226,7 +226,7 @@ public void onClick(View view) { * If there are form errors (invalid DNI, missing fields, etc.), the errors * are presented and no actual login attempt is made. */ - public void attemptLogin() { + private void attemptLogin() { SWADroidTracker.sendScreenView(getApplicationContext(), "SWADroid Login"); // Values for ID and password at the time of the login attempt. @@ -321,7 +321,7 @@ public void attemptLogin() { /** * Creates a new account */ - public void createAccount() { + private void createAccount() { startActivityForResult(new Intent(this, CreateAccountActivity.class), Constants.CREATE_ACCOUNT_REQUEST_CODE); } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/Marks.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/Marks.java index fcd677a84..4846220b6 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/Marks.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/marks/Marks.java @@ -25,12 +25,12 @@ */ public class Marks extends MenuActivity { - public static final String TAG = Constants.APP_TAG + " Marks"; + private static final String TAG = Constants.APP_TAG + " Marks"; /** * Webview to show marks */ - WebView webview; + private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/messages/Messages.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/messages/Messages.java index 884746c06..01a7e495c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/messages/Messages.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/messages/Messages.java @@ -77,15 +77,15 @@ public class Messages extends Module { /** * Receivers EditText */ - EditText rcvEditText; + private EditText rcvEditText; /** * Subject EditText */ - EditText subjEditText; + private EditText subjEditText; /** * Body EditText */ - EditText bodyEditText; + private EditText bodyEditText; /* (non-Javadoc) @@ -306,7 +306,7 @@ public boolean onOptionsItemSelected(MenuItem item) { } } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } return true; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notices/Notices.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notices/Notices.java index 58f8166ed..d828c996f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notices/Notices.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notices/Notices.java @@ -84,7 +84,7 @@ public void onClick(View view) { } } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } }; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/Notifications.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/Notifications.java index 1a14a8ce4..59413505f 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/Notifications.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/Notifications.java @@ -123,31 +123,31 @@ public class Notifications extends Module implements /** * ListView container for notifications */ - ExpandableListView list; + private ExpandableListView list; /** * Adapter container for notifications */ - NotificationsExpandableListAdapter adapter; + private NotificationsExpandableListAdapter adapter; /** * TextView for the empty notifications message */ - TextView emptyNotifTextView; + private TextView emptyNotifTextView; /** * List of groups for ExpandableListView */ - ArrayList groupItem; + private ArrayList groupItem; /** * List of childs for ExpandableListView */ - ArrayList> childItem; + private ArrayList> childItem; /** * Id for the not seen notifications group */ - int NOT_SEEN_GROUP_ID = 0; + private int NOT_SEEN_GROUP_ID = 0; /** * Id for the seen notifications group */ - int SEEN_GROUP_ID = 1; + private int SEEN_GROUP_ID = 1; /** * ListView click listener */ @@ -289,8 +289,8 @@ protected void onCreate(Bundle savedInstanceState) { mBirthdayLayout = (LinearLayout) findViewById(R.id.birthday_layout); mBirthdayTextView = (TextView) findViewById(R.id.birthdayTextView); - groupItem = new ArrayList(); - childItem = new ArrayList>(); + groupItem = new ArrayList<>(); + childItem = new ArrayList<>(); //Init ExpandableListView initSwipeOptions(); @@ -326,10 +326,8 @@ protected void onCreate(Bundle savedInstanceState) { /** * Launches an action when markAllRead button is pushed * - * @param v - * Actual view */ - public void onMarkAllReadClick(View v) { + public void onMarkAllReadClick() { dbHelper.updateAllNotifications("seenLocal", Utils.parseBoolString(true)); @@ -379,7 +377,7 @@ protected void onPause() { */ @Override protected void requestService() throws Exception { - int numDeletedNotif = 0; + int numDeletedNotif; if (SyncUtils.isSyncAutomatically(getApplicationContext())) { Log.i(TAG, @@ -543,14 +541,12 @@ protected void onError() { /** * Removes all notifications from database * - * @param context - * Database context */ - public void clearNotifications(Context context) { + public void clearNotifications() { try { dbHelper.emptyTable(DataBaseHelper.DB_TABLE_NOTIFICATIONS); } catch (Exception e) { - error(TAG, e.getMessage(), e, true); + error(e.getMessage(), e, true); } } @@ -577,7 +573,7 @@ public void onReceive(Context context, Intent intent) { notifCount = intent.getIntExtra("notifCount", 0); errorMessage = intent.getStringExtra("errorMessage"); if ((errorMessage != null) && !errorMessage.equals("")) { - error(TAG, errorMessage, null, true); + error(errorMessage, null, true); } else if (notifCount == 0) { Toast.makeText(context, R.string.NoNotificationsMsg, Toast.LENGTH_LONG).show(); @@ -727,21 +723,21 @@ private void setAppearance() { /** * It shows the SwipeRefreshLayout progress */ - public void showSwipeProgress() { + private void showSwipeProgress() { refreshLayout.setRefreshing(true); } /** * It shows the SwipeRefreshLayout progress */ - public void hideSwipeProgress() { + private void hideSwipeProgress() { refreshLayout.setRefreshing(false); } /** * Enables swipe gesture */ - public void enableSwipe() { + private void enableSwipe() { refreshLayout.setEnabled(true); //Log.d(TAG, "RefreshLayout Swipe ENABLED"); } @@ -768,12 +764,12 @@ public void onRefresh() { } } - public void setGroupData() { + private void setGroupData() { groupItem.add(getString(R.string.notSeenLabel)); groupItem.add(getString(R.string.seenLabel)); } - public void setChildGroupData() { + private void setChildGroupData() { List child; //Clear data diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsExpandableListAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsExpandableListAdapter.java index 838452264..2b3ffadd9 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsExpandableListAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsExpandableListAdapter.java @@ -19,7 +19,7 @@ package es.ugr.swad.swadroid.modules.notifications; import android.app.Activity; -import android.text.Html; +import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -97,9 +97,9 @@ public View getChildView(int groupPosition, final int childPosition, } if(!seenLocal) { - convertView.setBackgroundColor(activity.getResources().getColor(R.color.notifications_background_highlighted)); + convertView.setBackgroundColor(ContextCompat.getColor(activity, R.color.notifications_background_highlighted)); } else { - convertView.setBackgroundColor(activity.getResources().getColor(R.color.background)); + convertView.setBackgroundColor(ContextCompat.getColor(activity, R.color.background)); } convertView.setScrollContainer(false); @@ -205,7 +205,7 @@ public View getChildView(int groupPosition, final int childPosition, eventSender.setText(sender); } if (location != null) { - location.setText(Html.fromHtml(notif.getLocation())); + location.setText(Utils.fromHtml(notif.getLocation())); } if (summary != null) { summaryText = notif.getSummary(); @@ -214,7 +214,7 @@ public View getChildView(int groupPosition, final int childPosition, if (summaryText.equals(Constants.NULL_VALUE)) summaryText = activity.getString(R.string.noSubjectMsg); - summary.setText(Html.fromHtml(summaryText)); + summary.setText(Utils.fromHtml(summaryText)); } if ((content != null)) { contentText = notif.getContent(); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsSyncAdapterService.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsSyncAdapterService.java index f0a5f7530..4ad20d8e9 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsSyncAdapterService.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/notifications/NotificationsSyncAdapterService.java @@ -36,7 +36,6 @@ import android.util.Log; import org.ksoap2.SoapFault; -import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.SoapObject; import org.ksoap2.transport.HttpResponseException; import org.xmlpull.v1.XmlPullParserException; @@ -51,7 +50,6 @@ import javax.net.ssl.SSLException; import es.ugr.swad.swadroid.Constants; -import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.analytics.SWADroidTracker; import es.ugr.swad.swadroid.database.DataBaseHelper; @@ -60,6 +58,7 @@ import es.ugr.swad.swadroid.model.SWADNotification; import es.ugr.swad.swadroid.model.User; import es.ugr.swad.swadroid.modules.login.Login; +import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.ssl.SecureConnection; import es.ugr.swad.swadroid.utils.Utils; import es.ugr.swad.swadroid.webservices.IWebserviceClient; @@ -82,14 +81,14 @@ public class NotificationsSyncAdapterService extends Service { private static String METHOD_NAME = ""; private static Object result; private static String errorMessage = ""; + private static boolean isConnected; + private static boolean isDebuggable; public static final String START_SYNC = "es.ugr.swad.swadroid.sync.start"; public static final String STOP_SYNC = "es.ugr.swad.swadroid.sync.stop"; - public static boolean isConnected; - public static boolean isDebuggable; /** * Application context */ - public static Context mCtx; + private static Context mCtx; public NotificationsSyncAdapterService() { super(); @@ -110,7 +109,7 @@ public void onPerformSync(Account account, Bundle extras, String authority, Cont int httpStatusCode; try { - NotificationsSyncAdapterService.performSync(mContext, account, extras, authority, provider, syncResult); + NotificationsSyncAdapterService.performSync(mContext); //If synchronization was successful, update last synchronization time in preferences Preferences.setLastSyncTime(System.currentTimeMillis()); @@ -118,21 +117,26 @@ public void onPerformSync(Account account, Bundle extras, String authority, Cont if (e.getClass() == SoapFault.class) { SoapFault es = (SoapFault) e; - if (es.faultstring.equals("Bad log in")) { - errorMessage = mContext.getString(R.string.errorBadLoginMsg); - sendException = false; - } else if (es.faultstring.equals("Bad web service key")) { - errorMessage = mContext.getString(R.string.errorBadLoginMsg); - sendException = false; - - // Force logout and reset password (this will show again - // the login screen) - Login.setLogged(false); - Preferences.setUserPassword(""); - } else if (es.faultstring.equals("Unknown application key")) { - errorMessage = mContext.getString(R.string.errorBadAppKeyMsg); - } else { - errorMessage = "Server error: " + es.getMessage(); + switch (es.faultstring) { + case "Bad log in": + errorMessage = mContext.getString(R.string.errorBadLoginMsg); + sendException = false; + break; + case "Bad web service key": + errorMessage = mContext.getString(R.string.errorBadLoginMsg); + sendException = false; + + // Force logout and reset password (this will show again + // the login screen) + Login.setLogged(false); + Preferences.setUserPassword(""); + break; + case "Unknown application key": + errorMessage = mContext.getString(R.string.errorBadAppKeyMsg); + break; + default: + errorMessage = "Server error: " + es.getMessage(); + break; } } else if ((e.getClass() == TimeoutException.class) || (e.getClass() == SocketTimeoutException.class)) { errorMessage = mContext.getString(R.string.errorTimeoutMsg); @@ -252,7 +256,7 @@ private SyncAdapterImpl getSyncAdapter() { /** * Creates webservice request. */ - protected static void createRequest(String clientType) { + private static void createRequest(String clientType) { if(webserviceClient == null) { if(clientType.equals(SOAPClient.CLIENT_TYPE)) { webserviceClient = new SOAPClient(); @@ -270,7 +274,7 @@ protected static void createRequest(String clientType) { * @param param Parameter name. * @param value Parameter value. */ - protected static void addParam(String param, Object value) { + private static void addParam(String param, Object value) { webserviceClient.addParam(param, value); } @@ -282,7 +286,7 @@ protected static void addParam(String param, Object value) { * @param simple Flag for select simple or complex response * @throws Exception */ - protected static void sendRequest(Class cl, boolean simple) throws Exception { + private static void sendRequest(Class cl, boolean simple) throws Exception { ((SOAPClient) webserviceClient).sendRequest(cl, simple); result = webserviceClient.getResult(); } @@ -299,7 +303,6 @@ private static void logUser() throws Exception { sendRequest(User.class, true); if (result != null) { - KvmSerializable ks = (KvmSerializable) result; SoapObject soap = (SoapObject) result; //Stores user data returned by webservice response @@ -325,7 +328,7 @@ private static void logUser() throws Exception { } private static void getNotifications() throws Exception { - int numDeletedNotif = 0; + int numDeletedNotif; Log.d(TAG, "Logged"); @@ -425,7 +428,7 @@ private static void sendReadedNotifications(Context context) { } } - private static void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) + private static void performSync(Context context) throws Exception { Notification notif; @@ -453,7 +456,7 @@ private static void performSync(Context context, Account account, Bundle extras, */ if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { conn = new SecureConnection(); - conn.initSecureConnection(context); + conn.initSecureConnection(); Log.i(TAG, "Android API < 11 (HONEYCOMB). Adding Terena certificate manually"); } else { Log.i(TAG, "Android API >= 11 (HONEYCOMB). Using Terena built-in certificate"); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java index 258e14145..7a50eeabc 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/qr/GenerateQR.java @@ -109,7 +109,7 @@ private void generateQR() { String qrContents = "@" + Login.getLoggedUser().getUserNickname(); ImageView qr_image = (ImageView) findViewById(R.id.qr_code_image); Bitmap qrCode; - Map hintMap = new EnumMap(EncodeHintType.class); + Map hintMap = new EnumMap<>(EncodeHintType.class); hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8"); @@ -120,7 +120,7 @@ private void generateQR() { qrCode = barcodeEncoder.encodeBitmap(qrContents, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hintMap); qr_image.setImageBitmap(qrCode); } catch (WriterException e) { - error(TAG, e.getMessage(), e, true); + error(e.getMessage(), e, true); } } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java index 3e6876174..54898a346 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/ContinuousCaptureActivity.java @@ -133,7 +133,7 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { * * @param result The contents of the barcode. */ - public void handleDecode(BarcodeResult result) { + private void handleDecode(BarcodeResult result) { String messageResult; int iconResult; String qrContent = result.getText(); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsCursorAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsCursorAdapter.java index 613edb8c2..5314b99aa 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsCursorAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsCursorAdapter.java @@ -23,6 +23,7 @@ import android.content.Context; import android.database.Cursor; import android.graphics.Typeface; +import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -115,11 +116,11 @@ public void bindView(View view, final Context context, Cursor cursor) { //If the event is in time, show dates in green, else show in red if(today.before(startTimeCalendar) || today.after(endTimeCalendar)) { - holder.startTimeTextView.setTextColor(context.getResources().getColor(R.color.red)); - holder.endTimeTextView.setTextColor(context.getResources().getColor(R.color.red)); + holder.startTimeTextView.setTextColor(ContextCompat.getColor(context, R.color.red)); + holder.endTimeTextView.setTextColor(ContextCompat.getColor(context, R.color.red)); } else { - holder.startTimeTextView.setTextColor(context.getResources().getColor(R.color.green)); - holder.endTimeTextView.setTextColor(context.getResources().getColor(R.color.green)); + holder.startTimeTextView.setTextColor(ContextCompat.getColor(context, R.color.green)); + holder.endTimeTextView.setTextColor(ContextCompat.getColor(context, R.color.green)); } /* @@ -128,12 +129,12 @@ public void bindView(View view, final Context context, Cursor cursor) { */ if(pending) { holder.sendingStateTextView.setText(R.string.sendingStatePending); - holder.sendingStateTextView.setTextColor(context.getResources().getColor(R.color.red)); + holder.sendingStateTextView.setTextColor(ContextCompat.getColor(context, R.color.red)); holder.sendingStateTextView.setTypeface(null, Typeface.BOLD); } else { holder.sendingStateTextView.setText(R.string.ok); - holder.sendingStateTextView.setTextColor(context.getResources().getColor(R.color.green)); + holder.sendingStateTextView.setTextColor(ContextCompat.getColor(context, R.color.green)); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsDownload.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsDownload.java index 145389b7c..c41cffc44 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsDownload.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/EventsDownload.java @@ -80,7 +80,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } @@ -99,7 +99,7 @@ protected void requestService() throws Exception { ArrayList res = new ArrayList((Vector) result); SoapObject soap = (SoapObject) res.get(1); numEvents = soap.getPropertyCount(); - eventCodes = new ArrayList(); + eventCodes = new ArrayList<>(); for (int i = 0; i < numEvents; i++) { SoapObject pii = (SoapObject) soap.getProperty(i); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/Rollcall.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/Rollcall.java index eb0c39705..063ea3981 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/Rollcall.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/Rollcall.java @@ -55,7 +55,7 @@ public class Rollcall extends MenuExpandableListActivity implements /** * Rollcall tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " Rollcall"; + private static final String TAG = Constants.APP_TAG + " Rollcall"; /** * ListView of events */ @@ -65,14 +65,13 @@ public class Rollcall extends MenuExpandableListActivity implements */ private static EventsCursorAdapter adapter; private final RefreshAdapterHandler mHandler = new RefreshAdapterHandler(this); - /** - * Database cursor for Adapter of events - */ - Cursor dbCursor; private final Runnable mRunnable = new Runnable() { @Override public void run() { - dbCursor = dbHelper.getEventsCourseCursor(Courses.getSelectedCourseCode()); + /* + Database cursor for Adapter of events + */ + Cursor dbCursor = dbHelper.getEventsCourseCursor(Courses.getSelectedCourseCode()); startManagingCursor(dbCursor); @@ -103,7 +102,7 @@ public void run() { /** * TextView for the empty events message */ - TextView emptyEventsTextView; + private TextView emptyEventsTextView; /** * Layout with "Pull to refresh" function */ @@ -199,21 +198,21 @@ private void refreshEvents() { startActivityForResult(activity, Constants.ROLLCALL_EVENTS_DOWNLOAD_REQUEST_CODE); } - public void showProgress(boolean show) { + private void showProgress(boolean show) { DialogFactory.showProgress(this, show, R.id.swipe_container_list, R.id.loading_status); } /** * It shows the SwipeRefreshLayout progress */ - public void showSwipeProgress() { + private void showSwipeProgress() { refreshLayout.setRefreshing(true); } /** * It shows the SwipeRefreshLayout progress */ - public void hideSwipeProgress() { + private void hideSwipeProgress() { refreshLayout.setRefreshing(false); } @@ -289,7 +288,7 @@ private static class RefreshAdapterHandler extends Handler { private final WeakReference mActivity; public RefreshAdapterHandler(Rollcall activity) { - mActivity = new WeakReference(activity); + mActivity = new WeakReference<>(activity); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java index 4f2a50b69..74eb0db2c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersActivity.java @@ -66,7 +66,7 @@ public class UsersActivity extends MenuExpandableListActivity implements /** * Rollcall tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " UsersActivity"; + private static final String TAG = Constants.APP_TAG + " UsersActivity"; /** * Code of event associated to the users list */ @@ -211,21 +211,21 @@ private void refreshUsers() { startActivityForResult(activity, Constants.ROLLCALL_USERS_DOWNLOAD_REQUEST_CODE); } - public void showProgress(boolean show) { + private void showProgress(boolean show) { DialogFactory.showProgress(this, show, R.id.swipe_container_list, R.id.loading_status); } /** * It shows the SwipeRefreshLayout progress */ - public void showSwipeProgress() { + private void showSwipeProgress() { refreshLayout.setRefreshing(true); } /** * It shows the SwipeRefreshLayout progress */ - public void hideSwipeProgress() { + private void hideSwipeProgress() { refreshLayout.setRefreshing(false); } @@ -295,7 +295,7 @@ public boolean onOptionsItemSelected(MenuItem item) { } } else { //If the device has no rear camera available show error message - error(TAG, getString(R.string.noCameraFound), null, false); + error(getString(R.string.noCameraFound), null, false); } return true; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java index 416f18467..43d591ef7 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersCursorAdapter.java @@ -26,7 +26,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; -import android.widget.CompoundButton; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersDownload.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersDownload.java index 636446a1f..a86871ab5 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersDownload.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersDownload.java @@ -81,7 +81,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersSend.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersSend.java index 2aaa58e92..fdb17fb52 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersSend.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/rollcall/UsersSend.java @@ -91,7 +91,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/AnswerTypesArrayAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/AnswerTypesArrayAdapter.java index f3b1aff98..251b507d4 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/AnswerTypesArrayAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/AnswerTypesArrayAdapter.java @@ -19,13 +19,14 @@ package es.ugr.swad.swadroid.modules.tests; import android.content.Context; -import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckedTextView; +import es.ugr.swad.swadroid.utils.Utils; + public class AnswerTypesArrayAdapter extends ArrayAdapter { private final Context context; private final int textViewResourceId; @@ -52,7 +53,7 @@ public View getView(int position, View convertView, ViewGroup parent) { CheckedTextView tt = (CheckedTextView) convertView.findViewById(android.R.id.text1); if (tt != null) { - tt.setText(Html.fromHtml(itemsNames[position])); + tt.setText(Utils.fromHtml(itemsNames[position])); } return convertView; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/CheckedAnswersArrayAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/CheckedAnswersArrayAdapter.java index 4210e5827..6e1ce4f41 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/CheckedAnswersArrayAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/CheckedAnswersArrayAdapter.java @@ -20,7 +20,7 @@ import android.content.Context; import android.graphics.Color; -import android.text.Html; +import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; @@ -37,6 +37,7 @@ import es.ugr.swad.swadroid.gui.widget.CheckableLinearLayout; import es.ugr.swad.swadroid.model.Test; import es.ugr.swad.swadroid.model.TestAnswer; +import es.ugr.swad.swadroid.utils.Utils; public class CheckedAnswersArrayAdapter extends ArrayAdapter { private final Context context; @@ -84,7 +85,7 @@ public View getView(int position, View convertView, ViewGroup parent) { tt.setText(R.string.falseMsg); } } else { - tt.setText(Html.fromHtml(a.getAnswer())); + tt.setText(Utils.fromHtml(a.getAnswer())); } if (answerType.equals(TestAnswer.TYPE_UNIQUE_CHOICE) || answerType.equals(TestAnswer.TYPE_TRUE_FALSE)) { @@ -116,11 +117,11 @@ public void onClick(View v) { if (evaluated) { tt.setOnClickListener(null); answerFeedback = (TextView) convertView.findViewById(android.R.id.text2); - answerFeedback.setText(Html.fromHtml(a.getFeedback())); + answerFeedback.setText(Utils.fromHtml(a.getFeedback())); feedbackLevel = Test.FEEDBACK_VALUES.indexOf(feedback); if ((feedbackLevel > Test.FEEDBACK_VALUES.indexOf(Test.FEEDBACK_MEDIUM)) && a.getCorrect()) { - tt.setTextColor(context.getResources().getColor(R.color.green)); + tt.setTextColor(ContextCompat.getColor(context, R.color.green)); } else { tt.setTextColor(Color.BLACK); } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TagsArrayAdapter.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TagsArrayAdapter.java index 741429da7..bd5bf22ac 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TagsArrayAdapter.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TagsArrayAdapter.java @@ -19,7 +19,6 @@ package es.ugr.swad.swadroid.modules.tests; import android.content.Context; -import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -29,6 +28,7 @@ import java.util.List; import es.ugr.swad.swadroid.model.TestTag; +import es.ugr.swad.swadroid.utils.Utils; public class TagsArrayAdapter extends ArrayAdapter { private final Context context; @@ -59,7 +59,7 @@ public View getView(int position, View convertView, ViewGroup parent) { if (t != null) { CheckedTextView tt = (CheckedTextView) convertView.findViewById(android.R.id.text1); if (tt != null) { - tt.setText(Html.fromHtml(t.getTagTxt())); + tt.setText(Utils.fromHtml(t.getTagTxt())); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/Tests.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/Tests.java index ab4086bc8..7b1474d9a 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/Tests.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/Tests.java @@ -44,14 +44,10 @@ * @author Helena Rodríguez Gijon */ public class Tests extends MenuActivity implements OnItemClickListener { - /** - * Array adapter for showing menu options - */ - private ImageListAdapter adapter; /** * Tests tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " Tests"; + private static final String TAG = Constants.APP_TAG + " Tests"; public static final int RESULT_NO_QUESTIONS = 1; public static final int RESULT_NO_QUESTIONS_COURSE = 2; @@ -63,7 +59,7 @@ protected void onCreate(Bundle savedInstanceState) { ListView listView; String[] titles = getResources().getStringArray(R.array.testMenuItems); Integer[] images = {R.drawable.refresh, R.drawable.test}; - List imageListItems = new ArrayList(); + List imageListItems = new ArrayList<>(); super.onCreate(savedInstanceState); setContentView(R.layout.list_items); @@ -75,7 +71,10 @@ protected void onCreate(Bundle savedInstanceState) { imageListItems.add(item); } - adapter = new ImageListAdapter(this, R.layout.list_image_items, imageListItems); + /* + Array adapter for showing menu options + */ + ImageListAdapter adapter = new ImageListAdapter(this, R.layout.list_image_items, imageListItems); listView = (ListView) this.findViewById(R.id.listItems); listView.setAdapter(adapter); listView.setOnItemClickListener(this); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java index 4a7bcfe90..db45c2239 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsConfigDownload.java @@ -81,7 +81,7 @@ protected void onStart() { runConnection(); } catch (Exception e) { String errorMsg = getString(R.string.errorServerResponseMsg); - error(TAG, errorMsg, e, true); + error(errorMsg, e, true); } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsMake.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsMake.java index ecbb37a6c..c34d7a9bc 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsMake.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsMake.java @@ -23,6 +23,7 @@ import android.graphics.Color; import android.os.Build; import android.os.Bundle; +import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.text.InputType; import android.util.Log; @@ -90,10 +91,6 @@ public class TestsMake extends MenuActivity { * Click listener for courses dialog cancel button */ private OnItemClickListener tagsAnswersTypeItemClickListener; - /** - * Adapter for answer TF questions - */ - private ArrayAdapter tfAdapter; /** * Test question being showed */ @@ -102,6 +99,7 @@ public class TestsMake extends MenuActivity { * ActionBar menu */ private Menu menu; + /** * Possible values for screen steps */ @@ -182,7 +180,7 @@ private void setTags() { TagsArrayAdapter tagsAdapter = (TagsArrayAdapter) checkBoxesList.getAdapter(); int childsCount = checkBoxesList.getCount(); SparseBooleanArray checkedItems = checkBoxesList.getCheckedItemPositions(); - tagsList = new ArrayList(); + tagsList = new ArrayList<>(); //If "All tags" item checked, add the whole list to the list of selected tags if (checkedItems.get(0, false)) { @@ -244,7 +242,7 @@ private void setAnswerTypes() { AnswerTypesArrayAdapter answerTypesAdapter = (AnswerTypesArrayAdapter) checkBoxesList.getAdapter(); int childsCount = checkBoxesList.getCount(); SparseBooleanArray checkedItems = checkBoxesList.getCheckedItemPositions(); - answerTypesList = new ArrayList(); + answerTypesList = new ArrayList<>(); /* * If "All tags" item checked, add the whole list to the list of selected answer types, @@ -347,7 +345,7 @@ private void showQuestion(int pos) { String feedback = test.getFeedback(); String questionFeedbackText = question.getFeedback(); String correctAnswer = ""; - int feedbackColor = getResources().getColor(R.color.gray_goose); + int feedbackColor = ContextCompat.getColor(getApplicationContext(), R.color.gray_goose); int numAnswers = answers.size(); Float questionScore; DecimalFormat df = new DecimalFormat("0.00"); @@ -492,9 +490,9 @@ public boolean onTouch(View v, MotionEvent event) { questionScore = test.getQuestionScore(pos); if (questionScore > 0) { - score.setTextColor(getResources().getColor(R.color.green)); + score.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.green)); } else if (questionScore < 0) { - score.setTextColor(getResources().getColor(R.color.red)); + score.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red)); } else { score.setTextColor(Color.BLACK); } @@ -708,7 +706,7 @@ private void evaluateTest() { + df.format(scoreDec) + "/10"); if (scoreDec < 5) { - textView.setTextColor(getResources().getColor(R.color.red)); + textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red)); } textView.setVisibility(View.VISIBLE); @@ -727,18 +725,16 @@ private void evaluateTest() { /** * Launches an action when evaluate button is pushed * - * @param v Actual view */ - public void onEvaluateClick(View v) { + public void onEvaluateClick(View view) { evaluateTest(); } /** * Launches an action when show results details button is pushed * - * @param v Actual view */ - public void onShowResultsDetailsClick(View v) { + public void onShowResultsDetailsClick() { Button evalBt, resBt; showTest(); @@ -795,7 +791,10 @@ public void onItemClick(AdapterView parent, View v, int position, } }; - tfAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item); + /* + Adapter for answer TF questions + */ + ArrayAdapter tfAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item); tfAdapter.add(getString(R.string.trueMsg)); tfAdapter.add(getString(R.string.falseMsg)); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsQuestionsDownload.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsQuestionsDownload.java index 7b865152c..a07be0a88 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsQuestionsDownload.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/modules/tests/TestsQuestionsDownload.java @@ -102,7 +102,7 @@ protected void requestService() throws Exception { SoapObject questionsListObject = (SoapObject) res.get(1); SoapObject answersListObject = (SoapObject) res.get(2); SoapObject questionTagsListObject = (SoapObject) res.get(3); - List tagsList = new ArrayList(); + List tagsList = new ArrayList<>(); int listSizeTags = tagsListObject.getPropertyCount(); int listSizeQuestions = questionsListObject.getPropertyCount(); diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java index d1fd8a05c..40eb0d384 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/Preferences.java @@ -153,10 +153,6 @@ public class Preferences { * Indicates if there are changes on preferences */ private static boolean preferencesChanged = false; - /** - * Application context - */ - private static Context mContext; /** * Gets application preferences @@ -186,8 +182,6 @@ private static void getPreferences(Context ctx) { */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Preferences(Context ctx) { - mContext = ctx; - getPreferences(ctx); editor = prefs.edit(); @@ -197,7 +191,7 @@ public Preferences(Context ctx) { dbHelper = new DataBaseHelper(ctx); } catch (Exception e) { Log.e(TAG, e.getMessage()); - SWADroidTracker.sendException(mContext, e, false); + SWADroidTracker.sendException(ctx, e, false); } } } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/PreferencesActivity.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/PreferencesActivity.java index 803db73aa..fa2cd95c2 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/PreferencesActivity.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/preferences/PreferencesActivity.java @@ -45,7 +45,6 @@ import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.analytics.SWADroidTracker; import es.ugr.swad.swadroid.gui.DialogFactory; -import es.ugr.swad.swadroid.gui.widget.SeekBarDialogPreference; import es.ugr.swad.swadroid.modules.login.Login; import es.ugr.swad.swadroid.modules.login.LoginActivity; import es.ugr.swad.swadroid.sync.SyncUtils; @@ -61,11 +60,11 @@ public class PreferencesActivity extends PreferenceActivity implements OnPrefere /** * PreferencesActivity tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " PreferencesActivity"; + private static final String TAG = Constants.APP_TAG + " PreferencesActivity"; /** * Application context */ - public Context ctx; + private Context ctx; /** * Log out Preference */ @@ -121,7 +120,7 @@ public class PreferencesActivity extends PreferenceActivity implements OnPrefere /** * Application debuggable flag */ - protected static boolean isDebuggable; + private static boolean isDebuggable; /** * User password */ @@ -147,7 +146,7 @@ public class PreferencesActivity extends PreferenceActivity implements OnPrefere * * @param message Error message to show. */ - protected void error(String tag, String message, Exception ex, boolean sendException) { + private void error(String message, Exception ex, boolean sendException) { DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); @@ -179,7 +178,7 @@ protected void onCreate(Bundle savedInstanceState) { getPackageName(), 0); isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0); } catch (Exception ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } logOutPref = findPreference(Preferences.LOGOUTPREF); @@ -349,7 +348,7 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { } } catch (NoSuchAlgorithmException ex) { - error(TAG, ex.getMessage(), ex, true); + error(ex.getMessage(), ex, true); } } else if(Preferences.SYNCENABLEPREF.equals(key)) { boolean syncEnabled = (Boolean) newValue; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java index 6ccffeb14..ba012551c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasySSLSocketFactory.java @@ -18,7 +18,6 @@ */ package es.ugr.swad.swadroid.ssl; -import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; @@ -28,7 +27,6 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; -import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasyX509TrustManager.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasyX509TrustManager.java index 4ec8638c0..0ee9670d7 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasyX509TrustManager.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/EasyX509TrustManager.java @@ -70,7 +70,7 @@ public void checkServerTrusted(X509Certificate[] certificates, String authType) // Theoretically, we shouldn't have to do this, but various web servers // in practice are mis-configured to have out-of-order certificates or // expired self-issued root certificate. - int chainLength = certificates.length; + int chainLength; if (certificates.length > 1) { // 1. we clean the received certificates chain. diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/SecureConnection.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/SecureConnection.java index 6ad2b5bdc..8eec936bd 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/SecureConnection.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/ssl/SecureConnection.java @@ -18,7 +18,6 @@ */ package es.ugr.swad.swadroid.ssl; -import android.content.Context; import android.util.Log; import java.io.IOException; @@ -70,8 +69,6 @@ public static void initUntrustedSecureConnection() /** * Initialize certificate verification in application. * - * @param context - * Application context * @throws NoSuchAlgorithmException * @throws KeyManagementException * @throws IOException @@ -79,7 +76,7 @@ public static void initUntrustedSecureConnection() * @throws KeyStoreException * @throws UnrecoverableKeyException */ - public void initSecureConnection(Context context) + public void initSecureConnection() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/AccountAuthenticator.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/AccountAuthenticator.java index d120c5660..542e7e0bb 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/AccountAuthenticator.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/AccountAuthenticator.java @@ -15,7 +15,7 @@ public class AccountAuthenticator extends AccountAuthenticatorActivity { /** * Login tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " AccountAuthenticator"; + private static final String TAG = Constants.APP_TAG + " AccountAuthenticator"; @Override protected void onCreate(Bundle icicle) { diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/PeriodicSyncReceiver.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/PeriodicSyncReceiver.java index 1218b51c8..ab3fe949a 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/PeriodicSyncReceiver.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/PeriodicSyncReceiver.java @@ -34,7 +34,7 @@ */ public final class PeriodicSyncReceiver extends BroadcastReceiver { - private static Intent createIntent(Context context, String authority, Bundle extras) { + private static Intent createIntent(Context context, String authority) { Intent intent = new Intent(context, PeriodicSyncReceiver.class); intent.putExtra(Constants.AUTHORITY, authority); return intent; @@ -42,7 +42,7 @@ private static Intent createIntent(Context context, String authority, Bundle ext public static PendingIntent createPendingIntent(Context context, String authority, Bundle extras) { int requestCode = 0; - Intent intent = createIntent(context, authority, extras); + Intent intent = createIntent(context, authority); int flags = 0; return PendingIntent.getBroadcast(context, requestCode, intent, flags); } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/SyncUtils.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/SyncUtils.java index ecf9e8154..b78f692f8 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/SyncUtils.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/sync/SyncUtils.java @@ -39,7 +39,7 @@ public class SyncUtils { /** * Login tag name for Logcat */ - public static final String TAG = Constants.APP_TAG + " SyncUtils"; + private static final String TAG = Constants.APP_TAG + " SyncUtils"; public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) { long pollFrequencyMsec = frequency * 60000; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Crypto.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Crypto.java index 3db9296e3..a60fe8b56 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Crypto.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Crypto.java @@ -58,7 +58,7 @@ public class Crypto { /** * Application context */ - public Context mContext; + private Context mContext; public Crypto(Context ctx, String passPhrase) { mContext = ctx; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/DateTimeUtils.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/DateTimeUtils.java index 984551ed9..1c729651c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/DateTimeUtils.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/DateTimeUtils.java @@ -28,16 +28,16 @@ */ public class DateTimeUtils { - public final static long ONE_SECOND = 1000; - public final static long SECONDS = 60; + private final static long ONE_SECOND = 1000; + private final static long SECONDS = 60; - public final static long ONE_MINUTE = ONE_SECOND * 60; - public final static long MINUTES = 60; + private final static long ONE_MINUTE = ONE_SECOND * 60; + private final static long MINUTES = 60; - public final static long ONE_HOUR = ONE_MINUTE * 60; - public final static long HOURS = 24; + private final static long ONE_HOUR = ONE_MINUTE * 60; + private final static long HOURS = 24; - public final static long ONE_DAY = ONE_HOUR * 24; + private final static long ONE_DAY = ONE_HOUR * 24; private DateTimeUtils() { } @@ -47,8 +47,8 @@ private DateTimeUtils() { * " days, hours, minutes and (z) seconds" */ public static String millisToLongDHMS(long duration) { - StringBuffer res = new StringBuffer(); - long temp = 0; + StringBuilder res = new StringBuilder(); + long temp; if (duration >= ONE_SECOND) { temp = duration / ONE_DAY; if (temp > 0) { @@ -89,7 +89,7 @@ public static String millisToLongDHMS(long duration) { * "hh:mm:ss" */ public static String millisToShortDHMS(long duration) { - String res = ""; + String res; duration /= ONE_SECOND; int seconds = (int) (duration % SECONDS); duration /= SECONDS; diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Utils.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Utils.java index 3559ef938..f6ef68e5c 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Utils.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/utils/Utils.java @@ -23,6 +23,8 @@ import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; +import android.text.Html; +import android.text.Spanned; import android.util.TypedValue; import java.text.Normalizer; @@ -45,11 +47,11 @@ public class Utils { /** * Random generator */ - public static final Random rnd = new Random(); + private static final Random rnd = new Random(); /** * Base string to generate random alphanumeric strings */ - public static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /** * Generates a random string of length len @@ -76,9 +78,8 @@ public static boolean connectionAvailable(Context ctx) { //If boolean remains false there is no connection available NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); - boolean isConnected = activeNetwork != null && + return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); - return isConnected; } /** @@ -202,4 +203,16 @@ public static float getPixelsFromSp(float sp) { ); } + public static Spanned fromHtml(String text) { + Spanned result; + + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { + result = Html.fromHtml(text,Html.FROM_HTML_MODE_LEGACY); + } else { + result = Html.fromHtml(text); + } + + return result; + } + } diff --git a/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/SOAPClient.java b/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/SOAPClient.java index eb2f67156..66c9b29dd 100644 --- a/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/SOAPClient.java +++ b/SWADroid/src/main/java/es/ugr/swad/swadroid/webservices/SOAPClient.java @@ -68,7 +68,7 @@ public class SOAPClient implements IWebserviceClient { /** * Application debuggable flag */ - protected static boolean isDebuggable; + private static boolean isDebuggable; /** * Default constructor diff --git a/SWADroid/src/main/res/layout/dialog_filter_list.xml b/SWADroid/src/main/res/layout/dialog_filter_list.xml index 2870abdce..cae5bbdd0 100644 --- a/SWADroid/src/main/res/layout/dialog_filter_list.xml +++ b/SWADroid/src/main/res/layout/dialog_filter_list.xml @@ -10,7 +10,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" - android:layout_toRightOf="@+id/acceptFilters" + android:layout_alignParentLeft="true" + android:layout_marginLeft="90dp" android:text="@string/cancelFilters" />