diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/assets/ABC.pdf b/app/assets/ABC.pdf deleted file mode 100644 index e77ebca..0000000 Binary files a/app/assets/ABC.pdf and /dev/null differ diff --git a/app/assets/bgin.mp4 b/app/assets/bgin.mp4 deleted file mode 100644 index b5ac312..0000000 Binary files a/app/assets/bgin.mp4 and /dev/null differ diff --git a/app/assets/logo_spinning.gif b/app/assets/logo_spinning.gif deleted file mode 100644 index 6250d41..0000000 Binary files a/app/assets/logo_spinning.gif and /dev/null differ diff --git a/app/build.gradle b/app/build.gradle index 9922b1d..819a10c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,15 +1,15 @@ apply plugin: 'com.android.application' -android { - compileSdkVersion 23 - buildToolsVersion '25.0.0' +android { + compileSdkVersion 26 + buildToolsVersion "26.0.0" defaultConfig { - applicationId "pbell.offline.ole.org.pbell" - minSdkVersion 15 + applicationId "org.ole.learning.planet.planetlearning" + minSdkVersion 17 targetSdkVersion 26 - versionCode 1 - versionName "1.0" + versionCode 2 + versionName "2.0.5" multiDexEnabled true } buildTypes { @@ -18,44 +18,50 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } + packagingOptions { exclude 'META-INF/ASL2.0' exclude 'META-INF/LICENSE' exclude 'META-INF/NOTICE' } - /* lintOptions { + lintOptions { abortOnError false - }*/ + } + dexOptions { + javaMaxHeapSize "4g" + } - // useLibrary 'org.apache.http.legacy' -} + dependencies { + compile fileTree(include: ['*.jar'], dir: 'libs') + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { + exclude group: 'com.android.support', module: 'support-annotations' + }) + compile 'com.android.support:multidex:1.0.1' + compile 'com.android.support:support-v4:26.+' + compile 'com.android.support:design:26.+' + compile 'com.android.support:appcompat-v7:26.+' + compile 'com.android.support.constraint:constraint-layout:1.0.2' + compile 'com.github.kittinunf.fuel:fuel-android:1.3.1' + compile 'com.couchbase.lite:couchbase-lite-android:1.+' + compile 'org.lightcouch:lightcouch:+' + compile 'com.github.tonyofrancis:Fetch:+' + compile 'us.feras.mdv:markdownview:1.1.0' + compile 'com.makeramen:roundedimageview:2.3.0' -dependencies { - compile fileTree(include: ['*.jar'], dir: 'libs') - compile files('libs/PdfViewer.jar') - ///compile 'org.apache.httpcomponents:httpmime:4.2.6' - compile files('libs/PBKDF2-1.0.4.jar') - compile('org.apache.httpcomponents:httpmime:4.3.6') { - exclude module: 'httpclient' + compile 'com.github.florent37:diagonallayout:1.0.4' + compile 'org.webjars.npm:jsonparse:1.2.0' + compile 'org.apache.httpcomponents:httpclient-android:4.3.5' + compile 'com.roughike:bottom-bar:1.3.3' + compile 'com.mcxiaoke.volley:library-aar:1.0.0' + compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+' + compile 'us.feras.mdv:markdownview:1.1.0' + + compile 'com.android.support.constraint:constraint-layout:1.0.2' + + compile files('libs/PBKDF2-1.0.4.jar') + testCompile 'junit:junit:4.12' } - compile 'com.android.support:support-v4:23.4.0' - compile 'com.android.support:multidex:1.0.1' - compile 'com.android.support:appcompat-v7:23.4.0' - compile 'com.android.support:design:23.4.0' - compile 'com.android.support.constraint:constraint-layout:1.0.2' - compile 'com.google.android.support:wearable:2.0.0-alpha3' - compile 'com.google.android.gms:play-services-wearable:9.6.1' - ///compile 'com.github.tdscientist:ShelfView:v1.0' - compile 'com.github.florent37:diagonallayout:1.0.4' - compile 'com.github.kittinunf.fuel:fuel-android:1.3.1' - compile 'com.couchbase.lite:couchbase-lite-android:1.+' - compile 'org.lightcouch:lightcouch:0.1.8' - compile 'org.webjars.npm:jsonparse:1.2.0' - compile 'org.apache.httpcomponents:httpclient-android:4.3.5' - compile 'com.roughike:bottom-bar:1.3.3' - compile 'com.makeramen:roundedimageview:2.3.0' - compile 'com.mcxiaoke.volley:library-aar:1.0.0' - compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+' - compile 'us.feras.mdv:markdownview:1.1.0' - testCompile 'junit:junit:4.12' } + + + diff --git a/app/libs/PdfViewer.jar b/app/libs/PdfViewer.jar deleted file mode 100644 index a2404a5..0000000 Binary files a/app/libs/PdfViewer.jar and /dev/null differ diff --git a/app/libs/aspectjrt-1.7.3.jar b/app/libs/aspectjrt-1.7.3.jar deleted file mode 100644 index ef9fe4b..0000000 Binary files a/app/libs/aspectjrt-1.7.3.jar and /dev/null differ diff --git a/app/libs/isoparser-1.0-RC-27.jar b/app/libs/isoparser-1.0-RC-27.jar deleted file mode 100644 index 1eff8a3..0000000 Binary files a/app/libs/isoparser-1.0-RC-27.jar and /dev/null differ diff --git a/app/libs/sun.misc.BASE64Decoder.jar b/app/libs/sun.misc.BASE64Decoder.jar deleted file mode 100644 index 9811c13..0000000 Binary files a/app/libs/sun.misc.BASE64Decoder.jar and /dev/null differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index d0a202f..8f586cd 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -1,6 +1,6 @@ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified -# in /Users/leonardmensah/Library/android-sdk-macosx/tools/proguard/proguard-android.txt +# in /Users/leonardmensah/Library/Android/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # @@ -15,3 +15,11 @@ #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/androidTest/java/org/ole/learning/planet/planetlearning/ExampleInstrumentedTest.java b/app/src/androidTest/java/org/ole/learning/planet/planetlearning/ExampleInstrumentedTest.java new file mode 100644 index 0000000..e4e453e --- /dev/null +++ b/app/src/androidTest/java/org/ole/learning/planet/planetlearning/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package org.ole.learning.planet.planetlearning; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumentation test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("org.ole.learning.planet.planetlearning", appContext.getPackageName()); + } +} diff --git a/app/src/androidTest/java/pbell/offline/ole/org/pbell/ApplicationTest.java b/app/src/androidTest/java/pbell/offline/ole/org/pbell/ApplicationTest.java deleted file mode 100644 index 4933255..0000000 --- a/app/src/androidTest/java/pbell/offline/ole/org/pbell/ApplicationTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.app.Application; -import android.test.ApplicationTestCase; - -/** - * Testing Fundamentals - */ -@SuppressWarnings("ALL") -public class ApplicationTest extends ApplicationTestCase { - public ApplicationTest() { - super(Application.class); - } -} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c0e922c..342d890 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@ + package="org.ole.learning.planet.planetlearning"> @@ -18,8 +18,6 @@ - - - - - - - - - - - - - - - + android:theme="@style/SplashTheme"> + + + + - - + android:name=".FullscreenLogin" + android:configChanges="locale|orientation|keyboardHidden|screenSize" + android:label="@string/title_activity_fullscreen_login" + android:screenOrientation="reverseLandscape" + android:theme="@style/AppTheme"> - - - - - - - + android:screenOrientation="reverseLandscape" + android:theme="@style/FullscreenTheme"> + \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/AndroidDecrypter.java b/app/src/main/java/org/ole/learning/planet/planetlearning/AndroidDecrypter.java similarity index 98% rename from app/src/main/java/pbell/offline/ole/org/pbell/AndroidDecrypter.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/AndroidDecrypter.java index 6cc7657..6110880 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/AndroidDecrypter.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/AndroidDecrypter.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/CouchViews.java b/app/src/main/java/org/ole/learning/planet/planetlearning/CouchViews.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/CouchViews.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/CouchViews.java index 9faf07b..3e0c5ed 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/CouchViews.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/CouchViews.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import com.couchbase.lite.Database; import com.couchbase.lite.Emitter; diff --git a/app/src/main/java/org/ole/learning/planet/planetlearning/DownloadingItems.java b/app/src/main/java/org/ole/learning/planet/planetlearning/DownloadingItems.java new file mode 100644 index 0000000..de4c9e2 --- /dev/null +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/DownloadingItems.java @@ -0,0 +1,163 @@ +package org.ole.learning.planet.planetlearning; + +import android.annotation.SuppressLint; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.os.Handler; +import android.view.MotionEvent; +import android.view.View; + +/** + * An example full-screen activity that shows and hides the system UI (i.e. + * status bar and navigation/system bar) with user interaction. + */ +public class DownloadingItems extends AppCompatActivity { + /** + * Whether or not the system UI should be auto-hidden after + * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. + */ + private static final boolean AUTO_HIDE = true; + + /** + * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after + * user interaction before hiding the system UI. + */ + private static final int AUTO_HIDE_DELAY_MILLIS = 3000; + + /** + * Some older devices needs a small delay between UI widget updates + * and a change of the status and navigation bar. + */ + private static final int UI_ANIMATION_DELAY = 300; + private final Handler mHideHandler = new Handler(); + private View mContentView; + private final Runnable mHidePart2Runnable = new Runnable() { + @SuppressLint("InlinedApi") + @Override + public void run() { + // Delayed removal of status and navigation bar + + // Note that some of these constants are new as of API 16 (Jelly Bean) + // and API 19 (KitKat). It is safe to use them, as they are inlined + // at compile-time and do nothing on earlier devices. + mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE + | View.SYSTEM_UI_FLAG_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); + } + }; + private View mControlsView; + private final Runnable mShowPart2Runnable = new Runnable() { + @Override + public void run() { + // Delayed display of UI elements + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.show(); + } + mControlsView.setVisibility(View.VISIBLE); + } + }; + private boolean mVisible; + private final Runnable mHideRunnable = new Runnable() { + @Override + public void run() { + hide(); + } + }; + /** + * Touch listener to use for in-layout UI controls to delay hiding the + * system UI. This is to prevent the jarring behavior of controls going away + * while interacting with activity UI. + */ + private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + if (AUTO_HIDE) { + delayedHide(AUTO_HIDE_DELAY_MILLIS); + } + return false; + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_downloading_items); + + mVisible = true; + mControlsView = findViewById(R.id.fullscreen_content_controls); + mContentView = findViewById(R.id.fullscreen_content); + + + // Set up the user interaction to manually show or hide the system UI. + mContentView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + toggle(); + } + }); + + // Upon interacting with UI controls, delay any scheduled hide() + // operations to prevent the jarring behavior of controls going away + // while interacting with the UI. + findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); + } + + @Override + protected void onPostCreate(Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + + // Trigger the initial hide() shortly after the activity has been + // created, to briefly hint to the user that UI controls + // are available. + delayedHide(100); + } + + private void toggle() { + if (mVisible) { + hide(); + } else { + show(); + } + } + + private void hide() { + // Hide UI first + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.hide(); + } + mControlsView.setVisibility(View.GONE); + mVisible = false; + + // Schedule a runnable to remove the status and navigation bar after a delay + mHideHandler.removeCallbacks(mShowPart2Runnable); + mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); + } + + @SuppressLint("InlinedApi") + private void show() { + // Show the system bar + mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); + mVisible = true; + + // Schedule a runnable to display UI elements after a delay + mHideHandler.removeCallbacks(mHidePart2Runnable); + mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); + } + + /** + * Schedules a call to hide() in [delay] milliseconds, canceling any + * previously scheduled calls. + */ + private void delayedHide(int delayMillis) { + mHideHandler.removeCallbacks(mHideRunnable); + mHideHandler.postDelayed(mHideRunnable, delayMillis); + } +} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/FileCache.java b/app/src/main/java/org/ole/learning/planet/planetlearning/FileCache.java similarity index 95% rename from app/src/main/java/pbell/offline/ole/org/pbell/FileCache.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/FileCache.java index 92f88ec..a296cf8 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/FileCache.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/FileCache.java @@ -1,5 +1,4 @@ -package pbell.offline.ole.org.pbell; - +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. */ diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListView_Library.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Library.java similarity index 98% rename from app/src/main/java/pbell/offline/ole/org/pbell/ListView_Library.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Library.java index 1cc95cf..78e535f 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListView_Library.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Library.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.app.ProgressDialog; import android.content.Context; @@ -8,7 +8,7 @@ import android.support.v4.app.Fragment; import android.os.Bundle; /* -public class ListView_Library extends AppCompatActivity { +public class Fragm_Library extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { @@ -39,7 +39,7 @@ protected void onCreate(Bundle savedInstanceState) { import com.couchbase.lite.QueryRow; import com.couchbase.lite.android.AndroidContext; -public class ListView_Library extends Fragment { +public class Fragm_Library extends Fragment { // static final String URL = "http://api.androidhive.info/music/music.xml"; static final String KEY_MATERIALS = "materials"; // parent node static final String KEY_ID = "id"; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_Loading.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Loading.java similarity index 97% rename from app/src/main/java/pbell/offline/ole/org/pbell/Fragm_Loading.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Loading.java index 292ba8a..36acff8 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_Loading.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_Loading.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.content.Context; import android.net.Uri; @@ -96,7 +96,7 @@ public void run() { mListener.onFinishPageLoad(fg_myCourses, "myCourses"); }else if(requestedAction.equalsIgnoreCase("Library")) { - ListView_Library fg_Library = new ListView_Library(); + Fragm_Library fg_Library = new Fragm_Library(); mListener.onFinishPageLoad(fg_Library, "Library"); } } diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_TakeCourse.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_TakeCourse.java similarity index 98% rename from app/src/main/java/pbell/offline/ole/org/pbell/Fragm_TakeCourse.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_TakeCourse.java index 5e114e4..0d2667c 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_TakeCourse.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_TakeCourse.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.app.Dialog; import android.app.ProgressDialog; @@ -456,7 +456,12 @@ public void QuestionUILoader(String questionID, int numberOfQuestions) { public void onClick(View view) { try { if(CheckAnsBeforeNext(qn_Ids.get(quesionCurrentIndex),totalNumOfQuestions )){ - QuestionUILoader(qn_Ids.get(quesionCurrentIndex + 1), totalNumOfQuestions); + if ((quesionCurrentIndex+1) == totalNumOfQuestions) { + Log.d(TAG, "Last question "); + ///dialogTest.dismiss(); + }else { + QuestionUILoader(qn_Ids.get(quesionCurrentIndex + 1), totalNumOfQuestions); + } } } catch (Exception except) { diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myCourses.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myCourses.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myCourses.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myCourses.java index 10724bd..18678a3 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myCourses.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myCourses.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -331,7 +331,6 @@ public void LoadMyCourses() { } public int getIconType(String myresExt) { - int img = R.drawable.web; switch (myresExt) { case "Flow Video Player": @@ -369,7 +368,7 @@ public void createCourseDoc(String manualCourseId, int numberOfSteps) { try { document.putProperties(properties); } catch (CouchbaseLiteException e) { - Log.e(TAG, "Cannot course details in offline courses" + e.getMessage()); + Log.e(TAG, "Course details in offline courses" + e.getMessage()); } } catch (Exception e) { e.printStackTrace(); diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myLibrary.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myLibrary.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myLibrary.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myLibrary.java index 2d1d146..6738ec6 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Fragm_myLibrary.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Fragm_myLibrary.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.app.Activity; import android.app.ProgressDialog; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/FullscreenLogin.java b/app/src/main/java/org/ole/learning/planet/planetlearning/FullscreenLogin.java similarity index 97% rename from app/src/main/java/pbell/offline/ole/org/pbell/FullscreenLogin.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/FullscreenLogin.java index deac945..20a3502 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/FullscreenLogin.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/FullscreenLogin.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.annotation.SuppressLint; import android.app.Dialog; @@ -93,7 +93,6 @@ public class FullscreenLogin extends AppCompatActivity { String doc_lastVisit; private EditText mUsername; private EditText mPasswordView; - private LoginActivity.UserLoginTask mAuthTask = null; String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname, sys_usergender, sys_uservisits, sys_servername, sys_serverversion, sys_NewDate = ""; @@ -129,7 +128,6 @@ public class FullscreenLogin extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - ///setContentView(R.layout.activity_fullscreen_login_new); setContentView(R.layout.new_activity_login); mContentView = findViewById(R.id.fullscreen_content2); final ActionBar actionBar = getSupportActionBar(); @@ -143,18 +141,9 @@ protected void onCreate(Bundle savedInstanceState) { SignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - /*mDialog = new ProgressDialog(context); - mDialog.setMessage("Please wait. checking your credentials"); - mDialog.setCancelable(false); - mDialog.show();*/ - /* final Handler handler = new Handler(); - handler.postDelayed(new Runnable() { - @Override - public void run() {*/ if (getSystemInfo()) { if (authenticateUser()) { if (updateActivityLog()) { - /* mDialog.dismiss();*/ Intent intent = new Intent(context, User_Dashboard.class); //Intent intent = new Intent(context, FullscreenActivity.class); Log.e(TAG,"Opening Dashboard"); @@ -163,14 +152,11 @@ public void run() {*/ alertDialogOkay("System Error. Please contact system manager"); } } else { - /*mDialog.dismiss();*/ alertDialogOkay("Login incorrect / Not found. Check and try again."); } } else { alertDialogOkay("Device not linked to a cummunity/nation. Use the setting button to sync with community/nation."); } - /* } - }, 1000);*/ } }); // New UI @@ -183,7 +169,7 @@ public void onClick(View view) { sys_appInDemoMode = true; mUsername.setText("learner"); mPasswordView.setText("learner"); - DemoDataLoader demoDataLoader = new DemoDataLoader(context, SignInButton); + /// DemoDataLoader demoDataLoader = new DemoDataLoader(context, SignInButton); //alertDialogOkay("Device configured for Demo. Click Sign-in"); @@ -197,7 +183,7 @@ public void onClick(View view) { public void onClick(View view) { //alertDialogOkay("This feature has not been activated on this version."); setLocale("fr"); - //Intent intent = new Intent(context, ListView_Library.class); + //Intent intent = new Intent(context, Fragm_Library.class); //Intent intent = new Intent(context, User_Dashboard.class); //startActivity(intent); } @@ -216,7 +202,7 @@ public void onClick(View view) { // restorePref(); - startServiceCommand(); + ////startServiceCommand(); btnFeedback = (Button) findViewById(R.id.btnFeedback); btnFeedback.setOnClickListener(new View.OnClickListener() { @Override @@ -858,35 +844,6 @@ public void onClick(DialogInterface int_dialog, int which) { } } - public void setDateDialog() { - @SuppressLint("WifiManagerLeak") final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); - AlertDialog.Builder dialogB = new AlertDialog.Builder(this); - dialogB.setView(R.layout.dialog_date); - dialogB.setCancelable(true); - dialog = dialogB.create(); - dialog.show(); - Button saveDate = (Button) dialog.findViewById(R.id.btnSaveDate); - final DatePicker dp = (DatePicker) dialog.findViewById(R.id.datePicker); - String day = String.valueOf(dp.getDayOfMonth()) + "-" + String.valueOf(dp.getMonth() + 1) + "-" + String.valueOf(dp.getYear()); - Log.e("MyCouch", " date " + day); - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - try { - Date date = sdf.parse(day); - } catch (ParseException e) { - e.printStackTrace(); - } - saveDate.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Calendar cal = Calendar.getInstance(); - cal.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth()); - Intent intent = new Intent(context, FullscreenActivity.class); - startActivity(intent); - dialog.dismiss(); - } - }); - } - public void restorePref() { // Restore preferences settings = getSharedPreferences(PREFS_NAME, 0); @@ -920,13 +877,14 @@ public void restorePref() { Log.e("MYAPP", " Error creating sys_membersWithResource"); } try { - serviceIntent = new Intent(context, ServerSearchService.class); - context.stopService(serviceIntent); + // serviceIntent = new Intent(context, ServerSearchService.class); +// context.stopService(serviceIntent); } catch (Exception error) { Log.e("MYAPP", " Creating Service error " + error.getMessage()); } } + /* public void startServiceCommand() { try { serviceIntent = new Intent(context, ServerSearchService.class); @@ -936,6 +894,7 @@ public void startServiceCommand() { Log.e("MYAPP", " Creating Service error " + err.getMessage()); } } + */ public void syncNotifier() { emptyAllDbs(); diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ImageLoader.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ImageLoader.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/ImageLoader.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ImageLoader.java index ee4b383..123815b 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ImageLoader.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ImageLoader.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Courses.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Courses.java similarity index 84% rename from app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Courses.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Courses.java index cae4353..5705a3d 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Courses.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Courses.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. @@ -74,10 +74,10 @@ public View getView(int position, View convertView, ViewGroup parent) { material = data.get(position); // Setting all values in listview - title.setText(material.get(ListView_Library.KEY_TITLE)); - description.setText(material.get(ListView_Library.KEY_DESCRIPTION)); + title.setText(material.get(Fragm_Library.KEY_TITLE)); + description.setText(material.get(Fragm_Library.KEY_DESCRIPTION)); details.setText("Details"); - details.setTag(material.get(ListView_Library.KEY_DETAILS)); + details.setTag(material.get(Fragm_Library.KEY_DETAILS)); details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -85,7 +85,7 @@ public void onClick(View v) { } }); feedback.setText("Feedback"); - feedback.setTag(material.get(ListView_Library.KEY_FEEDBACK)); + feedback.setTag(material.get(Fragm_Library.KEY_FEEDBACK)); feedback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -94,21 +94,21 @@ public void onClick(View v) { }); addToMyLibrary.setText("Add to myLibrary"); - addToMyLibrary.setTag(material.get(ListView_Library.KEY_DELETE)); + addToMyLibrary.setTag(material.get(Fragm_Library.KEY_DELETE)); addToMyLibrary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "addToMyLibrary Clicked ********** "+v.getTag()); } }); - ratingAvgNum.setText(""+material.get(ListView_Library.KEY_RATING)); - ratingStars.setRating(Float.parseFloat(""+material.get(ListView_Library.KEY_RATING))); - totalNum.setText(material.get(ListView_Library.KEY_TOTALNUM_RATING)); + ratingAvgNum.setText(""+material.get(Fragm_Library.KEY_RATING)); + ratingStars.setRating(Float.parseFloat(""+material.get(Fragm_Library.KEY_RATING))); + totalNum.setText(material.get(Fragm_Library.KEY_TOTALNUM_RATING)); femalerating.setProgress(Integer.parseInt("1")); //femalerating.setProgress(Integer.parseInt(material.get(ListView_Library.KEY_FEMALE_RATING))); malerating.setProgress(Integer.parseInt("1")); //malerating.setProgress(Integer.parseInt(material.get(ListView_Library.KEY_MALE_RATING))); - imageLoader.DisplayImage(material.get(ListView_Library.KEY_THUMB_URL), thumb_image); + imageLoader.DisplayImage(material.get(Fragm_Library.KEY_THUMB_URL), thumb_image); return vi; } } \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Library.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Library.java similarity index 84% rename from app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Library.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Library.java index ece241f..8c9bbca 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_Library.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_Library.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. @@ -73,10 +73,10 @@ public View getView(int position, View convertView, ViewGroup parent) { material = data.get(position); // Setting all values in listview - title.setText(material.get(ListView_Library.KEY_TITLE)); - description.setText(material.get(ListView_Library.KEY_DESCRIPTION)); + title.setText(material.get(Fragm_Library.KEY_TITLE)); + description.setText(material.get(Fragm_Library.KEY_DESCRIPTION)); details.setText("Details"); - details.setTag(material.get(ListView_Library.KEY_DETAILS)); + details.setTag(material.get(Fragm_Library.KEY_DETAILS)); details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -84,7 +84,7 @@ public void onClick(View v) { } }); feedback.setText("Feedback"); - feedback.setTag(material.get(ListView_Library.KEY_FEEDBACK)); + feedback.setTag(material.get(Fragm_Library.KEY_FEEDBACK)); feedback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -93,21 +93,21 @@ public void onClick(View v) { }); addToMyLibrary.setText("Add to myLibrary"); - addToMyLibrary.setTag(material.get(ListView_Library.KEY_DELETE)); + addToMyLibrary.setTag(material.get(Fragm_Library.KEY_DELETE)); addToMyLibrary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "addToMyLibrary Clicked ********** "+v.getTag()); } }); - ratingAvgNum.setText(""+material.get(ListView_Library.KEY_RATING)); - ratingStars.setRating(Float.parseFloat(""+material.get(ListView_Library.KEY_RATING))); - totalNum.setText(material.get(ListView_Library.KEY_TOTALNUM_RATING)); + ratingAvgNum.setText(""+material.get(Fragm_Library.KEY_RATING)); + ratingStars.setRating(Float.parseFloat(""+material.get(Fragm_Library.KEY_RATING))); + totalNum.setText(material.get(Fragm_Library.KEY_TOTALNUM_RATING)); femalerating.setProgress(Integer.parseInt("1")); //femalerating.setProgress(Integer.parseInt(material.get(ListView_Library.KEY_FEMALE_RATING))); malerating.setProgress(Integer.parseInt("1")); //malerating.setProgress(Integer.parseInt(material.get(ListView_Library.KEY_MALE_RATING))); - imageLoader.DisplayImage(material.get(ListView_Library.KEY_THUMB_URL), thumb_image); + imageLoader.DisplayImage(material.get(Fragm_Library.KEY_THUMB_URL), thumb_image); return vi; } } \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myCourses.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myCourses.java similarity index 72% rename from app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myCourses.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myCourses.java index a172084..a2d2df0 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myCourses.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myCourses.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. @@ -20,6 +20,7 @@ import android.net.Uri; import android.os.AsyncTask; import android.os.Build; +import android.os.Environment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; @@ -42,6 +43,9 @@ import com.couchbase.lite.QueryRow; import com.couchbase.lite.android.AndroidContext; import com.google.gson.JsonObject; +import com.tonyodev.fetch.Fetch; +import com.tonyodev.fetch.listener.FetchListener; +import com.tonyodev.fetch.request.Request; import org.json.JSONObject; import org.lightcouch.CouchDbClientAndroid; @@ -69,6 +73,7 @@ public class ListViewAdapter_myCourses extends BaseAdapter { boolean singleFileDownload = true; public static final String PREFS_NAME = "MyPrefsFile"; CouchViews chViews = new CouchViews(); + long downloadId =0; /// String String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, @@ -97,6 +102,9 @@ public class ListViewAdapter_myCourses extends BaseAdapter { Cursor c; LogHouse logHouse = new LogHouse(); private OnCourseListListener mListener; + Fetch fetch; + List downloadListIDs = new ArrayList<>(); + List requests = new ArrayList<>(); public ListViewAdapter_myCourses(final List resIDsList, Activity a, Context cont, ArrayList> d) { activity = a; data = d; @@ -104,6 +112,11 @@ public ListViewAdapter_myCourses(final List resIDsList, Activity a, Cont inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader = new ImageLoader(activity.getApplicationContext()); + fetch = Fetch.newInstance(context); + + + +/* /// initialActivityLoad = true; BroadcastReceiver receiver = new BroadcastReceiver() { @Override @@ -168,8 +181,30 @@ public void onReceive(Context context, Intent intent) { } }; context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); + + */ this.mListener = null; mListener = (OnCourseListListener) cont; + + + fetch.addFetchListener(new FetchListener() { + + @Override + public void onUpdate(long id, int status, int progress, long downloadedBytes, long fileSize, int error) { + + if(downloadId == id && status == Fetch.STATUS_DOWNLOADING) { + Log.d(TAG,"downloading ooo."+ progress); + //progressBar.setProgress(progress); + }else if(error != Fetch.NO_ERROR) { + //An error occurred + + if(error == Fetch.ERROR_HTTP_NOT_FOUND) { + //handle error + } + + } + } + }); } public int getCount() { @@ -356,28 +391,31 @@ public void downloadCourseResources(String courseId){ if (courseId.equals((String) coursestep_properties.get("courseId"))) { ArrayList resourceList = (ArrayList) coursestep_properties.get("resourceId"); for (int cnt = 0; cnt < resourceList.size(); cnt++) { - resIDArrayList.add(String.valueOf(resourceList.get(cnt))); + if (!resIDArrayList.contains(String.valueOf(resourceList.get(cnt)))) { + resIDArrayList.add(String.valueOf(resourceList.get(cnt))); + } } Log.e(TAG, "Course Step title " + ((String) coursestep_properties.get("title")) + " "); courseStepsCounter++; } } - for(int x=0;x0) { - OneByOneResID = resIDArrayList.get(0); - mDialog = new ProgressDialog(activity.getWindow().getContext()); - mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); - mDialog.setMessage("Please wait..."); - mDialog.setCancelable(false); - mDialog.show(); - singleFileDownload = false; - OneByOneCourseId = courseId; - new downloadSpecificResourceToDisk().execute(); - - Log.e(TAG, "Clicked Showing wait"); + /// OneByOneResID = resIDArrayList.get(0); + // mDialog = new ProgressDialog(activity.getWindow().getContext()); + // mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); + // mDialog.setMessage("Please wait..."); + // mDialog.setCancelable(false); + // mDialog.show(); + // / singleFileDownload = false; + /// OneByOneCourseId = courseId; + /// new downloadSpecificResourceToDisk().execute(); + /// Log.e(TAG, "Clicked Showing wait"); ///mListener.onCourseDownloadingProgress(OneByOneResTitle,"Please Wait","Downloading item"); + }else{ } @@ -387,6 +425,106 @@ public void downloadCourseResources(String courseId){ } } + class FetchCompileDownload extends AsyncTask { + + private Exception exception; + + protected Boolean doInBackground(String... urls) { + try { + for(int x=0;x keys = _attachments.keys(); + if (keys.hasNext()) { + String key = (String) keys.next(); + Log.e(TAG, "-- " + key); + final String encodedkey = URLEncoder.encode(key, "utf-8"); + String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); + final String diskFileName = OneByOneResID + extension; + //activity.runOnUiThread(new Runnable() { + // @Override + // public void run() { + String root = Environment.getExternalStorageDirectory().toString(); + File dirPath = new File(root + "/ole_temp"); + String downloadURL = sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey; + Request request = new Request(downloadURL, dirPath.getAbsolutePath(), diskFileName); + requests.add(request); + + // Request request = new Request(downloadURL,dirPath.getAbsolutePath(),diskFileName); + // long downloadId = fetch.enqueue(request); + // downloadListIDs.add(downloadId); + // } + // }); + } + } + } + } catch (Exception e) { + Log.e(TAG, "Fetch -- Download this resource error " + e.getMessage()); + ///////////// mListener.onCourseDownloadingProgress(OneByOneResTitle,"Please Wait","Downloading item"); + /// mDialog.dismiss(); + alertDialogOkay("Fetch -- Error downloading file, check connection and try again"); + e.printStackTrace(); + } + + /// Log.e(TAG, "Resources for course ( "++" ) step " + resIDArrayList.get(x)); + } + fetch.enqueue(requests); + fetch.addFetchListener(new FetchListener() { + @Override + public void onUpdate(long id, int status, int progress, long downloadedBytes, long fileSize, int error) { + if(status == Fetch.STATUS_DOWNLOADING) { + Log.e(TAG, " Down 9" + progress); + + }else if(status == Fetch.STATUS_DONE) { + Log.e(TAG, " Completed All Down 1 " + progress); + fetch.release(); + }else if(error != Fetch.NO_ERROR) { + //An error occurred + Log.e(TAG, " Down Error No " + error); + if (error == Fetch.ERROR_HTTP_NOT_FOUND) { + //handle error + } + } + } + }); + // + /// List downloadIds = fetch.enqueue(requests); + + return true; + } catch (Exception e) { + this.exception = e; + return false; + } + } + + protected void onPostExecute() { + // TODO: check this.exception + // TODO: do something with the feed + } + } + public void downloadWithDownloadManagerSingleFile(String fileURL, String FileName) { String url = fileURL; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); @@ -449,8 +587,16 @@ protected Boolean doInBackground(String... params) { activity.runOnUiThread(new Runnable() { @Override public void run() { - downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey, diskFileName); - createCourseResourceDoc(OneByOneResID, title, openWith); + String root = Environment.getExternalStorageDirectory().toString(); + File dirPath = new File(root + "/ole_temp"); + Request request = new Request(sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey,dirPath.getAbsolutePath(),diskFileName); + downloadId = fetch.enqueue(request); + + + + + // downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey, diskFileName); + // createCourseResourceDoc(OneByOneResID, title, openWith); } }); diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myLibrary.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myLibrary.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myLibrary.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myLibrary.java index 80ca2f6..4df3500 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListViewAdapter_myLibrary.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ListViewAdapter_myLibrary.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/LogHouse.java b/app/src/main/java/org/ole/learning/planet/planetlearning/LogHouse.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/LogHouse.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/LogHouse.java index 7286b31..3fafe6b 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/LogHouse.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/LogHouse.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.annotation.SuppressLint; import android.content.Context; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Loading_Screen.java b/app/src/main/java/org/ole/learning/planet/planetlearning/MainActivity.java similarity index 76% rename from app/src/main/java/pbell/offline/ole/org/pbell/Loading_Screen.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/MainActivity.java index b42d3e6..56bfb88 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Loading_Screen.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/MainActivity.java @@ -1,29 +1,24 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.content.Intent; -import android.content.pm.PackageManager; import android.os.Environment; -import android.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; -import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; -public class Loading_Screen extends AppCompatActivity { +public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); - copyAPK(R.raw.adobe_reader, "adobe_reader.apk"); - copyAPK(R.raw.firefox_49_0_multi_android, "firefox_49_0_multi_android.apk"); - - +// copyAPK(R.raw.adobe_reader, "adobe_reader.apk"); +// copyAPK(R.raw.firefox_49_0_multi_android, "firefox_49_0_multi_android.apk"); Intent intent = new Intent(this, FullscreenLogin.class); startActivity(intent); finish(); diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/MemoryCache.java b/app/src/main/java/org/ole/learning/planet/planetlearning/MemoryCache.java similarity index 93% rename from app/src/main/java/pbell/offline/ole/org/pbell/MemoryCache.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/MemoryCache.java index 93fe46a..6a4f083 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/MemoryCache.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/MemoryCache.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ResourcesJson.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ResourcesJson.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/ResourcesJson.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ResourcesJson.java index aa6226b..b046bc8 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ResourcesJson.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ResourcesJson.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.app.NotificationManager; import android.content.Context; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ServerSearchService.java b/app/src/main/java/org/ole/learning/planet/planetlearning/ServerSearchService.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/ServerSearchService.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/ServerSearchService.java index 5747158..97fc2ea 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ServerSearchService.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/ServerSearchService.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.app.NotificationManager; import android.app.Service; import android.content.Context; diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/User_Dashboard.java b/app/src/main/java/org/ole/learning/planet/planetlearning/User_Dashboard.java similarity index 99% rename from app/src/main/java/pbell/offline/ole/org/pbell/User_Dashboard.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/User_Dashboard.java index d7bb9eb..fe72b6b 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/User_Dashboard.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/User_Dashboard.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; import android.annotation.SuppressLint; import android.app.Activity; @@ -116,8 +116,6 @@ protected void onCreate(Bundle savedInstanceState) { restorePreferences(); ///totalVisits(sys_usercouchId); loadUIDynamicText(); - - Fragm_Loading loading = new Fragm_Loading(); Bundle args = new Bundle(); args.putString("targetAction", "myLibrary"); diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Utils.java b/app/src/main/java/org/ole/learning/planet/planetlearning/Utils.java similarity index 92% rename from app/src/main/java/pbell/offline/ole/org/pbell/Utils.java rename to app/src/main/java/org/ole/learning/planet/planetlearning/Utils.java index 83d2704..1954645 100644 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Utils.java +++ b/app/src/main/java/org/ole/learning/planet/planetlearning/Utils.java @@ -1,4 +1,4 @@ -package pbell.offline.ole.org.pbell; +package org.ole.learning.planet.planetlearning; /** * Created by leonardmensah on 06/06/2017. diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/AppController.java b/app/src/main/java/pbell/offline/ole/org/pbell/AppController.java deleted file mode 100644 index bf4d843..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/AppController.java +++ /dev/null @@ -1,67 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 30/05/16. - */ - - import android.app.Application; - import android.text.TextUtils; - import com.android.volley.Request; - import com.android.volley.RequestQueue; - import com.android.volley.toolbox.ImageLoader; - import com.android.volley.toolbox.Volley; - -@SuppressWarnings("ALL") -public class AppController extends Application { - - public static final String TAG = AppController.class.getSimpleName(); - - private RequestQueue mRequestQueue; - private ImageLoader mImageLoader; - - private static AppController mInstance; - - @Override - public void onCreate() { - super.onCreate(); - mInstance = this; - } - - public static synchronized AppController getInstance() { - return mInstance; - } - - public RequestQueue getRequestQueue() { - if (mRequestQueue == null) { - mRequestQueue = Volley.newRequestQueue(getApplicationContext()); - } - - return mRequestQueue; - } - - public ImageLoader getImageLoader() { - getRequestQueue(); - if (mImageLoader == null) { - mImageLoader = new ImageLoader(this.mRequestQueue, - new LruBitmapCache()); - } - return this.mImageLoader; - } - - public void addToRequestQueue(Request req, String tag) { - // set the default tag if tag is empty - req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); - getRequestQueue().add(req); - } - - public void addToRequestQueue(Request req) { - req.setTag(TAG); - getRequestQueue().add(req); - } - - public void cancelPendingRequests(Object tag) { - if (mRequestQueue != null) { - mRequestQueue.cancelAll(tag); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Bar.java b/app/src/main/java/pbell/offline/ole/org/pbell/Bar.java deleted file mode 100644 index 7cfcc4a..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Bar.java +++ /dev/null @@ -1,33 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 07/03/2017. - */ - -import org.lightcouch.Document; - -@SuppressWarnings("ALL") -public class Bar extends Document { - private String bar; - - public Bar() { - - } - - public Bar(String id) { - this.setId(id); - } - - public String getBar() { - return bar; - } - - public void setBar(String bar) { - this.bar = bar; - } - - @Override - public String toString() { - return "Bar [bar=" + bar + "]"; - } -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/CourceListCustomAdapter.java b/app/src/main/java/pbell/offline/ole/org/pbell/CourceListCustomAdapter.java deleted file mode 100644 index 2ec292b..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/CourceListCustomAdapter.java +++ /dev/null @@ -1,88 +0,0 @@ -package pbell.offline.ole.org.pbell; - - -import android.app.Activity; -import android.content.Context; -import android.content.res.Resources; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.ImageView; -import android.widget.TextView; - -import com.android.volley.toolbox.ImageLoader; - -import java.util.List; - -@SuppressWarnings("ALL") -public class CourceListCustomAdapter extends BaseAdapter { - private Activity activity; - private LayoutInflater inflater; - private List resourceItems; - public Resources res; - - ImageLoader imageLoader = AppController.getInstance().getImageLoader(); - public CourceListCustomAdapter(Activity activity, List resourceItems) { - this.activity = activity; - this.resourceItems = resourceItems; - } - - @Override - public int getCount() { - return resourceItems.size(); - } - - @Override - public Object getItem(int location) { - return resourceItems.get(location); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - - if (inflater == null) - inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - if (convertView == null) - convertView = inflater.inflate(R.layout.list_row, null); - - if (imageLoader == null) - imageLoader = AppController.getInstance().getImageLoader(); - // NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail); - ImageView thumbNail = (ImageView) convertView.findViewById(R.id.thumbnail); - TextView title = (TextView) convertView.findViewById(R.id.title); - TextView rating = (TextView) convertView.findViewById(R.id.rating); - TextView genre = (TextView) convertView.findViewById(R.id.genre); - TextView year = (TextView) convertView.findViewById(R.id.releaseYear); - - // getting resource data for the row - CourseList r = resourceItems.get(position); - - // thumbnail image - thumbNail.setBackgroundResource(r.getThumbnailUrl()); - //thumbNail.setImageUrl(r.getThumbnailUrl(), imageLoader); - - // title - title.setText(r.getTitle()); - - // rating - rating.setText("" + String.valueOf(r.getDescription())); - - // genre - String genreStr = ""; - genreStr = genreStr.length() > 0 ? genreStr.substring(0, - genreStr.length() - 2) : genreStr; - genre.setText(genreStr); - - // release Rating - year.setText("End date : " + String.valueOf(r.getRating())); - - return convertView; - } - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Course.java b/app/src/main/java/pbell/offline/ole/org/pbell/Course.java deleted file mode 100644 index 4d5cb05..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Course.java +++ /dev/null @@ -1,165 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.support.design.widget.TabLayout; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; - -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.view.ViewPager; -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import android.widget.TextView; - -@SuppressWarnings("ALL") -public class Course extends AppCompatActivity { - - /** - * The {@link android.support.v4.view.PagerAdapter} that will provide - * fragments for each of the sections. We use a - * {@link FragmentPagerAdapter} derivative, which will keep every - * loaded fragment in memory. If this becomes too memory intensive, it - * may be best to switch to a - * {@link android.support.v4.app.FragmentStatePagerAdapter}. - */ - private SectionsPagerAdapter mSectionsPagerAdapter; - - /** - * The {@link ViewPager} that will host the section contents. - */ - private ViewPager mViewPager; - - String in_courseID=""; - int NumberOfStages=0; - - @Override - protected void onCreate(Bundle savedInstanceState) { - - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_course); - - NumberOfStages=3; - - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - // Create the adapter that will return a fragment for each of the three - // primary sections of the activity. - mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - - // Set up the ViewPager with the sections adapter. - mViewPager = (ViewPager) findViewById(R.id.container); - mViewPager.setAdapter(mSectionsPagerAdapter); - - TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); - tabLayout.setupWithViewPager(mViewPager); - - Bundle bundle = getIntent().getExtras(); - - if(bundle != null){ - in_courseID = bundle.getString("courseID"); - }else{ - in_courseID = ""; - } - Log.d("tag2", "Inside Course Steps Page : " + in_courseID); - - - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.menu_course, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle action bar item clicks here. The action bar will - // automatically handle clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - int id = item.getItemId(); - - //noinspection SimplifiableIfStatement - if (id == R.id.action_settings) { - return true; - } - - return super.onOptionsItemSelected(item); - } - - /** - * A placeholder fragment containing a simple view. - */ - public static class PlaceholderFragment extends Fragment { - /** - * The fragment argument representing the section number for this - * fragment. - */ - private static final String ARG_SECTION_NUMBER = "section_number"; - - public PlaceholderFragment() { - } - - /** - * Returns a new instance of this fragment for the given section - * number. - */ - public static PlaceholderFragment newInstance(int sectionNumber) { - PlaceholderFragment fragment = new PlaceholderFragment(); - Bundle args = new Bundle(); - args.putInt(ARG_SECTION_NUMBER, sectionNumber); - fragment.setArguments(args); - return fragment; - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_course, container, false); - TextView textView = (TextView) rootView.findViewById(R.id.txtStepTitle); - textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))); - return rootView; - } - } - - /** - * A {@link FragmentPagerAdapter} that returns a fragment corresponding to - * one of the sections/tabs/pages. - */ - public class SectionsPagerAdapter extends FragmentPagerAdapter { - - public SectionsPagerAdapter(FragmentManager fm) { - super(fm); - } - - @Override - public Fragment getItem(int position) { - // getItem is called to instantiate the fragment for the given page. - // Return a PlaceholderFragment (defined as a static inner class below). - return PlaceholderFragment.newInstance(position + 1); - } - - @Override - public int getCount() { - // Show 3 total pages. - return NumberOfStages; - } - - @Override - public CharSequence getPageTitle(int position) { - switch (position) { - default: - return "Stage "+(position+1); - } - } - } -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/CourseList.java b/app/src/main/java/pbell/offline/ole/org/pbell/CourseList.java deleted file mode 100644 index e88fefb..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/CourseList.java +++ /dev/null @@ -1,70 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import java.util.ArrayList; - -/** - * Created by leonardmensah on 21/07/16. - */ -@SuppressWarnings("ALL") -public class CourseList { - - private String title; - private int thumbnailUrl; - private String rating; - private String descr; - private ArrayList genre; - - public CourseList() { - - } - - public CourseList(String name, int thumbnailUrl, String rating, String descr, - ArrayList genre) { - this.title = name; - this.thumbnailUrl = thumbnailUrl; - this.rating = rating; - this.descr = descr; - this.genre = genre; - } - - public String getTitle() { - return title; - } - - public void setTitle(String name) { - this.title = name; - } - - public int getThumbnailUrl() { - return thumbnailUrl; - } - - public void setThumbnailUrl(int thumbnailUrl) { - this.thumbnailUrl = thumbnailUrl; - } - - public String getRating() { - return rating; - } - - public void setRating(String rating) { - this.rating = rating; - } - - public String getDescription() { - return descr; - } - - public void setDescription(String descr) { - this.descr = descr; - } - - public ArrayList getGenre() { - return genre; - } - - public void setGenre(ArrayList genre) { - this.genre = genre; - } - -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/CustomAdapter.java b/app/src/main/java/pbell/offline/ole/org/pbell/CustomAdapter.java deleted file mode 100644 index e4e07ae..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/CustomAdapter.java +++ /dev/null @@ -1,159 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 18/05/16. - */ - -import android.app.Activity; -import android.content.Context; -import android.content.res.Resources; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.ImageView; -import android.widget.TextView; - -import java.util.ArrayList; - -/********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/ -@SuppressWarnings("ALL") -public class CustomAdapter extends BaseAdapter implements View.OnClickListener { - - /*********** Declare Used Variables *********/ - private Activity activity; - private ArrayList data; - private static LayoutInflater inflater=null; - public Resources res; - ListModel tempValues=null; - int i=0; - - /************* CustomAdapter Constructor *****************/ - public CustomAdapter(Activity a, ArrayList d,Resources resLocal) { - - /********** Take passed values **********/ - activity = a; - data=d; - res = resLocal; - - /*********** Layout inflator to call external xml layout () ***********/ - inflater = ( LayoutInflater )activity. - getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - } - - /******** What is the size of Passed Arraylist Size ************/ - public int getCount() { - - if(data.size()<=0) - return 1; - return data.size(); - } - - public Object getItem(int position) { - return position; - } - - public long getItemId(int position) { - return position; - } - - /********* Create a holder Class to contain inflated xml file elements *********/ - public static class ViewHolder{ - - public TextView text; - public TextView text1; - public TextView textWide; - public ImageView image; - - } - - /****** Depends upon data size called for each row , Create each ListView row *****/ - public View getView(int position, View convertView, ViewGroup parent) { - - View vi = convertView; - ViewHolder holder; - - if(convertView==null){ - - /****** Inflate tabitem.xml file for each row ( Defined below ) *******/ - vi = inflater.inflate(R.layout.tabitem, null); - - /****** View Holder Object to contain tabitem.xml file elements ******/ - - holder = new ViewHolder(); - holder.text = (TextView) vi.findViewById(R.id.text); - holder.text1=(TextView)vi.findViewById(R.id.text1); - holder.image=(ImageView)vi.findViewById(R.id.image); - - /************ Set holder with LayoutInflater ************/ - vi.setTag( holder ); - } - else - holder=(ViewHolder)vi.getTag(); - - if(data.size()<=0) - { - holder.text.setText("No Data"); - - } - else - { - /***** Get each Model object from Arraylist ********/ - tempValues=null; - tempValues = ( ListModel ) data.get( position ); - - /************ Set Model values in Holder elements ***********/ - - holder.text.setText( tempValues.getTitle() ); - holder.text1.setText( tempValues.getDescription() ); - holder.image.setImageResource( res.getIdentifier("com.androidexample.customlistview:drawable/"+tempValues.getImage() ,null,null)); - - /******** Set Item Click Listner for LayoutInflater for each row *******/ - - vi.setOnClickListener(new OnItemClickListener( position )); - } - return vi; - } - - @Override - public void onClick(View v) { - Log.v("CustomAdapter", "=====Row button clicked====="); - } - - /********* Called when Item click in ListView ************/ - private class OnItemClickListener implements View.OnClickListener { - private int mPosition; - - OnItemClickListener(int position){ - mPosition = position; - } - - @Override - public void onClick(View arg0) { - - - ///TabFragment1 sct = (TabFragment1)activity; - - /**** Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/ - - //sct.onItemClick(mPosition); - } - } -} - - - - - - - - - - - - - - - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/CustomListAdapter.java b/app/src/main/java/pbell/offline/ole/org/pbell/CustomListAdapter.java deleted file mode 100644 index 4b38659..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/CustomListAdapter.java +++ /dev/null @@ -1,88 +0,0 @@ -package pbell.offline.ole.org.pbell; - - import java.util.List; - - import android.app.Activity; - import android.content.Context; - import android.content.res.Resources; - import android.view.LayoutInflater; - import android.view.View; - import android.view.ViewGroup; - import android.widget.BaseAdapter; - import android.widget.ImageView; - import android.widget.TextView; - - import com.android.volley.toolbox.ImageLoader; - -@SuppressWarnings("ALL") -public class CustomListAdapter extends BaseAdapter { - private Activity activity; - private LayoutInflater inflater; - private List resourceItems; - public Resources res; - - ImageLoader imageLoader = AppController.getInstance().getImageLoader(); - public CustomListAdapter(Activity activity, List resourceItems) { - this.activity = activity; - this.resourceItems = resourceItems; - } - - @Override - public int getCount() { - return resourceItems.size(); - } - - @Override - public Object getItem(int location) { - return resourceItems.get(location); - } - - @Override - public long getItemId(int position) { - return position; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - - if (inflater == null) - inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - if (convertView == null) - convertView = inflater.inflate(R.layout.list_row, null); - - if (imageLoader == null) - imageLoader = AppController.getInstance().getImageLoader(); - // NetworkImageView thumbNail = (NetworkImageView) convertView.findViewById(R.id.thumbnail); - ImageView thumbNail = (ImageView) convertView.findViewById(R.id.thumbnail); - TextView title = (TextView) convertView.findViewById(R.id.title); - TextView rating = (TextView) convertView.findViewById(R.id.rating); - TextView genre = (TextView) convertView.findViewById(R.id.genre); - TextView year = (TextView) convertView.findViewById(R.id.releaseYear); - - // getting resource data for the row - Resource r = resourceItems.get(position); - - // thumbnail image - thumbNail.setBackgroundResource(r.getThumbnailUrl()); - //thumbNail.setImageUrl(r.getThumbnailUrl(), imageLoader); - - // title - title.setText(r.getTitle()); - - // rating - //rating.setText(" " + String.valueOf(r.getDescription())); - rating.setText(" "); - - // genre - String genreStr = ""; - genreStr = genreStr.length() > 0 ? genreStr.substring(0, - genreStr.length() - 2) : genreStr; - genre.setText(genreStr); - - // release Rating - year.setText(String.valueOf(r.getRating())); - - return convertView; - } - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Dashboard.java b/app/src/main/java/pbell/offline/ole/org/pbell/Dashboard.java deleted file mode 100644 index 08fb5b1..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Dashboard.java +++ /dev/null @@ -1,339 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 19/05/16. - */ - -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.os.StrictMode; -import android.support.annotation.IdRes; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.app.FragmentTransaction; -import android.support.v4.content.ContextCompat; -import android.support.v4.view.ViewPager; -import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.util.Log; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; -import android.widget.Toast; - -import com.roughike.bottombar.BottomBar; -import com.roughike.bottombar.OnMenuTabClickListener; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Set; - -@SuppressWarnings("ALL") -public class Dashboard extends AppCompatActivity { - private BottomBar mBottomBar; - private TextView mMessageView; - final Context context = this; - private EditText txtSuncURL = null; - - - private ViewPager mViewPager; - private SectionsPagerAdapter mySectionsPagerAdapter; - TabFragment0 tab0 = new TabFragment0(); - TabFragment1 tab1 = new TabFragment1(); - TabFragment2 tab2 = new TabFragment2(); - TabFragment3 tab3 = new TabFragment3(); - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - - String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, - sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname, - sys_usergender, sys_uservisits = ""; - int sys_uservisits_Int = 0; - Object[] sys_membersWithResource; - boolean userShelfSynced = false; - - - FragmentManager fragMgr = getSupportFragmentManager(); - FragmentTransaction fragTrans = fragMgr.beginTransaction(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_dashboard); - - Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbar); - setSupportActionBar(toolbar); - StrictMode.VmPolicy.Builder stModeBuilder = new StrictMode.VmPolicy.Builder(); - StrictMode.setVmPolicy(stModeBuilder.build()); - - ///settings = context.getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE); - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username", ""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl", ""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate", ""); - sys_password = settings.getString("pf_password", ""); - sys_usercouchId = settings.getString("pf_usercouchId", ""); - sys_userfirstname = settings.getString("pf_userfirstname", ""); - sys_userlastname = settings.getString("pf_userlastname", ""); - sys_usergender = settings.getString("pf_usergender", ""); - sys_uservisits = settings.getString("pf_uservisits", ""); - - try { - Set mwr = settings.getStringSet("membersWithResource", null); - sys_membersWithResource = mwr.toArray(); - for (int cnt = 0; cnt < sys_membersWithResource.length; cnt++) { - - Log.e("MYAPP", " members With Resource Synced = " + sys_membersWithResource[cnt]); - if (sys_membersWithResource[cnt].equals(sys_usercouchId)) { - userShelfSynced = true; - break; - } - } - } catch (Exception err) { - - Log.e("TakeHome", " MembersWithResource Array" + err.getMessage()); - } - - if (!userShelfSynced) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("Materials on your shelf are NOT yet synchronized unto this device. " + - "You can only view title of items on your shelf BUT you can not launch or read them." + - "To access your materials on this device, please sync device with server.") - .setCancelable(false) - .setPositiveButton("Okay", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - }); - - AlertDialog closeDialogue = builder.create(); - closeDialogue.show(); - } - - /// Log.e("MYAPP", " membersWithResource = "+sys_membersWithResource.length); - - - TextView lbldate = (TextView) findViewById(R.id.lblDate); - - Calendar cal = Calendar.getInstance(); - Date d = new Date(); - - SimpleDateFormat s_df = new SimpleDateFormat("EEEE"); - String dayOfTheWeek = s_df.format(d); - SimpleDateFormat date_df = new SimpleDateFormat("d"); - String dayNumber = date_df.format(d); - SimpleDateFormat month_df = new SimpleDateFormat("MMMM"); - String month_name = month_df.format(cal.getTime()); - SimpleDateFormat year_df = new SimpleDateFormat("yyyy"); - String year = year_df.format(d); - String displayedDate = dayOfTheWeek + " | " + dayNumber + " " + month_name + " " + year; - lbldate.setText(displayedDate); - - - mySectionsPagerAdapter = new SectionsPagerAdapter(fragMgr); - mViewPager = (ViewPager) findViewById(R.id.container); - mViewPager.setAdapter(mySectionsPagerAdapter); - - mBottomBar = BottomBar.attach(this, savedInstanceState); - mBottomBar.useOnlyStatusBarTopOffset(); - //mBottomBar.setMaxFixedTabs(n-1); - //mBottomBar.noNavBarGoodness(); - // mBottomBar = BottomBar.attachShy((CoordinatorLayout) findViewById(R.id.main_content),findViewById(R.id.container), savedInstanceState); - - mBottomBar.noTabletGoodness(); - mBottomBar.setItemsFromMenu(R.menu.bottombar_menu, new OnMenuTabClickListener() { - @Override - public void onMenuTabSelected(@IdRes int menuItemId) { - /// mMessageView.setText(getMessage(menuItemId, false)); - } - - @Override - public void onMenuTabReSelected(@IdRes int menuItemId) { - Toast.makeText(getApplicationContext(), getMessage(menuItemId, true), Toast.LENGTH_SHORT).show(); - } - }); - - - // Setting colors for different tabs when there's more than three of them. - // You can set colors for tabs in three different ways as shown below. - mBottomBar.mapColorForTab(0, ContextCompat.getColor(this, R.color.colorAccent)); - mBottomBar.mapColorForTab(1, 0xFF5D4037); - mBottomBar.mapColorForTab(2, "#7B1FA2"); - mBottomBar.mapColorForTab(3, "#FF5252"); - - - //mBottomBar.hide(); - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.menu_main, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle action bar item clicks here. The action bar will - // automatically handle clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - int id = item.getItemId(); - - //noinspection SimplifiableIfStatement - if (id == R.id.action_syncserverUrl) { - SyncDialog(sys_oldSyncServerURL); - return true; - } else if (id == R.id.action_syncNow) { - Intent syncdeviceIntent = new Intent(this, SyncDevice.class); - ///intent.putExtra(EXTRA_MESSAGE, message); - startActivity(syncdeviceIntent); - return true; - } else if (id == R.id.action_about) { - return true; - } else if (id == R.id.action_help) { - return true; - } else if (id == R.id.action_profile) { - return true; - } - - return super.onOptionsItemSelected(item); - } - - - private String getMessage(int menuItemId, boolean isReselection) { - String message = "Content for "; - - switch (menuItemId) { - case R.id.bb_menu_friends: - mViewPager.setCurrentItem(0); - message += "Achievements"; - break; - case R.id.bb_menu_favorites: - mViewPager.setCurrentItem(2); - message += "My Library"; - break; - case R.id.bb_menu_recents: - mViewPager.setCurrentItem(1); - message += ""; - break; - case R.id.bb_menu_food: - mViewPager.setCurrentItem(3); - message += ""; - break; - } - - if (isReselection) { - message += ""; - } - - return message; - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - - // Necessary to restore the BottomBar's state, otherwise we would - // lose the current tab on orientation change. - mBottomBar.onSaveInstanceState(outState); - } - - - public class SectionsPagerAdapter extends FragmentPagerAdapter { - - public SectionsPagerAdapter(FragmentManager fm) { - - super(fm); - } - - @Override - public Fragment getItem(int position) { - - switch (position) { - case 0: - return tab0; - case 1: - return tab1; - case 2: - return tab2; - case 3: - return tab3; - default: - return null; - } - } - - @Override - public int getCount() { - // Show 3 total pages. - return 4; - } - - } - - /* - public static class PlaceholderFragment extends Fragment { - //The fragment argument representing the section number for this fragment. - private static final String ARG_SECTION_NUMBER = "section_number"; - - //Returns a new instance of this fragment for the given section - - public static PlaceholderFragment newInstance(int sectionNumber) { - PlaceholderFragment fragment = new PlaceholderFragment(); - Bundle args = new Bundle(); - args.putInt(ARG_SECTION_NUMBER, sectionNumber); - fragment.setArguments(args); - return fragment; - } - - public PlaceholderFragment() { - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_main, container, false); - return rootView; - } - } - - */ - public void SyncDialog(String oldSyncURL) { - // custom dialog - final Dialog dialog = new Dialog(context); - dialog.setContentView(R.layout.syncurl_dialog); - dialog.setTitle("Synchronization Server Url"); - - txtSuncURL = (EditText) dialog.findViewById(R.id.txtsyncURL); - txtSuncURL.setText(oldSyncURL); - Button dialogButton = (Button) dialog.findViewById(R.id.btnSaveSyncURL); - dialogButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - sys_oldSyncServerURL = txtSuncURL.getText().toString(); - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_sysncUrl", sys_oldSyncServerURL); - editor.commit(); - - dialog.dismiss(); - } - }); - - dialog.show(); - - } - -} - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/DemoDataLoader.java b/app/src/main/java/pbell/offline/ole/org/pbell/DemoDataLoader.java deleted file mode 100644 index 7d59757..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/DemoDataLoader.java +++ /dev/null @@ -1,1020 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.app.Activity; -import android.app.DownloadManager; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.database.Cursor; -import android.graphics.drawable.LayerDrawable; -import android.os.AsyncTask; -import android.os.Environment; -import android.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.Button; -import android.widget.ProgressBar; -import android.widget.RatingBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.android.AndroidContext; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by leonardmensah on 8/2/17. - */ - -public class DemoDataLoader { - - private Activity activity; - private ArrayList> data; - private static LayoutInflater inflater = null; - public ImageLoader imageLoader; - private static final String TAG = "MYAPP"; - Context context; - private ProgressDialog mDialog; - private long enqueue; - private DownloadManager downloadManager; - boolean singleFileDownload = true; - public static final String PREFS_NAME = "MyPrefsFile"; - CouchViews chViews = new CouchViews(); - - /// String - String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, - sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname, - sys_usergender, sys_uservisits, sys_servername, sys_serverversion = ""; - Boolean sys_demoMode; - AndroidContext androidContext; - - String OneByOneResID, OneByOneResTitle, OneByOneCourseId; - int courseStepsCounter = 0; - int action_button_id = 0; - SharedPreferences settings; - List resIDArrayList = new ArrayList<>(); - View vi; - - TextView title, description, ratingAvgNum, totalNum; - Button open; - RatingBar ratingStars; - LayerDrawable stars; - ProgressBar femalerating, malerating; - String activityName = "myCourses"; - - - protected int _splashTime = 5000; - private Thread splashTread; - - private long enqueues; - private DownloadManager dm; - Cursor c; - LogHouse logHouse = new LogHouse(); - private ListViewAdapter_myCourses.OnCourseListListener mListener; - Button SignInButton; - String[] databaseList = {"members", "meetups", "usermeetups", "assignments", - "assignmentpaper", "courseanswer", "coursequestion", "courses", "courseschedule", "coursestep", "membercourseprogress", - "calendar", "groups", "invitations", "configurations", "requests", "shelf", "languages"}; - - public DemoDataLoader(Context context, Button btn) { - SignInButton = btn; - this.context = context; - androidContext = new AndroidContext(this.context); - - /// Start - new startHere().execute(); - - } - - public void restorePreferences() { - settings = context.getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username", "learner"); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl", "http://demo:oleoleole@demo.ole.org:5995"); - sys_lastSyncDate = settings.getString("pf_lastSyncDate", ""); - sys_password = settings.getString("pf_password", "learner"); - sys_usercouchId = settings.getString("pf_usercouchId", ""); - sys_userfirstname = settings.getString("pf_userfirstname", "Demo"); - sys_userlastname = settings.getString("pf_userlastname", "Learner"); - sys_usergender = settings.getString("pf_usergender", "Female"); - sys_uservisits = settings.getString("pf_uservisits", "5"); - sys_servername = settings.getString("pf_server_name", "demo"); - sys_serverversion = settings.getString("pf_server_version", " "); - sys_serverversion = settings.getString("pf_server_code", "demo"); - sys_demoMode = settings.getBoolean("sys_demoMode", true); - - sys_oldSyncServerURL = "http://demo:oleoleole@demo.ole.org:5995"; - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_sysncUrl", sys_oldSyncServerURL); - editor.commit(); - } - - private class startHere extends AsyncTask { - @Override - protected Void doInBackground(Void... params) { - emptyAllDbs(); - return null; - } - - @Override - protected void onPostExecute(Void result) { - ResourcesJson rsj = new ResourcesJson(); - createConfigurations(); - restorePreferences(); - createMembers(); - createShelf(); - createCourses(); - createCoursestep(); - createMembercourseprogress(); - shadowresources_demo(); - listAssetFiles(); - //if(rsj.ResourcesJson(sys_oldSyncServerURL,"resources",androidContext)){ - //} - SignInButton.performClick(); - - } - } - - private boolean listAssetFiles() { - try { - String[] list = context.getAssets().list(""); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()) { - myDir.mkdirs(); - Log.v(TAG, "Had to create ole tamp folder " + myDir.getAbsolutePath()); - } - for (String file : list) { - Log.v(TAG, "Files in assets folder include " + file); - InputStream in = context.getAssets().open(file); - File dst = new File(myDir, file); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", file + " Copied " + dst.toString()); - } catch (Exception err) { - err.printStackTrace(); - } - } - } catch (IOException e) { - return false; - } - - return true; - } - - - public void emptyAllDbs() { - for (int cnt = 0; cnt < databaseList.length; cnt++) { - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getDatabase(databaseList[cnt]); - Log.e("MYAPP", "Deleting " + databaseList[cnt]); - db.delete(); - } catch (Exception e) { - e.printStackTrace(); - } - } - //// Delete Device Created Databases - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database dbResources = manager.getDatabase("resources"); - dbResources.delete(); - } catch (Exception err) { - err.printStackTrace(); - } - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database dbResources = manager.getDatabase("shadowresources"); - dbResources.delete(); - } catch (Exception err) { - err.printStackTrace(); - } - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database dbOffline_courses = manager.getDatabase("offline_courses"); - dbOffline_courses.delete(); - } catch (Exception err) { - err.printStackTrace(); - } - - try { - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - String[] flist = myDir.list(); - for (int i = 0; i < flist.length; i++) { - System.out.println(" " + myDir.getAbsolutePath()); - File temp = new File(myDir.getAbsolutePath() + "/" + flist[i]); - if (temp.isDirectory()) { - Log.d("Delete ", " Deleting " + temp.getName()); - temp.delete(); - } else { - temp.delete(); - } - } - } catch (Exception err) { - Log.e("MYAPP", " Deleting materials from ole_temp directory "); - } - - } - - public void createConfigurations() { - Manager manager = null; - Database configuration; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - configuration = manager.getDatabase("configurations"); - Document newdocument = configuration.getDocument("e3d7ca503eef922213e36bf3d6001389"); - Map newProperties = new HashMap(); - //newProperties.put("_rev", "1-51967df030f45163a9a5dc53dbfdbdca"); - newProperties.put("name", "demo"); - newProperties.put("nationName", "earthbell"); - newProperties.put("code", "demo"); - newProperties.put("type", "nation"); - newProperties.put("nationUrl", "earthbell.ole.org:5989"); - newProperties.put("version", "0.13.5"); - newProperties.put("notes", "Nation Bell"); - newProperties.put("currentLanguage", "English"); - newProperties.put("register", "nbs.ole.org:5997"); - newdocument.putProperties(newProperties); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void createMembers() { - Manager manager = null; - Database members; - ArrayList rolesList = new ArrayList(); - Map credentialMap = new HashMap(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - members = manager.getDatabase("members"); - Document newdocument = members.getDocument("e3d7ca503eef922213e36bf3d60080c2"); - Map newProperties = new HashMap(); - newProperties.put("kind", "Member"); - newProperties.put("bellLanguage", "English"); - newProperties.put("firstName", "Demo"); - newProperties.put("lastName", "Learner"); - newProperties.put("password", ""); - newProperties.put("phone", "234562345"); - newProperties.put("kind", "Member"); - newProperties.put("language", "English"); - newProperties.put("BirthDate", "1988-04-20T00:00:00.000Z"); - newProperties.put("visits", 5); - newProperties.put("Gender", "Female"); - newProperties.put("levels", "Higher"); - newProperties.put("community", "demo"); - newProperties.put("nation", "earthbell"); - newProperties.put("login", "learner"); - rolesList.add("Learner"); - rolesList.add("Leader"); - newProperties.put("roles", rolesList); - credentialMap.put("salt", "c0a24b98e089b6b0f5d3674430cebe0c"); - credentialMap.put("value", "53580b4213093aa7bda95c597d3eddfd7d5005d5"); - credentialMap.put("login", "learner"); - newProperties.put("credentials", credentialMap); - newdocument.putProperties(newProperties); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void createShelf() { - Manager manager = null; - Database shelf; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - shelf = manager.getDatabase("shelf"); - Document newdocument1 = shelf.getDocument("e3d7ca503eef922213e36bf3d600d0ea"); - Map newProperties1 = new HashMap(); - newProperties1.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties1.put("resourceId", "d3f3756c79722902f983267053025c21"); - newProperties1.put("resourceTitle", "الأميرة القاسِيَة"); - newdocument1.putProperties(newProperties1); - - Document newdocument2 = shelf.getDocument("e3d7ca503eef922213e36bf3d6017dd7"); - Map newProperties2 = new HashMap(); - newProperties2.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties2.put("resourceId", "3a162fea1d56beb7a4441a4a8018e5b0"); - newProperties2.put("resourceTitle", "Mental Health Strategies for Refugee Children"); - newdocument2.putProperties(newProperties2); - - Document newdocument3 = shelf.getDocument("e3d7ca503eef922213e36bf3d6018b07"); - Map newProperties3 = new HashMap(); - newProperties3.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties3.put("resourceId", "61461c3cf80877891652a143c3c77fed"); - newProperties3.put("resourceTitle", "Education in Emergency"); - newdocument3.putProperties(newProperties3); - - Document newdocument4 = shelf.getDocument("e3d7ca503eef922213e36bf3d6019428"); - Map newProperties4 = new HashMap(); - newProperties4.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties4.put("resourceId", "a28c81eac20e23529a5eda8e850eaeb3"); - newProperties4.put("resourceTitle", "Emergency Preparedness Plans"); - newdocument4.putProperties(newProperties4); - - - Document newdocument5 = shelf.getDocument("e3d7ca503eef922213e36bf3d601a08a"); - Map newProperties5 = new HashMap(); - newProperties5.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties5.put("resourceId", "68ec3d6c83989920cb75df8e5d01c449"); - newProperties5.put("resourceTitle", "Healthy Child Uganda VHT Training Manual: Paring a Community Emergency Transport Plan (CETP)"); - newdocument5.putProperties(newProperties5); - - Document newdocument6 = shelf.getDocument("e3d7ca503eef922213e36bf3d601a50a"); - Map newProperties6 = new HashMap(); - newProperties6.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties6.put("resourceId", "86ba8cb7d819aa7068748640fb347ab1"); - newProperties6.put("resourceTitle", "Children in War: The role of Child to Child Activities in the Therapy and Care of Displaced Unaccompanied Children"); - newdocument6.putProperties(newProperties6); - - - Document newdocument7 = shelf.getDocument("e3d7ca503eef922213e36bf3d601aac0"); - Map newProperties7 = new HashMap(); - newProperties7.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties7.put("resourceId", "326b61c2ae2be1b31cb65891cbbf1536"); - newProperties7.put("resourceTitle", "Because I Am a Girl"); - newdocument7.putProperties(newProperties7); - - - Document newdocument8 = shelf.getDocument("e3d7ca503eef922213e36bf3d601ba3d"); - Map newProperties8 = new HashMap(); - newProperties8.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties8.put("resourceId", "78c923afd67a7dc59b3f68b03b63bb17"); - newProperties8.put("resourceTitle", "Because I Am a Girl: A Year of Action and Innovation / Parce que je suis une fille: Une annee d’action et d’innovation (French)"); - newdocument8.putProperties(newProperties8); - - - Document newdocument9 = shelf.getDocument("e3d7ca503eef922213e36bf3d601c141"); - Map newProperties9 = new HashMap(); - newProperties9.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties9.put("resourceId", "242a13d826420075a3ece5f0ea31b1fb"); - newProperties9.put("resourceTitle", "Gender Awareness Workshop (en)"); - newdocument9.putProperties(newProperties9); - - Document newdocument10 = shelf.getDocument("e3d7ca503eef922213e36bf3d601c3c5"); - Map newProperties10 = new HashMap(); - newProperties10.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - newProperties10.put("resourceId", "acbdd7ae8325d8ff27fed560779f2fd1"); - newProperties10.put("resourceTitle", "To Educate a Girl - Lesson Plan (Grade 9-12)"); - newdocument10.putProperties(newProperties10); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void shadowresources_demo() { - Manager manager = null; - Database shadowresources_demo; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - shadowresources_demo = manager.getDatabase("shadowresources_demo"); - Document newdocument1 = shadowresources_demo.getDocument("d3f3756c79722902f983267053025c21"); - Map newProperties1 = new HashMap(); - newProperties1.put("author", "كامل كيلاني"); - newProperties1.put("language", "Arabic"); - newProperties1.put("Medium", "النص"); - newProperties1.put("uploadDate", "2015-12-02T05:00:00.000Z"); - newProperties1.put("averageRating", ""); - newProperties1.put("openWith", "PDF.js"); - newdocument1.putProperties(newProperties1); - - Document newdocument2 = shadowresources_demo.getDocument("3a162fea1d56beb7a4441a4a8018e5b0"); - Map newProperties2 = new HashMap(); - newProperties2.put("author", "Clea McNeely, et al."); - newProperties2.put("language", "English"); - newProperties2.put("Medium", "Text"); - newProperties2.put("uploadDate", "2014-08-14T04:00:00.000Z"); - newProperties2.put("averageRating", ""); - newProperties2.put("openWith", "PDF.js"); - newdocument2.putProperties(newProperties2); - - Document newdocument3 = shadowresources_demo.getDocument("61461c3cf80877891652a143c3c77fed"); - Map newProperties3 = new HashMap(); - newProperties3.put("title", "Education in Emergency"); - newProperties3.put("author", ""); - newProperties3.put("language", "English"); - newProperties3.put("Medium", "Text"); - newProperties3.put("uploadDate", "2014-08-27T04:00:00.000Z"); - newProperties3.put("averageRating", ""); - newProperties3.put("openWith", "PDF.js"); - newdocument3.putProperties(newProperties3); - - Document newdocument4 = shadowresources_demo.getDocument("a28c81eac20e23529a5eda8e850eaeb3"); - Map newProperties4 = new HashMap(); - newProperties4.put("title", "Emergency Preparedness Plans"); - newProperties4.put("author", ""); - newProperties4.put("language", "English"); - newProperties4.put("Medium", "Text"); - newProperties4.put("uploadDate", "2015-05-01T04:00:00.000Z"); - newProperties4.put("averageRating", ""); - newProperties4.put("openWith", "PDF.js"); - newdocument4.putProperties(newProperties4); - - Document newdocument5 = shadowresources_demo.getDocument("68ec3d6c83989920cb75df8e5d01c449"); - Map newProperties5 = new HashMap(); - newProperties5.put("title", "Healthy Child Uganda VHT Training Manual: Paring a Community Emergency Transport Plan (CETP)"); - newProperties5.put("author", ""); - newProperties5.put("language", "English"); - newProperties5.put("Medium", "Text"); - newProperties5.put("uploadDate", "2015-05-01T04:00:00.000Z"); - newProperties5.put("averageRating", ""); - newProperties5.put("openWith", "PDF.js"); - newdocument5.putProperties(newProperties5); - - /* Document newdocument6 = shadowresources_demo.getDocument("68ec3d6c83989920cb75df8e5d01c449"); - Map newProperties6 = new HashMap(); - newProperties6.put("title", "Healthy Child Uganda VHT Training Manual: Paring a Community Emergency Transport Plan (CETP)"); - newProperties6.put("author", ""); - newProperties6.put("language", "English"); - newProperties6.put("Medium", "Text"); - newProperties6.put("uploadDate", "2015-05-01T04:00:00.000Z"); - newProperties6.put("averageRating", ""); - newdocument6.putProperties(newProperties6);*/ - - Document newdocument7 = shadowresources_demo.getDocument("86ba8cb7d819aa7068748640fb347ab1"); - Map newProperties7 = new HashMap(); - newProperties7.put("title", "Children in War: The role of Child to Child Activities in the Therapy and Care of Displaced Unaccompanied Children"); - newProperties7.put("author", ""); - newProperties7.put("language", "English"); - newProperties7.put("Medium", "Text"); - newProperties7.put("uploadDate", "2014-05-19T04:00:00.000Z"); - newProperties7.put("averageRating", ""); - newProperties7.put("openWith", "PDF.js"); - newdocument7.putProperties(newProperties7); - - Document newdocument8 = shadowresources_demo.getDocument("326b61c2ae2be1b31cb65891cbbf1536"); - Map newProperties8 = new HashMap(); - newProperties8.put("title", "Because I Am a Girl"); - newProperties8.put("author", ""); - newProperties8.put("language", "English"); - newProperties8.put("Medium", "Text"); - newProperties8.put("uploadDate", "2014-08-27T04:00:00.000Z"); - newProperties8.put("averageRating", ""); - newProperties8.put("openWith", "PDF.js"); - newdocument8.putProperties(newProperties8); - - Document newdocument9 = shadowresources_demo.getDocument("78c923afd67a7dc59b3f68b03b63bb17"); - Map newProperties9 = new HashMap(); - newProperties9.put("title", "Because I Am a Girl: A Year of Action and Innovation / Parce que je suis une fille: Une annee d’action et d’innovation (French)"); - newProperties9.put("author", ""); - newProperties9.put("language", "English"); - newProperties9.put("Medium", "Text"); - newProperties9.put("uploadDate", "2014-08-20T04:00:00.000Z"); - newProperties9.put("averageRating", ""); - newProperties9.put("openWith", "PDF.js"); - newdocument9.putProperties(newProperties9); - - Document newdocument10 = shadowresources_demo.getDocument("242a13d826420075a3ece5f0ea31b1fb"); - Map newProperties10 = new HashMap(); - newProperties10.put("title", "Gender Awareness Workshop (en)"); - newProperties10.put("author", ""); - newProperties10.put("language", "English"); - newProperties10.put("Medium", "Text"); - newProperties10.put("uploadDate", "2014-08-20T04:00:00.000Z"); - newProperties10.put("averageRating", ""); - newProperties10.put("openWith", "PDF.js"); - newdocument10.putProperties(newProperties10); - - - } catch (Exception e) { - e.printStackTrace(); - } - } - - - public void createMeetups() { - /*AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - Database resourceRating; - int doc_rating; - int doc_timesRated; - ArrayList commentList = new ArrayList(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - resourceRating = manager.getDatabase("resourcerating"); - Document retrievedDocument = resourceRating.getExistingDocument(resourceId); - if (retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if (properties.containsKey("sum")) { - doc_rating = (int) properties.get("sum"); - doc_timesRated = (int) properties.get("timesRated"); - commentList = (ArrayList) properties.get("comments"); - commentList.add(comment); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("sum", (doc_rating + rate)); - newProperties.put("timesRated", doc_timesRated + 1); - newProperties.put("comments", commentList); - retrievedDocument.putProperties(newProperties); - updateActivityRatingResources(rate, resourceId); - Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show(); - } - } else { - Document newdocument = resourceRating.getDocument(resourceId); - Map newProperties = new HashMap(); - newProperties.put("sum", rate); - newProperties.put("timesRated", 1); - commentList.add(comment); - newProperties.put("comments", commentList); - newdocument.putProperties(newProperties); - } - } catch (Exception err) { - Log.e("MyCouch", "ERR : " + err.getMessage()); - }*/ - } - - public void createUsermeetups() { - } - - public void createAssignments() { - - } - - public void createAssignmentpaper() { - - } - - public void createCourseanswer() { - - } - - public void createCoursequestion() { - - } - - public void createCourses() { - Manager manager = null; - Database course; - ArrayList courseLeaderList = new ArrayList(); - ArrayList DayList = new ArrayList(); - ArrayList membersList = new ArrayList(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - course = manager.getDatabase("courses"); - Document newdocument = course.getDocument("e3d7ca503eef922213e36bf3d600eb0c"); - Map newProperties = new HashMap(); - newProperties.put("kind", "Course"); - newProperties.put("languageOfInstruction", "English"); - newProperties.put("CourseTitle", "Kangaroo Mother Care"); - newProperties.put("memberLimit", ""); - courseLeaderList.add("e3d7ca503eef922213e36bf3d60004b7"); - newProperties.put("courseLeader", courseLeaderList); - newProperties.put("description", "This course covers basics on Kangaroo Mother Care"); - newProperties.put("method", ""); - newProperties.put("gradeLevel", "Post-Graduate"); - newProperties.put("subjectLevel", "Beginner"); - newProperties.put("startDate", "08/01/2017"); - newProperties.put("endDate", "12/31/2017"); - newProperties.put("frequency", "Daily"); - newProperties.put("Day", DayList); - newProperties.put("startTime", ""); - newProperties.put("endTime", ""); - newProperties.put("location", ""); - newProperties.put("backgroundColor", ""); - newProperties.put("foregroundColor", ""); - membersList.add("e3d7ca503eef922213e36bf3d60080c2"); - membersList.add("e3d7ca503eef922213e36bf3d60004b7"); - newProperties.put("members", membersList); - newProperties.put("name", "Kangaroo Mother Care"); - newdocument.putProperties(newProperties); - } catch (Exception e) { - e.printStackTrace(); - } - - /* { - "_id": "e3d7ca503eef922213e36bf3d600eb0c", - "_rev": "1-6c382f914e468b760d7956202fc5d017", - "kind": "Course", - "languageOfInstruction": "English", - "CourseTitle": "Kangaroo Mother Care", - "memberLimit": "", - "courseLeader": [ - "e3d7ca503eef922213e36bf3d60004b7" - ], - "description": "This course covers basics on Kangaroo Mother Care", - "method": "", - "gradeLevel": "Post-Graduate", - "subjectLevel": "Beginner", - "startDate": "08/01/2017", - "endDate": "12/31/2017", - "frequency": "Daily", - "Day": [ - ], - "startTime": "", - "endTime": "", - "location": "", - "backgroundColor": "", - "foregroundColor": "", - "members": [ - "e3d7ca503eef922213e36bf3d60080c2", - "e3d7ca503eef922213e36bf3d60004b7" - ], - "name": "Kangaroo Mother Care" - }*/ - - } - - public void createCourseschedule() { - - } - - public void createCoursestep() { - Manager manager = null; - Database coursestep; - ArrayList resourceIdList = new ArrayList(); - ArrayList resourceTitlesList = new ArrayList(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - coursestep = manager.getDatabase("coursestep"); - - Document newdocument = coursestep.getDocument("e3d7ca503eef922213e36bf3d6010d84"); - Map newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "Introduction"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "This is Ekua. She was born a few weeks early and is very small. What can you do to improve Ekua’s chances?"); - newProperties.put("stepGoals", ""); - newProperties.put("step", "1"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument.putProperties(newProperties); - - Document newdocument2 = coursestep.getDocument("e3d7ca503eef922213e36bf3d6011162"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "Objectives"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "In this learning object you will practice identifying babies that need kangaroo mother care and describe components of kangaroo mother care.\\n\\nThis lesson supports Physiology and Management of the High Risk Neonate in the Nursing Midwifery course."); - newProperties.put("stepGoals", ""); - newProperties.put("step", "2"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument2.putProperties(newProperties); - - Document newdocument3 = coursestep.getDocument("e3d7ca503eef922213e36bf3d601124b"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "What is KMC?"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "Watch this video on kangaroo mother care from World Health Organization. The attached Kangaroo Mother Care job aid provides a summary of care."); - newProperties.put("stepGoals", ""); - newProperties.put("step", "3"); - resourceIdList.add("58a9ffe3ead5d4f48866867f02002dc6"); - newProperties.put("resourceId", resourceIdList); - resourceTitlesList.add("KMC_WHO_What_is_KMC"); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument3.putProperties(newProperties); - - Document newdocument4 = coursestep.getDocument("e3d7ca503eef922213e36bf3d6011437"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "WHO KMC Job Aid"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "Review the Kangaroo Mother Care job aid for a summary of care."); - newProperties.put("stepGoals", ""); - newProperties.put("step", "4"); - resourceIdList.add("58a9ffe3ead5d4f48866867f0200385d"); - newProperties.put("resourceId", resourceIdList); - resourceTitlesList.add("Kangaroo Mother Care job"); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument4.putProperties(newProperties); - - Document newdocument5 = coursestep.getDocument("e3d7ca503eef922213e36bf3d601232b"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "Low Birth Weight"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "Low birth weight (LBW) is defined as birth weight of less than 2500 grams. There are three types of LBW babies: \\nPreterm: born before 37 completed weeks\\nVery preterm: born before 32 completed weeks\\nSmall for Gestational Age (SGA) or Small For Date (SFD): birth weight lower than expected for gestational age (may be term or preterm).\\nLBW infants may be born at any term."); - newProperties.put("stepGoals", ""); - newProperties.put("step", "5"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument5.putProperties(newProperties); - - Document newdocument6 = coursestep.getDocument("e3d7ca503eef922213e36bf3d6012a16"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "Review KMC Main Components"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "Remember the main components of KMC from the video and job aid? What are the three main components?"); - newProperties.put("stepGoals", ""); - newProperties.put("step", "6"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument6.putProperties(newProperties); - - Document newdocument7 = coursestep.getDocument("e3d7ca503eef922213e36bf3d60137d8"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "What did you say were the main components?"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "What did you say were the main components? Your answer should have included the following: \\nskin-to-skin positioning of a baby on the mother’s chest;\\nadequate nutrition through breastfeeding;\\nambulatory care as a result of earlier discharge from hospital; and support for the mother and her family in caring for the baby."); - newProperties.put("stepGoals", ""); - newProperties.put("step", "7"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument7.putProperties(newProperties); - - Document newdocument8 = coursestep.getDocument("e3d7ca503eef922213e36bf3d6013ed5"); - newProperties = new HashMap(); - newProperties.put("kind", "Course Step"); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newProperties.put("totalMarks", "0"); - newProperties.put("stepType", "Objective"); - newProperties.put("title", "Time to Practice!"); - newProperties.put("stepMethod", ""); - newProperties.put("description", "Practice assessing a baby for gestational age and size in the simulation lab, use this checklist.\\n\\nNEED TO GET NEWBORN ASSESSMENT CHECKLIST FROM NMC"); - newProperties.put("stepGoals", ""); - newProperties.put("step", "8"); - newProperties.put("resourceId", resourceIdList); - newProperties.put("resourceTitles", resourceTitlesList); - newProperties.put("questionslist", null); - newProperties.put("passingPercentage", "10"); - newdocument8.putProperties(newProperties); - - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public void createMembercourseprogress() { - Manager manager = null; - Database membercourseprogress; - ArrayList stepsIdsList = new ArrayList(); - ArrayList stepsResultList = new ArrayList(); - ArrayList stepsStatusList = new ArrayList(); - ArrayList pqAttemptsList = new ArrayList(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - membercourseprogress = manager.getDatabase("membercourseprogress"); - - Document newdocument = membercourseprogress.getDocument("e3d7ca503eef922213e36bf3d600faf6"); - Map newProperties = new HashMap(); - newProperties.put("kind", "course-member-result"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6010d84"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6011162"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d601124b"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6011437"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d601232b"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6012a16"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d60137d8"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6013ed5"); - newProperties.put("stepsIds", stepsIdsList); - newProperties.put("memberId", "e3d7ca503eef922213e36bf3d60004b7"); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - newProperties.put("stepsResult", stepsResultList); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - newProperties.put("stepsStatus", stepsStatusList); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - newProperties.put("pqAttempts", pqAttemptsList); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newdocument.putProperties(newProperties); - - - /* { - "_id": "e3d7ca503eef922213e36bf3d600faf6", - "_rev": "9-496a84c07fb7c13678247490c80ba1b7", - "kind": "course-member-result", - "stepsIds": [ - "e3d7ca503eef922213e36bf3d6010d84", - "e3d7ca503eef922213e36bf3d6011162", - "e3d7ca503eef922213e36bf3d601124b", - "e3d7ca503eef922213e36bf3d6011437", - "e3d7ca503eef922213e36bf3d601232b", - "e3d7ca503eef922213e36bf3d6012a16", - "e3d7ca503eef922213e36bf3d60137d8", - "e3d7ca503eef922213e36bf3d6013ed5" - ], - "memberId": "e3d7ca503eef922213e36bf3d60004b7", - "stepsResult": [ - "", - "", - "", - "", - "", - "", - "", - "" - ], - "stepsStatus": [ - "0", - "0", - "0", - "0", - "0", - "0", - "0", - "0" - ], - "pqAttempts": [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "courseId": "e3d7ca503eef922213e36bf3d600eb0c" - } - - //// - - { - "_id": "e3d7ca503eef922213e36bf3d60101ef", - "_rev": "9-5858aa5a132b086621836cde7e273a75", - "kind": "course-member-result", - "stepsIds": [ - "e3d7ca503eef922213e36bf3d6010d84", - "e3d7ca503eef922213e36bf3d6011162", - "e3d7ca503eef922213e36bf3d601124b", - "e3d7ca503eef922213e36bf3d6011437", - "e3d7ca503eef922213e36bf3d601232b", - "e3d7ca503eef922213e36bf3d6012a16", - "e3d7ca503eef922213e36bf3d60137d8", - "e3d7ca503eef922213e36bf3d6013ed5" - ], - "memberId": "e3d7ca503eef922213e36bf3d60080c2", - "stepsResult": [ - "", - "", - "", - "", - "", - "", - "", - "" - ], - "stepsStatus": [ - "0", - "0", - "0", - "0", - "0", - "0", - "0", - "0" - ], - "pqAttempts": [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ], - "courseId": "e3d7ca503eef922213e36bf3d600eb0c" - } - */ - - Document newdocument2 = membercourseprogress.getDocument("e3d7ca503eef922213e36bf3d60101ef"); - newProperties = new HashMap(); - newProperties.put("kind", "course-member-result"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6010d84"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6011162"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d601124b"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6011437"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d601232b"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6012a16"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d60137d8"); - stepsIdsList.add("e3d7ca503eef922213e36bf3d6013ed5"); - newProperties.put("stepsIds", stepsIdsList); - newProperties.put("memberId", "e3d7ca503eef922213e36bf3d60080c2"); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - stepsResultList.add(""); - newProperties.put("stepsResult", stepsResultList); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - stepsStatusList.add(""); - newProperties.put("stepsStatus", stepsStatusList); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - pqAttemptsList.add(""); - newProperties.put("pqAttempts", pqAttemptsList); - newProperties.put("courseId", "e3d7ca503eef922213e36bf3d600eb0c"); - newdocument2.putProperties(newProperties); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - public void createCalendar() { - - } - - public void createGroups() { - - } - - public void createInvitations() { - - } - - public void createRequests() { - - } - - public void createLanguages() { - - } - -} - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/FullscreenActivity.java b/app/src/main/java/pbell/offline/ole/org/pbell/FullscreenActivity.java deleted file mode 100644 index f1332c3..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/FullscreenActivity.java +++ /dev/null @@ -1,2931 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.annotation.SuppressLint; -import android.app.Dialog; -import android.app.DownloadManager; -import android.app.ProgressDialog; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.graphics.Color; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.GradientDrawable; -import android.media.MediaPlayer; -import android.net.Uri; -import android.net.wifi.WifiManager; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.support.v4.content.IntentCompat; -import android.support.v7.app.ActionBar; -import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.Display; -import android.view.View; -import android.view.Window; -import android.view.WindowManager; -import android.view.animation.Animation; -import android.view.animation.LinearInterpolator; -import android.view.animation.TranslateAnimation; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.RatingBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.couchbase.lite.Attachment; -import com.couchbase.lite.CouchbaseLiteException; -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryOptions; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.Revision; -import com.couchbase.lite.android.AndroidContext; -import com.couchbase.lite.replicator.Replication; -import com.github.kittinunf.fuel.Fuel; -import com.github.kittinunf.fuel.core.FuelError; -import com.github.kittinunf.fuel.core.Request; -import com.github.kittinunf.fuel.core.Response; -import com.google.gson.JsonObject; - -import org.json.JSONException; -import org.json.JSONObject; -import org.lightcouch.CouchDbClientAndroid; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URL; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; - -import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; - -@SuppressWarnings("ALL") -public class FullscreenActivity extends AppCompatActivity { - - private View mContentView; - final Context context = this; - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - private static final String TAG = "MYAPP"; - String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, - sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname, - sys_usergender, sys_uservisits, sys_servername, sys_serverversion = ""; - Boolean sys_singlefilestreamdownload, sys_multiplefilestreamdownload; - int sys_uservisits_Int = 0; - Object[] sys_membersWithResource; - boolean userShelfSynced = true; - boolean synchronizing = true; - JSONObject jsonData; - Database dbResources; - int syncCnt, resourceNo,courseNo, allresDownload, allhtmlDownload = 0; - AndroidContext androidContext; - Replication pull; - Manager manager; - boolean status_SyncOneByOneResource = false; - private ProgressDialog mDialog; - String indexFilePath; - String openedResourceId, openedResourceTitle = ""; - boolean openedResource = false; - boolean openFromDiskDirectly = false; - boolean singleFiledownload = false; - boolean openFromOnlineServer = false; - boolean clicked_rs_status; - String clicked_rs_title, clicked_rs_ID; - String onlinecouchresource; - - CouchViews chViews = new CouchViews(); - String resourceIdList[],resourceTitleList[],courseIdList[],courseTitleList[]; - int rsLstCnt,csLstCnt = 0; - Button[] libraryButtons,courseButtons; - Dialog dialog2; - String OneByOneResID = ""; - int resButtonId; - boolean userInfoDisplayed = false; - - ArrayList lst; - - ImageView[] imageView; - static Uri videoURl; - static Intent intent; - MediaPlayer sd_Slidin; - Database database; - Replication repl; - DownloadManager downloadManager; - Boolean initialActivityLoad = false; - - - private List resourceList = new ArrayList(); - private List resIDArrayList = new ArrayList(); - private List courseList = new ArrayList(); - private List courseIDArrayList = new ArrayList(); - private ListView listView; - private CustomListAdapter adapter; - Boolean calbackStatus, syncALLInOneStarted = false; - Button dialogBtnDownoadAll, dialogBtnDownoadFile, dialogBtnOpenFileOnline; - private long enqueue; - int resourceCntr, attachmentLength; - List htmlResourceList = new ArrayList(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_fullscreen); - mContentView = findViewById(R.id.fullscreen_content); - ActionBar actionBar = getSupportActionBar(); - actionBar.hide(); - androidContext = new AndroidContext(this); - //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); - //StrictMode.setThreadPolicy(policy); - - initialActivityLoad = true; - BroadcastReceiver receiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { - long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); - DownloadManager.Query query = new DownloadManager.Query(); - query.setFilterById(enqueue); - Cursor c = downloadManager.query(query); - if (c.moveToFirst()) { - int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); - if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { - openFromDiskDirectly = true; - if (!singleFiledownload) { - libraryButtons[allresDownload].setTextColor(getResources().getColor(R.color.ole_white)); - if (allresDownload < libraryButtons.length) { - allresDownload++; - if (resourceTitleList[allresDownload] != null) { - new downloadAllResourceToDisk().execute(); - } else { - if (allhtmlDownload < htmlResourceList.size()) { - new SyncAllHTMLResource().execute(); - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } else { - if (allhtmlDownload < htmlResourceList.size()) { - new SyncSingleHTMLResource().execute(); - openFromDiskDirectly = true; - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - - } - } else { - libraryButtons[resButtonId].setTextColor(getResources().getColor(R.color.ole_white)); - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } else if (DownloadManager.STATUS_FAILED == c.getInt(columnIndex)) { - alertDialogOkay("Download Failed" + resourceTitleList[allresDownload]); - if (!singleFiledownload) { - if (allresDownload < libraryButtons.length) { - allresDownload++; - if (resourceTitleList[allresDownload] != null) { - new downloadAllResourceToDisk().execute(); - openFromDiskDirectly = true; - } else { - if (allhtmlDownload < htmlResourceList.size()) { - new SyncAllHTMLResource().execute(); - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } - } - }; - registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); - /////////////////////////////////// - TextView txtcurDate = (TextView) findViewById(R.id.lblDate); - txtcurDate.setText(curdate()); - ///////////////////////////////// - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username", ""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl", ""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate", ""); - sys_password = settings.getString("pf_password", ""); - sys_usercouchId = settings.getString("pf_usercouchId", ""); - sys_userfirstname = settings.getString("pf_userfirstname", ""); - sys_userlastname = settings.getString("pf_userlastname", ""); - sys_usergender = settings.getString("pf_usergender", ""); - sys_uservisits = settings.getString("pf_uservisits", ""); - sys_uservisits_Int = settings.getInt("pf_uservisits_Int", 0); - sys_servername = settings.getString("pf_server_name", " ------------- "); - sys_serverversion = settings.getString("pf_server_version", " ------------"); - ///////////////////////// - resourceList.clear(); - resIDArrayList.clear(); - LoadShelfResourceList(); - LoadCourseList(); - - ///Update user info - updateUI(); - - /// Todo :- Sync user usage data back to server - - if (!userShelfSynced) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("Materials on your shelf are NOT yet synchronized unto this device. " + - "You can only view title of items on your shelf BUT you can not launch or read them." + - "To access your materials on this device, please sync device with server.") - .setCancelable(false) - .setPositiveButton("Okay", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - }); - - AlertDialog closeDialogue = builder.create(); - closeDialogue.show(); - } - - sd_Slidin = MediaPlayer.create(this, R.raw.wave); - - Button btnCourses = (Button) findViewById(R.id.btnCourses); - btnCourses.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final Fuel ful = new Fuel(); - @SuppressLint("WifiManagerLeak") final WifiManager wifiManager = (WifiManager) FullscreenActivity.this.getSystemService(Context.WIFI_SERVICE); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening Courses please wait..."); - mDialog.setCancelable(true); - mDialog.show(); - if (wifiManager.isWifiEnabled()) { - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } else { - openServerPage("/apps/_design/bell/MyApp/index.html#courses"); - } - } catch (Exception e) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on your Wi-Fi and connect to the server to use this function"); - Log.e(TAG, "Device couldn't reach server. Error"); - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on your Wi-Fi and connect to the server to use this function"); - Log.e(TAG, "Device couldn't reach server. Check and try again"); - Log.e(TAG, " " + fuelError); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } - } - }); - - Button btnMeetups = (Button) findViewById(R.id.btnMeetups); - btnMeetups.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final Fuel ful = new Fuel(); - @SuppressLint("WifiManagerLeak") final WifiManager wifiManager = (WifiManager) FullscreenActivity.this.getSystemService(Context.WIFI_SERVICE); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening Meetups please wait..."); - mDialog.setCancelable(true); - mDialog.show(); - if (wifiManager.isWifiEnabled()) { - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } else { - openServerPage("/apps/_design/bell/MyApp/index.html#meetups"); - } - } catch (Exception e) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on your Wi-Fi and connect to the server to use this function"); - Log.e(TAG, "Device couldn't reach server. Error"); - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on your Wi-Fi and connect to the server to use this function"); - Log.e(TAG, "Device couldn't reach server. Check and try again"); - Log.e(TAG, " " + fuelError); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } - } - }); - - Button btnLogout = (Button) findViewById(R.id.btnLogout); - btnLogout.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - Button btnLibrary = (Button) findViewById(R.id.btnLibrary); - btnLibrary.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final Fuel ful = new Fuel(); - @SuppressLint("WifiManagerLeak") final WifiManager wifiManager = (WifiManager) FullscreenActivity.this.getSystemService(Context.WIFI_SERVICE); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening library please wait..."); - mDialog.setCancelable(true); - mDialog.show(); - if (wifiManager.isWifiEnabled()) { - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - mDialog.dismiss(); - populateLibraryDialogList(); - } else { - openServerPage("/apps/_design/bell/MyApp/index.html#resources"); - } - } catch (Exception e) { - mDialog.dismiss(); - populateLibraryDialogList(); - Log.e(TAG, "Device couldn't reach server. Error"); - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - mDialog.dismiss(); - populateLibraryDialogList(); - Log.e(TAG, "Device couldn't reach server. Check and try again"); - Log.e(TAG, " " + fuelError); - } - }); - } else { - mDialog.dismiss(); - populateLibraryDialogList(); - } - } - }); - - Button btnUpdate = (Button) findViewById(R.id.btnSetting); - btnUpdate.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ///openSettingDialogList(); - new checkServerConnection().execute(""); - } - }); - - TextView lblMyLibrary = (TextView) findViewById(R.id.lblMyLibrary); - lblMyLibrary.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - populateLibraryDialogList(); - } - }); - - TextView lblmycoursesProgress = (TextView) findViewById(R.id.lblmycourses); - lblmycoursesProgress.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - final Fuel ful = new Fuel(); - @SuppressLint("WifiManagerLeak") final WifiManager wifiManager = (WifiManager) FullscreenActivity.this.getSystemService(Context.WIFI_SERVICE); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening Course Progress please wait..."); - mDialog.setCancelable(true); - mDialog.show(); - if (wifiManager.isWifiEnabled()) { - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } else { - openServerPage("/apps/_design/bell/MyApp/index.html#courses/barchart"); - } - } catch (Exception e) { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - Log.e(TAG, "Device couldn't reach server. Error"); - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - mDialog.dismiss(); - populateLibraryDialogList(); - Log.e(TAG, "Device couldn't reach server. Check and try again"); - Log.e(TAG, " " + fuelError); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("You need to turn on Wi-Fi and connect to server to use this function"); - } - } - }); - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - animateLayoutBars(); - } - - @Override - public void onResume() { - super.onResume(); - checkResourceOpened(); - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - - } - - public void populateLibraryDialogList() { - AlertDialog.Builder dialogBMyLibrary = new AlertDialog.Builder(this); - // custom dialog - dialogBMyLibrary.setView(R.layout.dialog_my_library); - dialogBMyLibrary.setCancelable(true); - final Dialog dialogMyLibrary = dialogBMyLibrary.create(); - dialogMyLibrary.show(); - WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - Display display = wm.getDefaultDisplay(); - DisplayMetrics metrics = new DisplayMetrics(); - display.getMetrics(metrics); - Double width = metrics.widthPixels * .8; - Double height = metrics.heightPixels * .8; - Window win = dialogMyLibrary.getWindow(); - win.setLayout(width.intValue(), height.intValue()); - dialogMyLibrary.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); - listView = (ListView) dialogMyLibrary.findViewById(R.id.list); - adapter = new CustomListAdapter(this, resourceList); - try { - adapter = new CustomListAdapter(this, resourceList); - listView.setAdapter(adapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(AdapterView adapter, View v, int position, long id) { - if (libraryButtons[position].getCurrentTextColor() == getResources().getColor(R.color.ole_yellow)) { - MaterialClickDialog(false, resourceTitleList[position], resourceIdList[position], position); - dialogMyLibrary.dismiss(); - } else { - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening please " + resourceTitleList[position] + "wait..."); - mDialog.setCancelable(true); - mDialog.show(); - openedResourceId = resourceIdList[position]; - openedResourceTitle = resourceTitleList[position]; - openedResource = true; - openDoc(resourceIdList[position]); - Log.e("MyCouch", "Clicked to open resource Id " + resourceIdList[position]); - } - } - }); - } catch (Exception err) { - Log.e("adapter", " " + err); - } - } - - public void openSettingDialogList() { - restorePref(); - AlertDialog.Builder dialogBSettings = new AlertDialog.Builder(this); - // custom dialog - dialogBSettings.setView(R.layout.dialog_my_settings); - dialogBSettings.setCancelable(true); - final Dialog dialogSetting = dialogBSettings.create(); - dialogSetting.show(); - WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - Display display = wm.getDefaultDisplay(); - DisplayMetrics metrics = new DisplayMetrics(); - display.getMetrics(metrics); - Double width = metrics.widthPixels * .8; - Double height = metrics.heightPixels * .8; - Window win = dialogSetting.getWindow(); - win.setLayout(width.intValue(), height.intValue()); - - Button btnCheck4Updates = (Button) dialogSetting.findViewById(R.id.btnCheck4Updates); - btnCheck4Updates.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - new checkServerConnection().execute(""); - } - }); - } - - public String curdate() { - Calendar cal = Calendar.getInstance(); - Date d = new Date(); - - SimpleDateFormat s_df = new SimpleDateFormat("EEEE"); - String dayOfTheWeek = s_df.format(d); - SimpleDateFormat date_df = new SimpleDateFormat("d"); - String dayNumber = date_df.format(d); - SimpleDateFormat month_df = new SimpleDateFormat("MMMM"); - String month_name = month_df.format(cal.getTime()); - SimpleDateFormat year_df = new SimpleDateFormat("yyyy"); - String year = year_df.format(d); - String displayedDate = dayOfTheWeek + " | " + dayNumber + " " + month_name + " " + year; - return displayedDate; - } - - public void restorePref() { - // Restore preferences - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username", ""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl", ""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate", ""); - sys_password = settings.getString("pf_password", ""); - sys_usercouchId = settings.getString("pf_usercouchId", ""); - sys_userfirstname = settings.getString("pf_userfirstname", ""); - sys_userlastname = settings.getString("pf_userlastname", ""); - sys_usergender = settings.getString("pf_usergender", ""); - sys_uservisits = settings.getString("pf_uservisits", ""); - ; - sys_uservisits_Int = settings.getInt("pf_uservisits_Int", 0); - sys_singlefilestreamdownload = settings.getBoolean("pf_singlefilestreamdownload", true); - sys_multiplefilestreamdownload = settings.getBoolean("multiplefilestreamdownload", true); - sys_servername = settings.getString("pf_server_name", " "); - sys_serverversion = settings.getString("pf_server_version", " "); - Set mwr = settings.getStringSet("membersWithResource", null); - try { - sys_membersWithResource = mwr.toArray(); - Log.e("MYAPP", " membersWithResource = " + sys_membersWithResource.length); - - } catch (Exception err) { - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - } - - public void LoadShelfResourceList() { - String memberId = sys_usercouchId; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("shelf"); - Database resource_Db = manager.getDatabase("resources"); - Query orderedQuery = chViews.ReadShelfByIdView(db).createQuery(); - orderedQuery.setDescending(true); - QueryEnumerator results = orderedQuery.run(); - resourceIdList = new String[results.getCount()]; - resourceTitleList = new String[results.getCount()]; - rsLstCnt = 0; - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - Map resource_properties = null; - if (memberId.equals((String) properties.get("memberId"))) { - String myresTitile = ((String) properties.get("resourceTitle")); - String myresId = ((String) properties.get("resourceId")); - String myresType, myresDec, myresExt = ""; - resourceTitleList[rsLstCnt] = myresTitile; - resourceIdList[rsLstCnt] = myresId; - resIDArrayList.add(myresId); - Log.e("tag", "MEMBER ID " + (String) properties.get("resourceTitle")); - try { - Document resource_doc = resource_Db.getExistingDocument((String) properties.get("resourceId")); - Log.e("tag", "RES ID " + (String) properties.get("resourceId")); - try { - resource_properties = resource_doc.getProperties(); - } catch (Exception errs) { - Log.e("tag", "OBJECT ERROR " + errs.toString()); - } - //myresTitile = (String) resource_properties.get("title")+""; - //myresId = (String) properties.get("resourceId")+""; - myresDec = (String) resource_properties.get("author") + ""; - myresType = (String) resource_properties.get("averageRating") + ""; - myresExt = (String) resource_properties.get("openWith") + ""; - rsLstCnt++; - } catch (Exception err) { - Log.e("tag", "ERROR " + err.getMessage()); - //myresTitile = "Unknown resource .. "; - //myresId = ""; - myresDec = ""; - myresType = ""; - rsLstCnt++; - } - Resource resource = new Resource(); - resource.setTitle(myresTitile); - resource.setThumbnailUrl(getIconType(myresExt)); - resource.setDescription(myresDec); - resource.setRating(myresType); - - resource.setGenre(null); - // adding resource to resources array - resourceList.add(resource); - resourceNo++; - } - } - - LinearLayout row2 = (LinearLayout) findViewById(R.id.layholder_library); - libraryButtons = new Button[rsLstCnt]; - for (int ButtonCnt = 0; ButtonCnt < rsLstCnt; ButtonCnt++) { - libraryButtons[ButtonCnt] = new Button(this); - libraryButtons[ButtonCnt].setText(resourceTitleList[ButtonCnt]); - libraryButtons[ButtonCnt].setId(ButtonCnt); - libraryButtons[ButtonCnt].setBackgroundResource(R.drawable.rounded_corners_black_blue); - libraryButtons[ButtonCnt].setTextColor(getResources().getColor(R.color.white)); - libraryButtons[ButtonCnt].setAllCaps(false); - libraryButtons[ButtonCnt].setPadding(10, 5, 10, 5); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - libraryButtons[ButtonCnt].setTextAlignment(View.TEXT_ALIGNMENT_CENTER); - } - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(170, MATCH_PARENT); - layoutParams.setMargins(1, 0, 1, 0); // left, top, right, bottom - GradientDrawable drawable = new GradientDrawable(); - drawable.setShape(GradientDrawable.RECTANGLE); - drawable.setStroke(2, Color.WHITE); - drawable.setCornerRadius(2); - drawable.setColor(getResources().getColor(R.color.ole_black_blue)); - libraryButtons[ButtonCnt].setBackgroundDrawable(drawable); - libraryButtons[ButtonCnt].setLayoutParams(layoutParams); - row2.addView(libraryButtons[ButtonCnt]); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Document resource_doc = resource_Db.getExistingDocument((String) resourceIdList[ButtonCnt]); - Map resource_properties = resource_doc.getProperties(); - Log.e("tag", "RES ID " + (String) resource_properties.get("resourceId")); - libraryButtons[ButtonCnt].setTextColor(getResources().getColor(R.color.ole_white)); - } catch (Exception errs) { - libraryButtons[ButtonCnt].setTextColor(getResources().getColor(R.color.ole_yellow)); - Log.e("tag", "OBJECT ERROR " + errs.toString()); - } - - libraryButtons[ButtonCnt].setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (libraryButtons[view.getId()].getCurrentTextColor() == getResources().getColor(R.color.ole_yellow)) { - MaterialClickDialog(false, resourceTitleList[view.getId()], resourceIdList[view.getId()], view.getId()); - } else { - mDialog = new ProgressDialog(context); - mDialog.setMessage("Opening please " + resourceTitleList[view.getId()] + " wait..."); - mDialog.setCancelable(true); - mDialog.show(); - openedResourceId = resourceIdList[view.getId()]; - openedResourceTitle = resourceTitleList[view.getId()]; - openedResource = true; - openDoc(resourceIdList[view.getId()]); - Log.e("MyCouch", "Clicked to open " + resourceIdList[view.getId()]); - - } - - } - - }); - //////////// Save list in Preferences - } - db.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void LoadCourseList() { - String memberId = sys_usercouchId; - try { - //maximus - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("courses"); - ///Database resource_Db = manager.getDatabase("resources"); - Query orderedQuery = chViews.ReadCourses(db).createQuery(); - orderedQuery.setDescending(true); - QueryEnumerator results = orderedQuery.run(); - courseIdList = new String[results.getCount()]; - courseTitleList = new String[results.getCount()]; - csLstCnt = 0; - String mycourseId=""; - String mycourseTitile; - String mycourseForgndColor="#000000"; - String mycourseBackgndColor="#FFFFFF"; - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - ArrayList courseMembers = (ArrayList) properties.get("members"); - for (int cnt = 0; cnt < courseMembers.size(); cnt++) { - if (memberId.equals(courseMembers.get(cnt).toString())) { - mycourseTitile = ((String) properties.get("CourseTitle")); - mycourseId = ((String) properties.get("_id")); - mycourseForgndColor = ((String) properties.get("foregroundColor")); - mycourseBackgndColor = ((String) properties.get("backgroundColor")); - courseIdList[csLstCnt] = mycourseId; - courseTitleList[csLstCnt] = mycourseTitile; - courseIDArrayList.add(mycourseId); - } - } - - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database coursestep_Db = manager.getExistingDatabase("coursestep"); - orderedQuery = chViews.ReadCourseSteps(coursestep_Db).createQuery(); - orderedQuery.setDescending(true); - results = orderedQuery.run(); - for (Iterator item = results; item.hasNext(); ) { - row = item.next(); - docId = (String) row.getValue(); - doc = coursestep_Db.getExistingDocument(docId); - Map coursestep_properties = doc.getProperties(); - if (mycourseId.equals((String) coursestep_properties.get("members"))) { - ArrayList course_step_resourceId = (ArrayList) coursestep_properties.get("resourceId"); - ArrayList course_step_resourceTitles = (ArrayList) coursestep_properties.get("resourceId"); - String course_step_title = (String) coursestep_properties.get("title"); - String course_step_id = (String) coursestep_properties.get("_id"); - String course_step_descr = (String) coursestep_properties.get("description"); - int course_step_No = (Integer) coursestep_properties.get("step"); - } - } - csLstCnt++; - coursestep_Db.close(); - } - - LinearLayout row3 = (LinearLayout) findViewById(R.id.layholder_courses); - courseButtons = new Button[csLstCnt]; - for (int ButtonCnt = 0; ButtonCnt < csLstCnt; ButtonCnt++) { - courseButtons[ButtonCnt] = new Button(this); - courseButtons[ButtonCnt].setText(courseTitleList[ButtonCnt]); - courseButtons[ButtonCnt].setId(ButtonCnt); - courseButtons[ButtonCnt].setBackgroundColor(Color.parseColor(mycourseBackgndColor)); - courseButtons[ButtonCnt].setTextColor(Color.parseColor(mycourseForgndColor)); - courseButtons[ButtonCnt].setAllCaps(false); - courseButtons[ButtonCnt].setPadding(10, 5, 10, 5); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - libraryButtons[ButtonCnt].setTextAlignment(View.TEXT_ALIGNMENT_CENTER); - } - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(170, MATCH_PARENT); - layoutParams.setMargins(1, 0, 1, 0); // left, top, right, bottom - GradientDrawable drawable = new GradientDrawable(); - drawable.setShape(GradientDrawable.RECTANGLE); - drawable.setStroke(2, Color.WHITE); - drawable.setCornerRadius(2); - drawable.setColor(getResources().getColor(R.color.ole_black_blue)); - courseButtons[ButtonCnt].setBackgroundDrawable(drawable); - courseButtons[ButtonCnt].setLayoutParams(layoutParams); - row3.addView(courseButtons[ButtonCnt]); - courseButtons[ButtonCnt].setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (courseButtons[view.getId()].getCurrentTextColor() == getResources().getColor(R.color.ole_yellow)) { - /// MaterialClickDialog(false, courseTitleList[view.getId()], courseIdList[view.getId()], view.getId()); - } else { - - } - } - - }); - } - //////////// Save list in Preferences - db.close(); - - } catch (Exception e) { - Log.d("MyCouch", "Error loading courses"); - e.printStackTrace(); - } - } - - public void MaterialClickDialog(boolean online, String title, String resId, int buttonPressedId) { - clicked_rs_status = online; - clicked_rs_title = title; - clicked_rs_ID = resId; - resButtonId = buttonPressedId; - AlertDialog.Builder dialogB2 = new AlertDialog.Builder(this); - // custom dialog - dialogB2.setView(R.layout.dialog_prompt_resource_location); - dialogB2.setCancelable(true); - dialog2 = dialogB2.create(); - dialog2.show(); - TextView txtResourceId = (TextView) dialog2.findViewById(R.id.txtResourceID); - txtResourceId.setText(title); - //// Open material online - dialogBtnOpenFileOnline = (Button) dialog2.findViewById(R.id.btnOpenOnline); - dialogBtnOpenFileOnline.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - //Todo Open resource in a browser - dialog2.dismiss(); - OneByOneResID = clicked_rs_ID; - Fuel ful = new Fuel(); - onlinecouchresource = sys_oldSyncServerURL + "/resources/" + OneByOneResID; - ful.get(sys_oldSyncServerURL + "/resources/" + OneByOneResID).responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - try { - /// alertDialogOkay(OneByOneResID+""); - openFromOnlineServer = true; - jsonData = new JSONObject(s); - String openWith = (String) jsonData.get("openWith"); - Log.e("MyCouch", "Open With -- " + openWith); - JSONObject _attachments = (JSONObject) jsonData.get("_attachments"); - if (!openWith.equalsIgnoreCase("HTML")) { - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - String encodedkey = URLEncoder.encode(key, "utf-8"); - onlinecouchresource = onlinecouchresource + "/" + encodedkey; - mDialog.dismiss(); - openHTML(onlinecouchresource); - } - } else { - if (_attachments.length() <= 1) { - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - String encodedkey = URLEncoder.encode(key, "utf-8"); - onlinecouchresource = onlinecouchresource + "/" + encodedkey; - mDialog.dismiss(); - openHTML(onlinecouchresource); - } - } else { - onlinecouchresource = onlinecouchresource + "/index.html"; - mDialog.dismiss(); - openHTML(onlinecouchresource); - } - - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - alertDialogOkay("Error downloading file"); - Log.e("MyCouch", " " + fuelError); - } - }); - } - }); - - //// Download Only selected file - dialogBtnDownoadFile = (Button) dialog2.findViewById(R.id.btnDownloadFile); - dialogBtnDownoadFile.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dialog2.dismiss(); - OneByOneResID = clicked_rs_ID; - try { - mDialog = new ProgressDialog(context); - mDialog.setMessage("Please wait..."); - mDialog.setCancelable(false); - mDialog.show(); - - ///syncThreadHandler(); - - //// Todo Decide which option is best - singleFiledownload = true; - new downloadSpecificResourceToDisk().execute(); - //final AsyncTask execute = new SyncResource().execute(); - } catch (Exception e) { - e.printStackTrace(); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Error Downloading Resource. Check connection to server and try again"); - mDialog.setCancelable(true); - mDialog.show(); - } catch (Throwable throwable) { - throwable.printStackTrace(); - - } - } - }); - - //// Download all resources on button click - dialogBtnDownoadAll = (Button) dialog2.findViewById(R.id.btnDownloadAll); - dialogBtnDownoadAll.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dialog2.dismiss(); - OneByOneResID = clicked_rs_ID; - try { - //String root = Environment.getExternalStorageDirectory().toString(); - //File myDir = new File(root + "/ole_temp"); - //deleteDirectory(myDir); - //myDir.mkdirs(); - mDialog = new ProgressDialog(context); - mDialog.setMessage("Downloading resource, please wait..." + resourceTitleList[allresDownload]); - mDialog.setCancelable(true); - mDialog.show(); - htmlResourceList.clear(); - allhtmlDownload = 0; - //// Todo Decide which option is best - singleFiledownload = false; - new downloadAllResourceToDisk().execute(); - //new SyncAllResource().execute(); - } catch (Exception e) { - e.printStackTrace(); - } catch (Throwable throwable) { - throwable.printStackTrace(); - - } - } - }); - mDialog = new ProgressDialog(context); - mDialog.setMessage("This resource is not downloaded on this device. \n Please wait. Establishing connection with to server so you can download it..."); - mDialog.setCancelable(false); - mDialog.show(); - new AsyncCheckConnection().execute(); - } - - ///todo check and replace below - private class AsyncCheckConnection extends AsyncTask { - @Override - protected Void doInBackground(Void... params) { - Fuel ful = new Fuel(); - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - mDialog.dismiss(); - dialog2.dismiss(); - alertDialogOkay("Check the server address again. Saved address isn't the BeLL server"); - calbackStatus = false; - } else { - calbackStatus = true; - mDialog.dismiss(); - dialog2.show(); - ///alertDialogOkay("Test successful. You can now click on \"Save and Proceed\" "); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void failure(Request request, Response response, FuelError fuelError) { - dialog2.dismiss(); - mDialog.dismiss(); - calbackStatus = false; - alertDialogOkay("Device couldn't reach server [" + sys_oldSyncServerURL + "]. \n Check server address and try again"); - Log.e("MyCouch", " " + fuelError); - - } - }); - return null; - } - - @Override - protected void onPostExecute(Void result) { - - } - } - - class SyncResource extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URL remote = getReplicationURL(); - CountDownLatch replicationDoneSignal = new CountDownLatch(1); - database = manager.getDatabase("resources"); - repl = database.createPullReplication(remote); - repl.setContinuous(false); -//// Todo Decide either use design document in app or not -// repl.setFilter("bell/by_resource"); - repl.setFilter("apps/by_resource"); - Map map = new HashMap(); - map.put("_id", OneByOneResID); - repl.setFilterParams(map); - repl.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - Log.e("MyCouch", "Current Status " + repl.getStatus()); - if (repl.isRunning()) { - if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_ACTIVE")) { - Log.e("MyCouch", " " + event.getChangeCount()); - Log.e("MyCouch", " Document Count " + database.getDocumentCount()); - } else if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_STOPPED")) { - mDialog.dismiss(); - checkAllDocsInDB(); - libraryButtons[resButtonId].setTextColor(getResources().getColor(R.color.ole_white)); - } else { - mDialog.setMessage("Data transfer error. Check connection to server."); - } - } else { - Log.e("MyCouch", "Document Count " + database.getDocumentCount()); - mDialog.dismiss(); - checkAllDocsInDB(); - libraryButtons[resButtonId].setTextColor(getResources().getColor(R.color.ole_white)); - - } - } - }); - repl.start(); - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - return null; - } - } - - class SyncAllHTMLResource extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URL remote = getReplicationURL(); - CountDownLatch replicationDoneSignal = new CountDownLatch(1); - final Database database; - database = manager.getDatabase("resources"); - final Replication repl = (Replication) database.createPullReplication(remote); - repl.setContinuous(false); - repl.setDocIds(htmlResourceList); - repl.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - Log.e("MyCouch", "Current Status " + repl.getStatus()); - if (repl.isRunning()) { - if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_ACTIVE")) { - Log.e("MyCouch", " " + event.getChangeCount()); - Log.e("MyCouch", " Document Count " + database.getDocumentCount()); - mDialog.setMessage("Downloading HTML resources now .. " + database.getDocumentCount() + "/" + htmlResourceList.size()); - } else if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_STOPPED")) { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - - } else { - mDialog.setMessage("Data transfer error. Check connection to server."); - - } - } else { - Log.e("MyCouch", "Document Count Last " + database.getDocumentCount()); - mDialog.dismiss(); - // dbDiagnosticCheck(); - } - } - }); - repl.start(); - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - return null; - } - - protected void onPostExecute(final Boolean success) { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - - class SyncSingleHTMLResource extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URL remote = getReplicationURL(); - CountDownLatch replicationDoneSignal = new CountDownLatch(1); - final Database database; - database = manager.getDatabase("resources"); - final Replication repl = (Replication) database.createPullReplication(remote); - repl.setContinuous(false); - repl.setDocIds(htmlResourceList); - repl.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - Log.e("MyCouch", "Current Status " + repl.getStatus()); - if (repl.isRunning()) { - if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_ACTIVE")) { - Log.e("MyCouch", " " + event.getChangeCount()); - Log.e("MyCouch", " Document Count " + database.getDocumentCount()); - mDialog.setMessage("Downloading HTML resources now .. " + database.getDocumentCount() + "/" + htmlResourceList.size()); - } else if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_STOPPED")) { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } else { - mDialog.setMessage("Data transfer error. Check connection to server."); - } - } else { - Log.e("MyCouch", "Document Count Last " + database.getDocumentCount()); - mDialog.dismiss(); - // dbDiagnosticCheck(); - } - } - }); - repl.start(); - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - return null; - } - - protected void onPostExecute(final Boolean success) { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - - public URL getReplicationURL() { - URL url = null; - try { - url = new URL(sys_oldSyncServerURL + "/resources"); - } catch (Exception err) { - Log.d("TAG", "Error with URL "); - } - return url; - } - - public void checkAllDocsInDB() { - try { - Database database = manager.getDatabase("resources"); - database.getAllDocs(new QueryOptions()); - Query queryAllDocs = database.createAllDocumentsQuery(); - QueryEnumerator queryEnumerator = queryAllDocs.run(); - for (Iterator it = queryEnumerator; it.hasNext(); ) { - QueryRow row = it.next(); - Document document = row.getDocument(); - Revision revision = document.getCurrentRevision(); - Log.d("MyCouch", document.getId() + " : " + revision.getAttachments().size()); - if (document.getId().equalsIgnoreCase(OneByOneResID)) { - Resource resource = resourceList.get(resButtonId); - resource.setTitle((String) document.getProperty("title")); - String OpenWith = (String) document.getProperty("openWith"); - if (OpenWith.equalsIgnoreCase("Flow Video Player") || OpenWith.equalsIgnoreCase("MP3") || OpenWith.equalsIgnoreCase("PDF.js") || OpenWith.equalsIgnoreCase("HTML")) { - resource.setThumbnailUrl(getIconType((String) document.getProperty("openWith"))); - } else { - resource.setThumbnailUrl(getIconType("-")); - } - Log.d("MyCouch", "Found resource : Making " + (String) document.getProperty("openWith")); - resourceList.set(resButtonId, resource); - } - } - - Log.d("MyCouch", "done looping over all docs "); - ///mDialog.dismiss(); - - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - } - - public void dbDiagnosticCheck() { - try { - Database database = manager.getDatabase("resources"); - database.getAllDocs(new QueryOptions()); - Query queryAllDocs = database.createAllDocumentsQuery(); - QueryEnumerator queryEnumerator = queryAllDocs.run(); - for (Iterator it = queryEnumerator; it.hasNext(); ) { - QueryRow row = it.next(); - Document document = row.getDocument(); - Revision revision = document.getCurrentRevision(); - Log.d("MyCouch", document.getId() + " : " + revision.getAttachments().size()); - for (int cnt = 0; cnt <= resourceIdList.length; cnt++) { - if (document.getId().equalsIgnoreCase(resourceIdList[cnt])) { - libraryButtons[cnt].setTextColor(getResources().getColor(R.color.ole_white)); - Resource resource = resourceList.get(cnt); - resource.setTitle((String) document.getProperty("title")); - String OpenWith = (String) document.getProperty("openWith"); - if (OpenWith.equalsIgnoreCase("Flow Video Player") || OpenWith.equalsIgnoreCase("MP3") || OpenWith.equalsIgnoreCase("PDF.js") || OpenWith.equalsIgnoreCase("HTML")) { - resource.setThumbnailUrl(getIconType((String) document.getProperty("openWith"))); - } else { - resource.setThumbnailUrl(getIconType("-")); - } - Log.d("MyCouch", "Found resource : Making " + (String) document.getProperty("openWith")); - resourceList.set(cnt, resource); - Log.d("MyCouch", "done looping over all docs "); - } - } - - } - - - ///mDialog.dismiss(); - - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - } - - public int getIconType(String myresExt) { - - int img = R.drawable.web; - switch (myresExt) { - case "Flow Video Player": - img = R.drawable.video; - break; - case "MP3": - img = R.drawable.mp3; - break; - case "PDF.js": - img = R.drawable.pdf; - break; - case "HTML": - img = R.drawable.htmlimage; - break; - case "-": - img = R.drawable.web; - break; - default: - img = R.drawable.unknownresource1; - break; - } - return img; - } - - public void openDoc(String docId) { - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - String openwith = (String) res_doc.getProperty("openWith"); - String openResName = (String) res_doc.getProperty("title"); - openFromDiskDirectly = true; - updateActivityOpenedResources(openResName, docId); - Log.e("MYAPP", " member opening resource = " + docId + " and Open with " + openwith); - List attmentNames = res_doc.getCurrentRevision().getAttachmentNames(); -/////HTML - if (openwith.equalsIgnoreCase("HTML")) { - indexFilePath = null; - if (attmentNames.size() > 1) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - downloadHTMLContent(docId, (String) attmentNames.get(cnt)); - } - if (indexFilePath != null) { - openHTML(indexFilePath); - } - } else { - openImage(docId, (String) attmentNames.get(0), getExtension(attmentNames.get(0))); - } -////PDF - } else if (openwith.equalsIgnoreCase("Just download")) { - //// Todo work to get just download - } else if (openwith.equalsIgnoreCase("PDF.js")) { - if (openFromDiskDirectly) { - Log.e("MyCouch", " Command Video name -: " + docId); - String filenameOnly = ""; - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - for (File f : myDir.listFiles()) { - if (f.isFile()) { - if (f.getName().indexOf(".") > 0) { - filenameOnly = f.getName().substring(0, f.getName().lastIndexOf(".")); - } - Log.e("MyCouch", " File name -: " + f.getName() + " Filename only " + filenameOnly); - if (filenameOnly.equalsIgnoreCase(docId)) { - try { - mDialog.dismiss(); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setPackage("com.adobe.reader"); - intent.setDataAndType(Uri.fromFile(f), "application/pdf"); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } catch (Exception err) { - myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir, "adobe_reader.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - } - } - } else { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openPDF(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - } -////MP3 - } else if (openwith.equalsIgnoreCase("MP3")) { - if (openFromDiskDirectly) { - Log.e("MyCouch", " Command Video name -: " + docId); - String filenameOnly = ""; - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - for (File f : myDir.listFiles()) { - if (f.isFile()) { - if (f.getName().indexOf(".") > 0) { - filenameOnly = f.getName().substring(0, f.getName().lastIndexOf(".")); - } - Log.e("MyCouch", " File name -: " + f.getName() + " Filename only " + filenameOnly); - if (filenameOnly.equalsIgnoreCase(docId)) { - mDialog.dismiss(); - intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(f), mimetype); - this.startActivity(intent); - } - } - } - } else { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - } -/// BELL READER - } else if (openwith.equalsIgnoreCase("Bell-Reader")) { - if (openFromDiskDirectly) { - Log.e("MyCouch", " Command Video name -: " + docId); - String filenameOnly = ""; - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - for (File f : myDir.listFiles()) { - if (f.isFile()) { - if (f.getName().indexOf(".") > 0) { - filenameOnly = f.getName().substring(0, f.getName().lastIndexOf(".")); - } - Log.e("MyCouch", " File name -: " + f.getName() + " Filename only " + filenameOnly); - if (filenameOnly.equalsIgnoreCase(docId)) { - try { - mDialog.dismiss(); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setPackage("com.adobe.reader"); - intent.setDataAndType(Uri.fromFile(f), "application/pdf"); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - } catch (Exception err) { - myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir, "adobe_reader.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } - } - } - } else { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openPDF(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - } - /////VIDEO - } else if (openwith.equalsIgnoreCase("Flow Video Player")) { - if (openFromDiskDirectly) { - Log.e("MyCouch", " Command Video name -: " + docId); - String filenameOnly = ""; - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - for (File f : myDir.listFiles()) { - if (f.isFile()) { - if (f.getName().indexOf(".") > 0) { - filenameOnly = f.getName().substring(0, f.getName().lastIndexOf(".")); - } - Log.e("MyCouch", " File name -: " + f.getName() + " Filename only " + filenameOnly); - if (filenameOnly.equalsIgnoreCase(docId)) { - mDialog.dismiss(); - intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(f), mimetype); - this.startActivity(intent); - } - } - } - } else { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - } - - } else if (openwith.equalsIgnoreCase("BeLL Video Book Player")) { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - - } - } -/// Native Video - } else if (openwith.equalsIgnoreCase("Native Video")) { - if (openFromDiskDirectly) { - Log.e("MyCouch", " Command Video name -: " + docId); - String filenameOnly = ""; - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - for (File f : myDir.listFiles()) { - if (f.isFile()) { - if (f.getName().indexOf(".") > 0) { - filenameOnly = f.getName().substring(0, f.getName().lastIndexOf(".")); - } - Log.e("MyCouch", " File name -: " + f.getName() + " Filename only " + filenameOnly); - if (filenameOnly.equalsIgnoreCase(docId)) { - mDialog.dismiss(); - intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(f), mimetype); - this.startActivity(intent); - } - } - } - } else { - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - } - - } - } catch (Exception Er) { - Log.d("MyCouch", "Opening resource error " + Er.getMessage()); - } - } - - public void openHTML(String index) { - final String mainFile = index; - try { - try { - mDialog.dismiss(); - ComponentName componentName = getPackageManager().getLaunchIntentForPackage("org.mozilla.firefox").getComponent(); - Intent firefoxIntent = IntentCompat.makeRestartActivityTask(componentName); - firefoxIntent.setDataAndType(Uri.parse(mainFile), "text/html"); - startActivity(firefoxIntent); - - //startActivity(intent); - } catch (Exception err) { - mDialog.dismiss(); - Log.e("Error", err.getMessage()); - File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir, "firefox_49_0_multi_android.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - - } catch (Exception Er) { - Er.printStackTrace(); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - - } - - } - - public void downloadHTMLContent(String docId, final String fileName) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - int lth = (int) fileAttachment.getLength(); - try { - InputStream in = fileAttachment.getContent(); - String root = Environment.getExternalStorageDirectory().toString(); - File newDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2/" + docId); - if (!newDir.exists()) { - newDir.mkdirs(); - } - - File myDir = new File(root + "/ole_temp2/" + docId); - File dst = new File(myDir, fileAttachment.getName().replace(" ", "")); - String filepath[] = dst.toString().split("/"); - int defaultLength = myDir.getPath().split("/").length; - String path = myDir.getPath(); - //Log.e("tag", " Location "+ dst.toString() + " Default :" + defaultLength + " fpath: "+filepath.length); - for (int cnt = defaultLength; cnt < (filepath.length - 1); cnt++) { - path = path + "/" + filepath[cnt]; - myDir = new File(path); - if (!myDir.exists()) { - myDir.mkdirs(); - } - } - try { - BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst)); - byte[] buff = new byte[1024]; - int len; - while ((len = in.read(buff)) > 0) { - out.write(buff, 0, len); - } - - Log.e("tag", " Saved " + dst.toString() + " Original length: " + lth); - - in.close(); - out.close(); - if (dst.getName().equalsIgnoreCase("index.html") && (filepath.length - defaultLength) == 1) { - indexFilePath = dst.toString(); - } - - } catch (Exception err) { - Log.e("tag", " Saving " + err.getMessage()); - } - } catch (Exception err) { - err.printStackTrace(); - } - } catch (Exception Er) { - Er.printStackTrace(); - - } - } - - public void openImage(String docId, final String fileName, String player) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - try { - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()) { - myDir.mkdirs(); - } - File dst = new File(myDir, fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF " + dst.toString()); - } catch (Exception err) { - err.printStackTrace(); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - mDialog.dismiss(); - Intent intent = new Intent(); - intent.setAction(android.content.Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "image/*"); - //Log.e("tag", " URL Path "+ Uri.fromFile(dst).getPath());; - startActivity(intent); - } catch (Exception err) { - - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - } catch (Exception Er) { - Er.printStackTrace(); - - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - - } - - public static void mkDirs(File root, List dirs, int depth) { - if (depth == 0) return; - for (String s : dirs) { - File subdir = new File(root, s); - subdir.mkdir(); - mkDirs(subdir, dirs, depth - 1); - } - } - - public void openPDF(String docId, final String fileName, String player) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - - android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).create(); - alertDialog.setTitle("Open Document"); - alertDialog.setMessage("Select which application you wish to open document with"); - alertDialog.setButton(android.app.AlertDialog.BUTTON_POSITIVE, "Adobe PDF Reader", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - try { - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()) { - myDir.mkdirs(); - } - File dst = new File(myDir, fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF " + dst.toString()); - } catch (Exception err) { - err.printStackTrace(); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } /// - mDialog.dismiss(); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setPackage("com.adobe.reader"); - intent.setDataAndType(Uri.fromFile(dst), "application/pdf"); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - - - } catch (Exception err) { - File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir, "adobe_reader.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - - } - }); - - alertDialog.setButton(android.app.AlertDialog.BUTTON_NEGATIVE, "In-App PDF Viewer", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - - try { - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()) { - myDir.mkdirs(); - } - File dst = new File(myDir, fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF " + dst.toString()); - } catch (Exception err) { - err.printStackTrace(); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } /// - - mDialog.dismiss(); - Intent intent = new Intent(FullscreenActivity.this, MyPdfViewerActivity.class); - Log.e("tag", " URL Path " + Uri.fromFile(dst).getPath()); - intent.putExtra(net.sf.andpdf.pdfviewer.PdfViewerActivity.EXTRA_PDFFILENAME, Uri.fromFile(dst).getPath()); - startActivity(intent); - - - } catch (Exception err) { - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - } - }); - alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - - - } - }); - alertDialog.show(); - - } catch (Exception Er) { - Er.printStackTrace(); - - } - - } - public void openAudioVideo(String docId, String fileName, String player) { - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - File src = new File(fileAttachment.getContentURL().getPath()); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - deleteDirectory(myDir); - myDir.mkdirs(); - String diskFileName = fileAttachment.getName(); - diskFileName = diskFileName.replace(" ", ""); - File dst = new File(myDir, diskFileName); - - InputStream in = new FileInputStream(src); - OutputStream out = new FileOutputStream(dst); - - // Transfer bytes from in to out - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - in.close(); - out.close(); - dst.setReadable(true); - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(dst).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - Log.e("tag", "- " + mimetype + " - "); - - if (mimetype == "audio/mpeg") { - mDialog.dismiss(); - intent.setDataAndType(Uri.fromFile(dst), mimetype); - this.startActivity(intent); - } else { - try { - mDialog.dismiss(); - intent.setDataAndType(Uri.fromFile(dst), mimetype); - this.startActivity(intent); - } catch (Exception Er) { - Log.e("tag", Er.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - } - } catch (Exception Er) { - Log.e("tag", Er.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Couldn't open resource try again"); - } - - } - - public String getExtension(final String filename) { - if (filename == null) { - return null; - } - final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1); - final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1; - final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash); - return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1); - } - - public boolean updateActivityOpenedResources(String resource_name, String resourceid) { - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - Database activityLog; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - activityLog = manager.getDatabase("activitylog"); - @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); - //This is for setting the MAC address if it is being run in a android emulator. - String m_WLANMAC; - m_WLANMAC = wm.getConnectionInfo().getMacAddress(); - if(m_WLANMAC == null) { - m_WLANMAC = "mymac"; - } - Document retrievedDocument = activityLog.getDocument(m_WLANMAC); - Map properties = retrievedDocument.getProperties(); - if ((ArrayList) properties.get("female_opened") != null) { - try { - ArrayList female_opened = (ArrayList) properties.get("female_opened"); - ArrayList male_opened = (ArrayList) properties.get("male_opened"); - ArrayList resources_names = (ArrayList) properties.get("resources_names"); - ArrayList resources_opened = (ArrayList) properties.get("resources_opened"); - Log.e("MyCouch", "Option 1 "+ sys_usergender.toLowerCase()); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_opened.add(1); - male_opened.add(0); - } else { - female_opened.add(0); - male_opened.add(1); - } - resources_names.add(resource_name); - resources_opened.add(resourceid); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("female_opened", female_opened); - newProperties.put("male_opened", male_opened); - newProperties.put("resources_names", resources_names); - newProperties.put("resources_opened", resources_opened); - retrievedDocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource open in local Activity Log "+newProperties.toString()); - return true; - } catch (Exception err) { - Log.e("MyCouch", "Option 1 Failed " + err.getMessage()); - return false; - } - } else { - try { - Log.e("MyCouch", "Option 2 gender is "+ sys_usergender.toLowerCase()); - Document newdocument = activityLog.getDocument(m_WLANMAC); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - ArrayList female_opened = new ArrayList(); - ArrayList male_opened = new ArrayList(); - ArrayList resources_names = new ArrayList(); - ArrayList resources_opened = new ArrayList(); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_opened.add(1); - male_opened.add(0); - } else { - female_opened.add(0); - male_opened.add(1); - } - resources_names.add(resource_name); - resources_opened.add(resourceid); - newProperties.put("female_opened", female_opened); - newProperties.put("male_opened", male_opened); - newProperties.put("resources_names", resources_names); - newProperties.put("resources_opened", resources_opened); - newdocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource open in local Activity Log "+newProperties.toString()); - return true; - } catch (Exception er) { - Log.e("MyCouch", "Option 2 Failed" + er.getMessage()); - return false; - } - } - /* - try { - Log.e("MyCouch", "Option 1b"); - Document newdocument = activityLog.getDocument(m_WLANMAC); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - ArrayList female_opened = new ArrayList(); - ArrayList male_opened = new ArrayList(); - ArrayList resources_names = new ArrayList(); - ArrayList resources_opened = new ArrayList(); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_opened.add(1); - male_opened.add(0); - } else { - female_opened.add(0); - male_opened.add(1); - } - resources_names.add(resource_name); - resources_opened.add(resourceid); - newProperties.put("female_opened", female_opened); - newProperties.put("male_opened", male_opened); - newProperties.put("resources_names", resources_names); - newProperties.put("resources_opened", resources_opened); - newdocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource open in local Activity Log "); - return true; - }catch(Exception err) { - Log.e("MyCouch", "Opetion 1b Failed : " + err.getMessage()); - return false; - } - */ - } catch (Exception err) { - Log.e("MyCouch", "Updating Activity Log : " + err.getMessage()); - return false; - } - } - - public boolean updateActivityRatingResources(float rate, String resourceid) { - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - Database activityLog; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - activityLog = manager.getDatabase("activitylog"); - @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); - String m_WLANMAC = wm.getConnectionInfo().getMacAddress(); - Document retrievedDocument = activityLog.getDocument(m_WLANMAC); - if (retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - try { - ArrayList female_rating = (ArrayList) properties.get("female_rating"); - ArrayList female_timesRated = (ArrayList) properties.get("female_timesRated"); - ArrayList male_rating = (ArrayList) properties.get("male_rating"); - ArrayList male_timesRated = (ArrayList) properties.get("male_timesRated"); - ArrayList resourcesIds = (ArrayList) properties.get("resourcesIds"); - Log.e("MyCouch", "Option Rating 1"); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_rating.add(rate); - female_timesRated.add(1); - male_rating.add(0); - male_timesRated.add(0); - } else { - female_rating.add(0); - female_timesRated.add(0); - male_rating.add(rate); - male_timesRated.add(1); - } - resourcesIds.add(resourceid); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("female_rating", female_rating); - newProperties.put("female_timesRated", female_timesRated); - newProperties.put("male_rating", male_rating); - newProperties.put("male_timesRated", male_timesRated); - newProperties.put("resourcesIds", resourcesIds); - retrievedDocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource rating in local Activity Log "); - return true; - } catch (Exception err) { - Log.e("MyCouch", "Option Rating 1 Failed " + err.getMessage()); - try { - Log.e("MyCouch", "Option 2"); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - ArrayList female_rating = new ArrayList(); - ArrayList female_timesRated = new ArrayList(); - ArrayList male_rating = new ArrayList(); - ArrayList male_timesRated = new ArrayList(); - ArrayList resourcesIds = new ArrayList(); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_rating.add(rate); - female_timesRated.add(1); - male_rating.add(0); - male_timesRated.add(0); - } else { - female_rating.add(0); - female_timesRated.add(0); - male_rating.add(rate); - male_timesRated.add(1); - } - resourcesIds.add(resourceid); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("female_rating", female_rating); - newProperties.put("female_timesRated", female_timesRated); - newProperties.put("male_rating", male_rating); - newProperties.put("male_timesRated", male_timesRated); - newProperties.put("resourcesIds", resourcesIds); - retrievedDocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource rating in local Activity Log "); - return true; - } catch (Exception er) { - Log.e("MyCouch", "Option Rating 2 Failed" + er.getMessage()); - return false; - } - } - } else { - try { - Log.e("MyCouch", "Option Rating 1b"); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - ArrayList female_rating = new ArrayList(); - ArrayList female_timesRated = new ArrayList(); - ArrayList male_rating = new ArrayList(); - ArrayList male_timesRated = new ArrayList(); - ArrayList resourcesIds = new ArrayList(); - if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) { - female_rating.add(rate); - female_timesRated.add(1); - male_rating.add(0); - male_timesRated.add(0); - } else { - female_rating.add(0); - female_timesRated.add(0); - male_rating.add(rate); - male_timesRated.add(1); - } - resourcesIds.add(resourceid); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("female_rating", female_rating); - newProperties.put("female_timesRated", female_timesRated); - newProperties.put("male_rating", male_rating); - newProperties.put("male_timesRated", male_timesRated); - newProperties.put("resourcesIds", resourcesIds); - retrievedDocument.putProperties(newProperties); - Log.e("MyCouch", "Saved resource rating in local Activity Log "); - return true; - } catch (Exception err) { - Log.e("MyCouch", "Option Rating 1b Failed : " + err.getMessage()); - return false; - } - } - } catch (Exception err) { - Log.e("MyCouch", "Updating Activity Rating Log : " + err.getMessage()); - return false; - } - } - - public boolean deleteDirectory(File path) { - if (path.exists()) { - if (path.isDirectory()) { - File[] files = path.listFiles(); - for (int i = 0; i < files.length; i++) { - deleteDirectory(files[i]); - } - } - return path.delete(); - } - - return false; - } - - public void animateLayoutBars() { - - ///////// Layout Slide in Animation from bottom to up - final LinearLayout libraryLayout = (LinearLayout) findViewById(R.id.layoutMasterLibrary); - libraryLayout.setVisibility(View.INVISIBLE); - final TranslateAnimation translateAnimationLibrary = new TranslateAnimation(-1000, 0, 0, 0); - translateAnimationLibrary.setInterpolator(new LinearInterpolator()); - translateAnimationLibrary.setDuration(500); - translateAnimationLibrary.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - libraryLayout.setVisibility(View.VISIBLE); - - - } - - @Override - public void onAnimationEnd(Animation animation) { - //sd_Slidin.stop(); - - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - - - final LinearLayout coursesLayout = (LinearLayout) findViewById(R.id.layoutMasterCoursesProgress); - coursesLayout.setVisibility(View.INVISIBLE); - final TranslateAnimation translateAnimationCourses = new TranslateAnimation(1000, 0, 0, 0); - translateAnimationCourses.setInterpolator(new LinearInterpolator()); - translateAnimationCourses.setDuration(500); - translateAnimationCourses.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - coursesLayout.setVisibility(View.VISIBLE); - - } - - @Override - public void onAnimationEnd(Animation animation) { - - libraryLayout.startAnimation(translateAnimationLibrary); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - - final LinearLayout MeetupLayout = (LinearLayout) findViewById(R.id.layoutMasterMeetup); - MeetupLayout.setVisibility(View.INVISIBLE); - final TranslateAnimation translateAnimationMeetup = new TranslateAnimation(-1000, 0, 0, 0); - translateAnimationMeetup.setInterpolator(new LinearInterpolator()); - translateAnimationMeetup.setDuration(500); - translateAnimationMeetup.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - MeetupLayout.setVisibility(View.VISIBLE); - - - } - - @Override - public void onAnimationEnd(Animation animation) { - - //sd_Slidin = null; - coursesLayout.startAnimation(translateAnimationCourses); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - - - final LinearLayout TutorsLayout = (LinearLayout) findViewById(R.id.layoutMasterTutors); - TutorsLayout.setVisibility(View.INVISIBLE); - final TranslateAnimation translateAnimationTutors = new TranslateAnimation(1000, 0, 0, 0); - translateAnimationTutors.setInterpolator(new LinearInterpolator()); - translateAnimationTutors.setDuration(500); - translateAnimationTutors.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - TutorsLayout.setVisibility(View.VISIBLE); - //sd_Slidin.start(); - - } - - @Override - public void onAnimationEnd(Animation animation) { - MeetupLayout.startAnimation(translateAnimationMeetup); - - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - TutorsLayout.startAnimation(translateAnimationTutors); - - - } - - public void toggleTopUserInfo() { - final LinearLayout userInfoLayout = (LinearLayout) findViewById(R.id.layoutUserInfo); - //userInfoLayout.setVisibility(View.INVISIBLE); - - final TranslateAnimation translateShowUserInfo = new TranslateAnimation(0, 0, 0, -200); - translateShowUserInfo.setInterpolator(new LinearInterpolator()); - translateShowUserInfo.setDuration(500); - translateShowUserInfo.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - userInfoLayout.setVisibility(View.VISIBLE); - - } - - @Override - public void onAnimationEnd(Animation animation) { - userInfoDisplayed = true; - //userInfoLayout.setVisibility(View.INVISIBLE); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - - final TranslateAnimation translateHideUserInfo = new TranslateAnimation(0, 0, -100, 0); - translateHideUserInfo.setInterpolator(new LinearInterpolator()); - translateHideUserInfo.setDuration(500); - translateHideUserInfo.setAnimationListener(new Animation.AnimationListener() { - @Override - public void onAnimationStart(Animation animation) { - userInfoLayout.setVisibility(View.VISIBLE); - } - - @Override - public void onAnimationEnd(Animation animation) { - userInfoDisplayed = false; - //userInfoLayout.setVisibility(View.INVISIBLE); - } - - @Override - public void onAnimationRepeat(Animation animation) { - - } - }); - - - ImageView imgProfileImage = (ImageView) findViewById(R.id.imageProfilePics); - imgProfileImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (!userInfoDisplayed) { - userInfoLayout.startAnimation(translateShowUserInfo); - } else { - userInfoLayout.startAnimation(translateHideUserInfo); - } - } - }); - } - - public void updateUI() { - TextView lblName = (TextView) findViewById(R.id.lblName); - lblName.setText(" " + sys_userfirstname + " " + sys_userlastname); - TextView lblVisits = (TextView) findViewById(R.id.lblVisits); - if (sys_uservisits == "") { - //// Todo change word 'Visits' to be read from languages - lblVisits.setText("" + sys_uservisits_Int + " Visits"); - } else { - lblVisits.setText("" + sys_uservisits + " Visits"); - } - TextView lblServerName = (TextView) findViewById(R.id.lbl_SeverName); - lblServerName.setText("" + sys_servername.toUpperCase()); - - } - - public void alertDialogOkay(String Message) { - AlertDialog.Builder builder1 = new AlertDialog.Builder(context); - builder1.setMessage(Message); - builder1.setCancelable(true); - builder1.setNegativeButton("Okay", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - }); - AlertDialog alert11 = builder1.create(); - alert11.show(); - } - public void downloadOneResourceToDisk() { - try { - URI uri = URI.create(sys_oldSyncServerURL); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = null, url_pwd = null; - if (sys_oldSyncServerURL.contains("@")) { - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - - CouchDbClientAndroid dbClient = new CouchDbClientAndroid("resources", true, url_Scheme, url_Host, url_Port, url_user, url_pwd); - Log.e("MyCouch", "Here Now"); - if (dbClient.contains(OneByOneResID)) { - /// Handle with Json - JsonObject jsonObject = dbClient.find(JsonObject.class, OneByOneResID); - JsonObject jsonAttachments = jsonObject.getAsJsonObject("_attachments"); - String openWith = (String) jsonObject.get("openWith").getAsString(); - Log.e("MyCouch", "Open With -- " + openWith); - if (!openWith.equalsIgnoreCase("HTML")) { - JSONObject _attachments = new JSONObject(jsonAttachments.toString()); - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - Log.e("MyCouch", "-- " + key); - String encodedkey = URLEncoder.encode(key, "utf-8"); - File file = new File(encodedkey); - String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); - String diskFileName = OneByOneResID + extension; - //createResourceDoc(OneByOneResID, jsonObject.get("title").getAsString(), jsonObject.get("openWith").getAsString()); - //downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey, diskFileName); - } - } else { - Log.e("MyCouch", "-- HTML NOT PART OF DOWNLOADS "); - htmlResourceList.add(OneByOneResID); - if (allhtmlDownload < htmlResourceList.size()) { - try { - URL remote = getReplicationURL(); - CountDownLatch replicationDoneSignal = new CountDownLatch(1); - final Database database; - database = manager.getDatabase("resources"); - final Replication repl = (Replication) database.createPullReplication(remote); - repl.setContinuous(false); - repl.setDocIds(htmlResourceList); - repl.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - Log.e("MyCouch", "Current Status " + repl.getStatus()); - if (repl.isRunning()) { - if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_ACTIVE")) { - Log.e("MyCouch", " " + event.getChangeCount()); - Log.e("MyCouch", " Document Count " + database.getDocumentCount()); - mDialog.setMessage("Downloading HTML resources now .. " + database.getDocumentCount() + "/" + htmlResourceList.size()); - } else if (repl.getStatus().toString().equalsIgnoreCase("REPLICATION_STOPPED")) { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } else { - mDialog.setMessage("Data transfer error. Check connection to server."); - } - } else { - Log.e("MyCouch", "Document Count Last " + database.getDocumentCount()); - mDialog.dismiss(); - // dbDiagnosticCheck(); - } - } - }); - repl.start(); - } catch (CouchbaseLiteException e) { - e.printStackTrace(); - } - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } catch (Exception e) { - Log.e("MyCouch", "Download this resource error " + e.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Error downloading file, check connection and try again"); - } - } - - /// Todo Review Code and test class - class downloadSpecificResourceToDisk extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URI uri = URI.create(sys_oldSyncServerURL); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = null, url_pwd = null; - if (sys_oldSyncServerURL.contains("@")) { - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - CouchDbClientAndroid dbClient = new CouchDbClientAndroid("resources", true, url_Scheme, url_Host, url_Port, url_user, url_pwd); - if (dbClient.contains(OneByOneResID)) { - /// Handle with Json - JsonObject jsonObject = dbClient.find(JsonObject.class, OneByOneResID); - JsonObject jsonAttachments = jsonObject.getAsJsonObject("_attachments"); - final String openWith = (String) jsonObject.get("openWith").getAsString(); - final String title = jsonObject.get("title").getAsString(); - Log.e("MyCouch", "Open With -- " + openWith); - if (!openWith.equalsIgnoreCase("HTML")) { - JSONObject _attachments = new JSONObject(jsonAttachments.toString()); - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - Log.e("MyCouch", "-- " + key); - final String encodedkey = URLEncoder.encode(key, "utf-8"); - File file = new File(encodedkey); - String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); - final String diskFileName = OneByOneResID + extension; - runOnUiThread(new Runnable() { - @Override - public void run() { - downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + OneByOneResID + "/" + encodedkey, diskFileName); - createResourceDoc(OneByOneResID, title, openWith); - } - }); - } - } else { - Log.e("MyCouch", "-- HTML NOT PART OF DOWNLOADS "); - htmlResourceList.add(OneByOneResID); - if (allhtmlDownload < htmlResourceList.size()) { - runOnUiThread(new Runnable() { - @Override - public void run() { - callSuncOneHTMLResource(); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } catch (Exception e) { - Log.e("MyCouch", "Download this resource error " + e.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Error downloading file, check connection and try again"); - return null; - } - return null; - } - } - - public void callSuncOneHTMLResource() { - SyncSingleHTMLResource ssHTML = new SyncSingleHTMLResource(); - ssHTML.execute(); - } -/* - class downloadAllResourceToDisk extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URI uri = URI.create(sys_oldSyncServerURL); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = null, url_pwd = null; - if (sys_oldSyncServerURL.contains("@")) { - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - CouchDbClientAndroid dbClient = new CouchDbClientAndroid("resources", true, url_Scheme, url_Host, url_Port, url_user, url_pwd); - if (dbClient.contains(resourceIdList[allresDownload])) { - /// Handle with Json - JsonObject jsonObject = dbClient.find(JsonObject.class, resourceIdList[allresDownload]); - JsonObject jsonAttachments = jsonObject.getAsJsonObject("_attachments"); - final String openWith = (String) jsonObject.get("openWith").getAsString(); - final String title = jsonObject.get("title").getAsString(); - Log.e("MyCouch", "Open With -- " + openWith); - if (!openWith.equalsIgnoreCase("HTML")) { - JSONObject _attachments = new JSONObject(jsonAttachments.toString()); - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - Log.e("MyCouch", "-- " + key); - final String encodedkey = URLEncoder.encode(key, "utf-8"); - File file = new File(encodedkey); - String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); - final String diskFileName = resourceIdList[allresDownload] + extension; - runOnUiThread(new Runnable() { - @Override - public void run() { - downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + resourceIdList[allresDownload] + "/" + encodedkey, diskFileName); - createResourceDoc(resourceIdList[allresDownload], title, openWith); - } - }); - } - } else { - Log.e("MyCouch", "-- HTML NOT PART OF DOWNLOADS "); - htmlResourceList.add(resourceIdList[allresDownload]); - if (allresDownload < libraryButtons.length) { - allresDownload++; - if (resourceTitleList[allresDownload] != null) { - runOnUiThread(new Runnable() { - @Override - public void run() { - mDialog.setMessage("Download please wait ..."); - new downloadAllResourceToDisk().execute(); - } - }); - } else { - if (allhtmlDownload < htmlResourceList.size()) { - runOnUiThread(new Runnable() { - @Override - public void run() { - callSuncOneHTMLResource(); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } - } - } catch (Exception e) { - Log.e("MyCouch", "Download this resource error " + e.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Error downloading file, check connection and try again"); - return null; - } - return null; - } - - public void callSuncOneHTMLResource() { - SyncSingleHTMLResource ssHTML = new SyncSingleHTMLResource(); - ssHTML.execute(); - } - } - */ - class downloadAllResourceToDisk extends AsyncTask { - @Override - protected Boolean doInBackground(String... params) { - try { - URI uri = URI.create(sys_oldSyncServerURL); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = null, url_pwd = null; - if (sys_oldSyncServerURL.contains("@")) { - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - CouchDbClientAndroid dbClient = new CouchDbClientAndroid("resources", true, url_Scheme, url_Host, url_Port, url_user, url_pwd); - if (dbClient.contains(resourceIdList[allresDownload])) { - /// Handle with Json - JsonObject jsonObject = dbClient.find(JsonObject.class, resourceIdList[allresDownload]); - JsonObject jsonAttachments = jsonObject.getAsJsonObject("_attachments"); - final String openWith = (String) jsonObject.get("openWith").getAsString(); - final String title = jsonObject.get("title").getAsString(); - Log.e("MyCouch", "Open With -- " + openWith); - if (!openWith.equalsIgnoreCase("HTML")) { - JSONObject _attachments = new JSONObject(jsonAttachments.toString()); - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - Log.e("MyCouch", "-- " + key); - final String encodedkey = URLEncoder.encode(key, "utf-8"); - File file = new File(encodedkey); - String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); - final String diskFileName = resourceIdList[allresDownload] + extension; - runOnUiThread(new Runnable() { - @Override - public void run() { - downloadWithDownloadManagerSingleFile(sys_oldSyncServerURL + "/resources/" + resourceIdList[allresDownload] + "/" + encodedkey, diskFileName); - createResourceDoc(resourceIdList[allresDownload], title, openWith); - } - }); - } - } else { - Log.e("MyCouch", "-- HTML NOT PART OF DOWNLOADS "); - htmlResourceList.add(resourceIdList[allresDownload]); - if (allresDownload < libraryButtons.length) { - allresDownload++; - if (resourceTitleList[allresDownload] != null) { - runOnUiThread(new Runnable() { - @Override - public void run() { - mDialog.setMessage("Download please wait ..."); - new downloadAllResourceToDisk().execute(); - } - }); - } else { - if (allhtmlDownload < htmlResourceList.size()) { - runOnUiThread(new Runnable() { - @Override - public void run() { - callSuncOneHTMLResource(); - } - }); - } else { - mDialog.dismiss(); - alertDialogOkay("Download Completed"); - } - } - } - } - } - } catch (Exception e) { - Log.e("MyCouch", "Download this resource error " + e.getMessage()); - mDialog.dismiss(); - alertDialogOkay("Error downloading file, check connection and try again"); - return null; - } - return null; - /* - Fuel ful = new Fuel(); - ful.get(sys_oldSyncServerURL+"/resources/" + resourceIdList[allresDownload]).responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - try { - openFromDiskDirectly = true; - jsonData = new JSONObject(s); - String openWith = (String) jsonData.get("openWith"); - Log.e("MyCouch", "Open With -- " + openWith); - if(!openWith.equalsIgnoreCase("HTML")) { - JSONObject _attachments = (JSONObject) jsonData.get("_attachments"); - Iterator keys = _attachments.keys(); - if (keys.hasNext()) { - String key = (String) keys.next(); - Log.e("MyCouch", "-- " + key); - String encodedkey = URLEncoder.encode(key, "utf-8"); - File file = new File(encodedkey); - String extension = encodedkey.substring(encodedkey.lastIndexOf(".")); - String diskFileName = resourceIdList[allresDownload] + extension; - createResourceDoc(resourceIdList[allresDownload],(String) jsonData.get("title"), (String) jsonData.get("openWith")); - downloadWithDownloadManager(sys_oldSyncServerURL + "/resources/" + resourceIdList[allresDownload] + "/" + encodedkey, diskFileName); - } - }else{ - Log.e("MyCouch", "-- HTML NOT PART OF DOWNLOADS " ); - htmlResourceList.add(resourceIdList[allresDownload]); - if(allresDownload= Build.VERSION_CODES.HONEYCOMB) { - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - } - Log.e("MyCouch", " Destination is " + FileName); - request.setDestinationInExternalPublicDir("ole_temp", FileName); - -// get download service and enqueue file - mDialog.setMessage("Downloading \" " + resourceTitleList[allresDownload] + " \" . please wait..."); - downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); - enqueue = downloadManager.enqueue(request); - } - - public void downloadWithDownloadManagerSingleFile(String fileURL, String FileName) { - String url = fileURL; - DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); - request.setDescription(clicked_rs_ID + "-" + clicked_rs_title); - request.setTitle(clicked_rs_title); -// in order for this if to run, you must use the android 3.2 to compile your app - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { - request.allowScanningByMediaScanner(); - request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); - } - Log.e("MyCouch", " Destination is " + FileName); - request.setDestinationInExternalPublicDir("ole_temp", FileName); - -// get download service and enqueue file - mDialog.setMessage("Downloading \" " + clicked_rs_title + " \" . please wait..."); - downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); - enqueue = downloadManager.enqueue(request); - } - - public void createResourceDoc(String manualResId, String manualResTitle, String manualResopenWith) { - Database database = null; - try { - database = manager.getDatabase("resources"); - Map properties = new HashMap(); - properties.put("title", manualResTitle); - properties.put("openWith", manualResopenWith); - properties.put("localfile", "yes"); - // properties.put("resourceType", manualResType); - Document document = database.getDocument(manualResId); - try { - document.putProperties(properties); - } catch (CouchbaseLiteException e) { - Log.e("MyCouch", "Cannot save document", e); - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public void rateResourceDialog(String resourceId, String title) { - // custom dialog - final String resourceID = resourceId; - final Dialog dialog = new Dialog(context); - dialog.setContentView(R.layout.rate_resource_dialog); - dialog.setTitle("Add Feedback For \n"); - - final TextView txtResTitle = (TextView) dialog.findViewById(R.id.txtResTitle); - txtResTitle.setText(title); - final EditText txtComment = (EditText) dialog.findViewById(R.id.editTextComment); - final RatingBar ratingBar = (RatingBar) dialog.findViewById(R.id.ratingBar); - ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { - public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { - - } - }); - Button dialogButton = (Button) dialog.findViewById(R.id.btnRateResource); - dialogButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - saveRating((int) ratingBar.getRating(), String.valueOf(txtComment.getText()), resourceID); - dialog.dismiss(); - } - }); - dialog.show(); - } - - public void saveRating(int rate, String comment, String resourceId) { - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - Database resourceRating; - int doc_rating; - int doc_timesRated; - ArrayList commentList = new ArrayList(); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - resourceRating = manager.getDatabase("resourcerating"); - Document retrievedDocument = resourceRating.getExistingDocument(resourceId); - if (retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if (properties.containsKey("sum")) { - doc_rating = (int) properties.get("sum"); - doc_timesRated = (int) properties.get("timesRated"); - commentList = (ArrayList) properties.get("comments"); - commentList.add(comment); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("sum", (doc_rating + rate)); - newProperties.put("timesRated", doc_timesRated + 1); - newProperties.put("comments", commentList); - retrievedDocument.putProperties(newProperties); - updateActivityRatingResources(rate, resourceId); - Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show(); - } - } else { - Document newdocument = resourceRating.getDocument(resourceId); - Map newProperties = new HashMap(); - newProperties.put("sum", rate); - newProperties.put("timesRated", 1); - commentList.add(comment); - newProperties.put("comments", commentList); - newdocument.putProperties(newProperties); - /// todo check updating resource to see it works - updateActivityRatingResources(rate, resourceId); - Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show(); - } - } catch (Exception err) { - Log.e("MyCouch", "ERR : " + err.getMessage()); - } - } - - public void checkResourceOpened() { - if (openedResource) { - rateResourceDialog(openedResourceId, openedResourceTitle); - openedResource = false; - } - } - class checkServerConnection extends AsyncTask { - private Exception exception; - protected String doInBackground(String... urls) { - runOnUiThread(new Runnable() { - public void run() - { - final Fuel ful = new Fuel(); - final ProgressDialog connectionDialog = new ProgressDialog(context); - connectionDialog.setMessage("Checking Connection. Please wait .."); - connectionDialog.setCancelable(false); - connectionDialog.show(); - ful.get(sys_oldSyncServerURL + "/_all_dbs").responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - List myList = new ArrayList(); - myList.clear(); - myList = Arrays.asList(s.split(",")); - Log.e("MyCouch", "-- " + myList.size()); - if (myList.size() < 8) { - alertDialogOkay("Check WiFi connection and try again"); - connectionDialog.dismiss(); - } else { - connectionDialog.dismiss(); - final ProgressDialog progressDialog = ProgressDialog.show(FullscreenActivity.this, "Please wait ...", "Syncing", false); - ////////////////////////////// - URL url = new URL(sys_oldSyncServerURL+"/shelf"); - database = manager.getDatabase("shelf"); - final Replication pull = database.createPullReplication(url); - final Replication push = database.createPushReplication(url); - pull.setContinuous(false); - push.setContinuous(false); - pull.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - boolean active = (pull.getStatus() == Replication.ReplicationStatus.REPLICATION_ACTIVE) || - (push.getStatus() == Replication.ReplicationStatus.REPLICATION_ACTIVE); - if (!active) { - progressDialog.dismiss(); - runOnUiThread(new Runnable() { - public void run() { - alertDialogOkay("Tablet Updated Successfully. Logout and Login again to see changes"); - } - }); - } else { - double total = push.getCompletedChangesCount() + pull.getCompletedChangesCount(); - progressDialog.setMax((int) total); - progressDialog.setProgress(push.getChangesCount() + pull.getChangesCount()); - } - } - }); - pull.start(); - push.start(); - } - } catch (Exception e) { - connectionDialog.dismiss(); - alertDialogOkay("Device couldn't reach server. Check and try again"); - e.printStackTrace(); - } - } - @Override - public void failure(Request request, Response response, FuelError fuelError) { - connectionDialog.dismiss(); - alertDialogOkay("Device couldn't reach server. Check and try again"); - Log.e("MyCouch", " " + fuelError); - } - }); - } - }); - return ""; - } - protected void onPostExecute(String data) { - // TODO: check this.exception - // TODO: do something with the feed - } - } - - public void openServerPage(String pageUrl){ - URI uri = URI.create(sys_oldSyncServerURL); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = null, url_pwd = null; - if(sys_oldSyncServerURL.contains("@")){ - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - final String mainFile = url_Scheme+"://"+url_Host+":"+url_Port+""+ pageUrl; - Log.e("Error", mainFile+" --- URL"); - try { - try { - mDialog.dismiss(); - ComponentName componentName = getPackageManager().getLaunchIntentForPackage("org.mozilla.firefox").getComponent(); - Intent firefoxIntent = IntentCompat.makeRestartActivityTask(componentName); - firefoxIntent.setDataAndType(Uri.parse(mainFile), "text/html"); - startActivity(firefoxIntent); - } catch (Exception err) { - mDialog.dismiss(); - File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir, "firefox_49_0_multi_android.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - } catch (Exception Er) { - mDialog.dismiss(); - Er.printStackTrace(); - alertDialogOkay("Couldn't open page try again"); - } - } -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/HTML5WebView.java b/app/src/main/java/pbell/offline/ole/org/pbell/HTML5WebView.java deleted file mode 100644 index 2743cc7..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/HTML5WebView.java +++ /dev/null @@ -1,185 +0,0 @@ -package pbell.offline.ole.org.pbell; -import android.app.Activity; -import android.content.Context; -import android.graphics.Bitmap; -import android.util.AttributeSet; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.webkit.GeolocationPermissions; -import android.webkit.WebChromeClient; -import android.webkit.WebSettings; -import android.webkit.WebView; -import android.webkit.WebViewClient; -import android.widget.FrameLayout; - -/** - * Created by leonardmensah on 06/06/16. - */ -@SuppressWarnings("ALL") -public class HTML5WebView extends WebView { - - private Context mContext; - private MyWebChromeClient mWebChromeClient; - private View mCustomView; - private FrameLayout mCustomViewContainer; - private WebChromeClient.CustomViewCallback mCustomViewCallback; - - private FrameLayout mContentView; - private FrameLayout mBrowserFrameLayout; - private FrameLayout mLayout; - - static final String LOGTAG = "HTML5WebView"; - - private void init(Context context) { - mContext = context; - Activity a = (Activity) mContext; - - mLayout = new FrameLayout(context); - - mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null); - mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content); - mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content); - - mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); - - // Configure the webview - WebSettings s = getSettings(); - s.setBuiltInZoomControls(true); - s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); - s.setUseWideViewPort(true); - s.setLoadWithOverviewMode(true); - // s.setSavePassword(true); - s.setSaveFormData(true); - s.setJavaScriptEnabled(true); - mWebChromeClient = new MyWebChromeClient(); - setWebChromeClient(mWebChromeClient); - - setWebViewClient(new WebViewClient()); - - setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); - - // enable navigator.geolocation - // s.setGeolocationEnabled(true); - // s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/"); - - // enable Web Storage: localStorage, sessionStorage - s.setDomStorageEnabled(true); - - mContentView.addView(this); - } - - public HTML5WebView(Context context) { - super(context); - init(context); - } - - public HTML5WebView(Context context, AttributeSet attrs) { - super(context, attrs); - init(context); - } - - public HTML5WebView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context); - } - - public FrameLayout getLayout() { - return mLayout; - } - - public boolean inCustomView() { - return (mCustomView != null); - } - - public void hideCustomView() { - mWebChromeClient.onHideCustomView(); - } - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { - if ((mCustomView == null) && canGoBack()){ - goBack(); - return true; - } - } - return super.onKeyDown(keyCode, event); - } - - private class MyWebChromeClient extends WebChromeClient { - private Bitmap mDefaultVideoPoster; - private View mVideoProgressView; - - @Override - public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) - { - //Log.i(LOGTAG, "here in on ShowCustomView"); - HTML5WebView.this.setVisibility(View.GONE); - - // if a view already exists then immediately terminate the new one - if (mCustomView != null) { - callback.onCustomViewHidden(); - return; - } - - mCustomViewContainer.addView(view); - mCustomView = view; - mCustomViewCallback = callback; - mCustomViewContainer.setVisibility(View.VISIBLE); - } - - @Override - public void onHideCustomView() { - System.out.println("customview hide"); - if (mCustomView == null) - return; - - // Hide the custom view. - mCustomView.setVisibility(View.GONE); - - // Remove the custom view from its container. - mCustomViewContainer.removeView(mCustomView); - mCustomView = null; - mCustomViewContainer.setVisibility(View.GONE); - mCustomViewCallback.onCustomViewHidden(); - - HTML5WebView.this.setVisibility(View.VISIBLE); - HTML5WebView.this.goBack(); - //Log.i(LOGTAG, "set it to webVew"); - } - - - @Override - public View getVideoLoadingProgressView() { - //Log.i(LOGTAG, "here in on getVideoLoadingPregressView"); - - if (mVideoProgressView == null) { - LayoutInflater inflater = LayoutInflater.from(mContext); - mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null); - } - return mVideoProgressView; - } - - @Override - public void onReceivedTitle(WebView view, String title) { - ((Activity) mContext).setTitle(title); - } - - @Override - public void onProgressChanged(WebView view, int newProgress) { - ((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100); - } - - @Override - public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { - callback.invoke(origin, true, false); - } - } - - - static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = - new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Home.java b/app/src/main/java/pbell/offline/ole/org/pbell/Home.java deleted file mode 100644 index 33e9b46..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Home.java +++ /dev/null @@ -1,49 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.support.v7.app.ActionBar; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.os.Handler; -import android.view.View; - -/** - * An example full-screen activity that shows and hides the system UI (i.e. - * status bar and navigation/system bar) with user interaction. - */ -public class Home extends AppCompatActivity { - - private final Handler mHideHandler = new Handler(); - private View mContentView; - //private View mControlsView; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_home); - //mVisible = true; - //mControlsView = findViewById(R.id.fullscreen_content_controls); - mContentView = findViewById(R.id.fullscreen_content); - /*mContentView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - // toggle(); - } - }); - */ - //CalendarView calendarView = (CalendarView)findViewById(R.id.calendarView); - ///long a = calendarView.getDate(); - //calendarView.setMaxDate(a); - - - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - ActionBar actionBar = getSupportActionBar(); - //mControlsView.setVisibility(View.GONE); - if (actionBar != null) { - actionBar.hide(); - } - } -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListModel.java b/app/src/main/java/pbell/offline/ole/org/pbell/ListModel.java deleted file mode 100644 index 5e6f4c7..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListModel.java +++ /dev/null @@ -1,51 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.util.Log; - -/** - * Created by leonardmensah on 18/05/16. - */ -public class ListModel { - - private String ResourceTitle=""; - private String Image=""; - private String Description=""; - - /*********** Set Methods ******************/ - - public void setTitle(String ResourceTitle) - { - this.ResourceTitle = ResourceTitle; - } - - public void setImage(String Image) - { - this.Image = Image; - } - - public void setDescription(String Description) - { - - Log.e("MYAPP", "DD "+Description); - this.Description = Description; - } - - /*********** Get Methods ****************/ - - public String getTitle() - { - return this.ResourceTitle; - } - - public String getImage() - { - return this.Image; - } - - public String getDescription() - { - return this.Description; - } - - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/ListView_Courses.java b/app/src/main/java/pbell/offline/ole/org/pbell/ListView_Courses.java deleted file mode 100644 index 5749c5e..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/ListView_Courses.java +++ /dev/null @@ -1,196 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.AssetManager; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ListView; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class ListView_Courses extends Fragment { - // static final String URL = "http://api.androidhive.info/music/music.xml"; - static final String KEY_MATERIALS = "materials"; // parent node - static final String KEY_ID = "id"; - static final String KEY_TITLE = "title"; - static final String KEY_DESCRIPTION = "description"; - static final String KEY_DETAILS = "details"; - static final String KEY_FEEDBACK = "feedback"; - static final String KEY_DELETE = "delete"; - static final String KEY_RATING = "4"; - static final String KEY_TOTALNUM_RATING = "200"; - static final String KEY_FEMALE_RATING = "0"; - static final String KEY_MALE_RATING = "0"; - static final String KEY_THUMB_URL = "thumb_url"; - Context context; - public static final String PREFS_NAME = "MyPrefsFile"; - public static final String USERNAME = ""; - SharedPreferences settings; - private static final String TAG = "MYAPP"; - String sys_oldSyncServerURL, sys_username, sys_lastSyncDate, - sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname, - sys_usergender, sys_uservisits, sys_servername, sys_serverversion = ""; - Boolean sys_singlefilestreamdownload, sys_multiplefilestreamdownload; - int sys_uservisits_Int = 0; - AndroidContext androidContext; - Manager manager; - private ProgressDialog mDialog; - - CouchViews chViews = new CouchViews(); - String courseIdList[],courseTitleList[]; - int crsLstCnt,csLstCnt = 0; - static Intent intent; - Database database; - AssetManager assetManager; - - private List courseIDArrayList = new ArrayList<>(); - ListView list; - ListViewAdapter_Library adapter; - ArrayList> materialList; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - context = container.getContext(); - assetManager = getActivity().getAssets(); - View rootView = inflater.inflate(R.layout.listview_universal, container, false); - - materialList = new ArrayList<>(); - - androidContext = new AndroidContext(container.getContext()); - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - } catch (IOException e) { - e.printStackTrace(); - } - restorePref(); - LoadShadowCourseList(); - - list=(ListView)rootView.findViewById(R.id.material_list); - adapter=new ListViewAdapter_Library(getActivity(), materialList); - list.setAdapter(adapter); - list.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view,int position, long id) { - } - }); - - return rootView; - } - public void LoadShadowCourseList() { - try { - Database shadowCourses = manager.getDatabase("courses"); - Query orderedQuery = chViews.ReadCourses(shadowCourses).createQuery(); - orderedQuery.setDescending(true); - QueryEnumerator results = orderedQuery.run(); - courseTitleList = new String[results.getCount()]; - courseIdList = new String[results.getCount()]; - for (Iterator shr = results; shr.hasNext(); ) { - QueryRow row = shr.next(); - String docId = (String) row.getValue(); - com.couchbase.lite.Document course_doc = shadowCourses.getExistingDocument(docId); - Map course_properties = course_doc.getProperties(); - String doc_id = ((String) course_properties.get("_id")); - try { - course_properties = course_doc.getProperties(); - } catch (Exception errs) { - Log.e("tag", "OBJECT ERROR " + errs.toString()); - } - HashMap map = new HashMap<>(); - Log.e("MyCouch", "Number shadow items " + ((String) course_properties.get("title")) + " "); - String buildDecript =""; - try{ - buildDecript = "Author : ............. "; - }catch(Exception err){ - buildDecript = " "; - return; - } - courseTitleList[crsLstCnt] = (String) course_properties.get("title"); - courseIdList[crsLstCnt] = (String) course_properties.get("_id"); - courseIDArrayList.add((String) course_properties.get("_id")); - map.put(KEY_ID, ((String) course_properties.get("_id"))); - map.put(KEY_TITLE, ((String) course_properties.get("title"))); - map.put(KEY_DESCRIPTION, buildDecript); - // Button Actions - map.put(KEY_DETAILS,((String) course_properties.get("_id"))); - map.put(KEY_FEEDBACK, ((String) course_properties.get("_id"))); - map.put(KEY_DELETE, ((String) course_properties.get("_id"))); - - map.put(KEY_RATING, (((String) course_properties.get("averageRating")) == "")? "2.2" : (String) course_properties.get("averageRating")); - map.put(KEY_TOTALNUM_RATING, "Rating ("+course_properties.get("averageRating")+")"); - map.put(KEY_FEMALE_RATING, ""); - map.put(KEY_MALE_RATING, ""); - ///map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL)); - materialList.add(map); - crsLstCnt++; - } - shadowCourses.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - public int getIconType(String myresExt) { - - int img = R.drawable.web; - switch (myresExt) { - case "Flow Video Player": - img = R.drawable.video; - break; - case "MP3": - img = R.drawable.mp3; - break; - case "PDF.js": - img = R.drawable.pdf; - break; - case "HTML": - img = R.drawable.htmlimage; - break; - case "-": - img = R.drawable.web; - break; - default: - img = R.drawable.unknownresource1; - break; - } - return img; - } - public void restorePref(){ - // Restore preferences - settings = getActivity().getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl","http://"); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - sys_password = settings.getString("pf_password",""); - sys_usercouchId = settings.getString("pf_usercouchId",""); - sys_userfirstname = settings.getString("pf_userfirstname",""); - sys_userlastname = settings.getString("pf_userlastname",""); - sys_usergender = settings.getString("pf_usergender",""); - sys_uservisits = settings.getString("pf_uservisits",""); - sys_uservisits_Int = settings.getInt("pf_uservisits_Int",0); - sys_singlefilestreamdownload =settings.getBoolean("pf_singlefilestreamdownload",true); - sys_multiplefilestreamdownload = settings.getBoolean("multiplefilestreamdownload",true); - sys_servername = settings.getString("pf_server_name"," "); - sys_serverversion = settings.getString("pf_server_version"," "); - } - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/LoginActivity.java b/app/src/main/java/pbell/offline/ole/org/pbell/LoginActivity.java deleted file mode 100644 index b268aca..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/LoginActivity.java +++ /dev/null @@ -1,661 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.annotation.TargetApi; -import android.app.Dialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.support.annotation.NonNull; -import android.support.design.widget.Snackbar; -import android.support.multidex.MultiDex; -import android.support.v7.app.AppCompatActivity; -import android.app.LoaderManager.LoaderCallbacks; - -import android.content.CursorLoader; -import android.content.Loader; -import android.database.Cursor; -import android.net.Uri; -import android.os.AsyncTask; - -import android.os.Build; -import android.os.Bundle; -import android.provider.ContactsContract; -import android.text.TextUtils; -import android.util.Log; -import android.view.KeyEvent; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.inputmethod.EditorInfo; -import android.widget.ArrayAdapter; -import android.widget.AutoCompleteTextView; -import android.widget.Button; -import android.widget.EditText; -import android.widget.TextView; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static android.Manifest.permission.READ_CONTACTS; - -/** - * A login screen that offers login via email/password. - */ -@SuppressWarnings("ALL") -public class LoginActivity extends AppCompatActivity implements LoaderCallbacks { - - /** - * Id to identity READ_CONTACTS permission request. - */ - private static final int REQUEST_READ_CONTACTS = 0; - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - CouchViews chViews = new CouchViews(); - final Context context = this; - String doc_lastVisit; - - /** - * A dummy authentication store containing known user names and passwords. - * TODO: remove after connecting to a real authentication system. - */ - private static final String[] DUMMY_CREDENTIALS = new String[]{ - "foo@example.com:hello", "bar@example.com:world" - }; - /** - * Keep track of the login task to ensure we can cancel it if requested. - */ - private UserLoginTask mAuthTask = null; - - // UI references. - private AutoCompleteTextView mUsername; - private EditText mPasswordView; - private View mProgressView; - private View mLoginFormView; - - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate, - sys_password,sys_usercouchId,sys_userfirstname,sys_userlastname, - sys_usergender,sys_uservisits,lbl_SeverName,sys_servername,sys_serverversion= ""; - Object[] sys_membersWithResource; - ///int sys_uservisits=0; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_login); - - - - // Set up the login form. - mUsername = (AutoCompleteTextView) findViewById(R.id.username); - populateAutoComplete(); - - mPasswordView = (EditText) findViewById(R.id.password); - mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { - @Override - public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { - if (id == R.id.login || id == EditorInfo.IME_NULL) { - attemptLogin(); - return true; - } - return false; - } - }); - - - - Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); - mEmailSignInButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View view) { - attemptLogin(); - - - } - }); - - mLoginFormView = findViewById(R.id.login_form); - mProgressView = findViewById(R.id.login_progress); - - - // Restore preferences - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - sys_password = settings.getString("pf_password",""); - sys_usercouchId = settings.getString("pf_usercouchId",""); - sys_userfirstname = settings.getString("pf_userfirstname",""); - sys_userlastname = settings.getString("pf_userlastname",""); - sys_usergender = settings.getString("pf_usergender",""); - sys_uservisits = settings.getString("pf_uservisits",""); - sys_servername = settings.getString("pf_server_name"," -- "); - sys_serverversion = settings.getString("pf_server_version"," ---"); - - - - if(sys_username!=""){ - mUsername.setText(sys_username); - }else{ - mUsername.setText(""); - } - Set mwr = settings.getStringSet("membersWithResource",null); - try{ - sys_membersWithResource = mwr.toArray(); - Log.e("MYAPP", " membersWithResource = "+sys_membersWithResource.length); - - }catch(Exception err){ - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - - - try { - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("members"); - if(db.getDocumentCount()<1){ - Log.e("MYAPP", " Device Not Synced "); - db.close(); - getSyncURLDialog(); - } - } catch (Exception e) { - e.printStackTrace(); - getSyncURLDialog(); - Log.e("MYAPP", " Device Not Synced "); - - } - - - } - @Override - protected void attachBaseContext(Context newBase) { - super.attachBaseContext(newBase); - MultiDex.install(this); - } - - private void populateAutoComplete() { - if (!mayRequestContacts()) { - return; - } - - getLoaderManager().initLoader(0, null, this); - } - - private boolean mayRequestContacts() { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { - return true; - } - if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { - return true; - } - if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { - Snackbar.make(mUsername, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) - .setAction(android.R.string.ok, new View.OnClickListener() { - @Override - @TargetApi(Build.VERSION_CODES.M) - public void onClick(View v) { - requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); - } - }); - } else { - requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); - } - return false; - } - - /** - * Callback received when a permissions request has been completed. - */ - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { - if (requestCode == REQUEST_READ_CONTACTS) { - if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { - populateAutoComplete(); - } - } - } - - - /** - * Attempts to sign in or register the account specified by the login form. - * If there are form errors (invalid email, missing fields, etc.), the - * errors are presented and no actual login attempt is made. - */ - private void attemptLogin() { - if (mAuthTask != null) { - return; - } - - // Reset errors. - mUsername.setError(null); - mPasswordView.setError(null); - - // Store values at the time of the login attempt. - String email = mUsername.getText().toString(); - String password = mPasswordView.getText().toString(); - - boolean cancel = false; - View focusView = null; - - // Check for a valid password, if the user entered one. - if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { - ///mPasswordView.setError(getString(R.string.error_invalid_password)); - ///focusView = mPasswordView; - //cancel = true; - } - - // Check for a valid email address. - if (TextUtils.isEmpty(email)) { - mUsername.setError(getString(R.string.error_field_required)); - focusView = mUsername; - cancel = true; - } - - if (cancel) { - // There was an error; don't attempt login and focus the first - // form field with an error. - focusView.requestFocus(); - } else { - // Show a progress spinner, and kick off a background task to - // perform the user login attempt. - showProgress(true); - mAuthTask = new UserLoginTask(email, password); - mAuthTask.execute((Void) null); - } - } - - private boolean isEmailValid(String email) { - //TODO: Replace this with your own logic - return email.contains("@"); - } - - private boolean isPasswordValid(String password) { - //TODO: Replace this with your own logic - return password.length() > 4; - } - - /** - * Shows the progress UI and hides the login form. - */ - @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) - private void showProgress(final boolean show) { - // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow - // for very easy animations. If available, use these APIs to fade-in - // the progress spinner. - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { - int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); - - mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); - mLoginFormView.animate().setDuration(shortAnimTime).alpha( - show ? 0 : 1).setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); - } - }); - - mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); - mProgressView.animate().setDuration(shortAnimTime).alpha( - show ? 1 : 0).setListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationEnd(Animator animation) { - mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); - } - }); - } else { - // The ViewPropertyAnimator APIs are not available, so simply show - // and hide the relevant UI components. - mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); - mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); - } - } - - @Override - public Loader onCreateLoader(int i, Bundle bundle) { - return new CursorLoader(this, - // Retrieve data rows for the device user's 'profile' contact. - Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, - ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, - - // Select only email addresses. - ContactsContract.Contacts.Data.MIMETYPE + - " = ?", new String[]{ContactsContract.CommonDataKinds.Email - .CONTENT_ITEM_TYPE}, - - // Show primary email addresses first. Note that there won't be - // a primary email address if the user hasn't specified one. - ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); - } - - @Override - public void onLoadFinished(Loader cursorLoader, Cursor cursor) { - List emails = new ArrayList<>(); - cursor.moveToFirst(); - while (!cursor.isAfterLast()) { - emails.add(cursor.getString(ProfileQuery.ADDRESS)); - cursor.moveToNext(); - } - - addEmailsToAutoComplete(emails); - } - - @Override - public void onLoaderReset(Loader cursorLoader) { - - } - - private void addEmailsToAutoComplete(List emailAddressCollection) { - //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. - ArrayAdapter adapter = - new ArrayAdapter<>(LoginActivity.this, - android.R.layout.simple_dropdown_item_1line, emailAddressCollection); - - mUsername.setAdapter(adapter); - } - - - private interface ProfileQuery { - String[] PROJECTION = { - ContactsContract.CommonDataKinds.Email.ADDRESS, - ContactsContract.CommonDataKinds.Email.IS_PRIMARY, - }; - - int ADDRESS = 0; - int IS_PRIMARY = 1; - } - - public boolean authenticateUser(){ - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("members"); - Query orderedQuery = chViews.CreateLoginByIdView(db).createQuery(); - orderedQuery.setDescending(true); - QueryEnumerator results = orderedQuery.run(); - for (Iterator it = results; it.hasNext();) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - String doc_loginId = (String) properties.get("login"); - String doc_password = (String) properties.get("password"); - - if(mUsername.getText().toString().equals(doc_loginId)) { - Log.e("MYAPP", "Authentiicating User"); - - if (mPasswordView.getText().toString().equals(doc_password) && !properties.containsKey("credentials") ) { - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_username", (String) properties.get("login")); - editor.putString("pf_password", (String) properties.get("password")); - editor.putString("pf_usercouchId", (String) properties.get("_id")); - editor.putString("pf_userfirstname", (String) properties.get("firstName")); - editor.putString("pf_userlastname", (String) properties.get("lastName")); - editor.putString("pf_usergender", (String) properties.get("Gender")); - editor.putString("pf_lastVisitDate", doc_lastVisit); - try { - String noOfVisits = properties.get("visits").toString(); - editor.putInt("pf_uservisits_Int", (Integer.parseInt(noOfVisits) + totalVisits((String) properties.get("_id")))); - } catch (Exception err) { - } - Set stgSet = settings.getStringSet("pf_userroles", new HashSet()); - ArrayList roleList = (ArrayList) properties.get("roles"); - for (int cnt = 0; cnt < roleList.size(); cnt++) { - stgSet.add(String.valueOf(roleList.get(cnt))); - } - editor.putStringSet("pf_userroles", stgSet); - editor.commit(); - Log.e("MYAPP", " Data Login OLD encryption: " + doc_loginId + " Password: " + doc_password); - Intent intent = new Intent(this, Dashboard.class); - startActivity(intent); - return true; - - }else if (doc_password == "" && !mPasswordView.getText().toString().equals("")) { - try { - Map doc_credentials = (Map) properties.get("credentials"); - AndroidDecrypter adc = new AndroidDecrypter(); - if(adc.AndroidDecrypter(doc_loginId, mPasswordView.getText().toString(), doc_credentials.get("value").toString())){ - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_username", (String) properties.get("login")); - editor.putString("pf_password", (String) properties.get("password")); - editor.putString("pf_usercouchId", (String) properties.get("_id")); - editor.putString("pf_userfirstname", (String) properties.get("firstName")); - editor.putString("pf_userlastname", (String) properties.get("lastName")); - editor.putString("pf_usergender", (String) properties.get("Gender")); - editor.putString("pf_lastVisitDate", doc_lastVisit); - try { - String noOfVisits = properties.get("visits").toString(); - editor.putInt("pf_uservisits_Int", (Integer.parseInt(noOfVisits) + totalVisits((String) properties.get("_id")))); - } catch (Exception err) { - - } - Set stgSet = settings.getStringSet("pf_userroles", new HashSet()); - ArrayList roleList = (ArrayList) properties.get("roles"); - for (int cnt = 0; cnt < roleList.size(); cnt++) { - stgSet.add(String.valueOf(roleList.get(cnt))); - } - editor.putStringSet("pf_userroles", stgSet); - editor.commit(); - Log.e("MYAPP", " Data Login Id: " + doc_loginId + " Password: " + doc_password); - Intent intent = new Intent(this, Dashboard.class); - startActivity(intent); - return true; - - } - - ////doc_credentials.get("salt").toString()); - ///doc_credentials.get("value").toString() - } catch (Exception err) { - Log.e("MYAPP", " Encryption Err " + err.getMessage()); - } - - } else{ - return false; - } - } - - } - db.close(); - return false; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean getSystemInfo(){ - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("configurations"); - Query orderedQuery = chViews.CreateLoginByIdView(db).createQuery(); - orderedQuery.setDescending(true); - QueryEnumerator results = orderedQuery.run(); - for (Iterator it = results; it.hasNext();) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - String Server_name = (String) properties.get("name"); - String Server_nationName = (String) properties.get("nationName"); - String Server_version = (String) properties.get("version"); - - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_server_name", Server_name); - editor.putString("pf_server_nation", Server_nationName); - editor.putString("pf_server_version", Server_version); - - } - db.close(); - return false; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * Represents an asynchronous login/registration task used to authenticate - * the user. - */ - public class UserLoginTask extends AsyncTask { - - private final String mEmail; - private final String mPassword; - - UserLoginTask(String email, String password) { - mEmail = email; - mPassword = password; - } - - @Override - protected Boolean doInBackground(Void... params) { - // TODO: attempt authentication against a network service. - - try { - // Simulate network access. - ///Thread.sleep(1000); - - return authenticateUser(); - - } catch (Exception e) { - Log.v("myLoginTag","Login Error "+e.getLocalizedMessage()); - return false; - } - - // TODO: register the new account here. - //return false; - } - - @Override - protected void onPostExecute(final Boolean success) { - mAuthTask = null; - showProgress(false); - - if (success) { - finish(); - } else { - mPasswordView.setError(getString(R.string.error_incorrect_password)); - mPasswordView.requestFocus(); - } - } - - @Override - protected void onCancelled() { - mAuthTask = null; - showProgress(false); - } - } - public void getSyncURLDialog(){ - // custom dialog - final Dialog dialog = new Dialog(context); - dialog.setContentView(R.layout.newsetup_dialog_welcome); - dialog.setTitle("WELCOME"); - dialog.setCancelable(false); - - - final EditText txtSuncURL = (EditText)dialog.findViewById(R.id.txtNewSyncURL); - txtSuncURL.setText(sys_oldSyncServerURL); - Button dialogButton = (Button) dialog.findViewById(R.id.btnNewSaveSyncURL); - dialogButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - sys_oldSyncServerURL = txtSuncURL.getText().toString(); - - SharedPreferences.Editor editor = settings.edit(); - editor.putString("pf_sysncUrl", sys_oldSyncServerURL); - editor.commit(); - - ///dialog.dismiss(); - Intent intent = new Intent(context,NewSync.class); - startActivity(intent); - ///dialog.getOwnerActivity().setVisible(false); - } - }); - Button btnCloseWindow = (Button) dialog.findViewById(R.id.btnCloseDialog); - btnCloseWindow.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - - - dialog.show(); - - } - public int totalVisits(String memberId){ - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - Database visitHolder; - int doc_noOfVisits; - - - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - visitHolder = manager.getDatabase("visits"); - Document retrievedDocument = visitHolder.getExistingDocument(memberId); - if(retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if(properties.containsKey("noOfVisits")){ - doc_noOfVisits = (int) properties.get("noOfVisits") ; - doc_lastVisit = (String) properties.get("lastVisits"); - /// Increase No Of visits by 1 - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - doc_noOfVisits += 1; - newProperties.put("noOfVisits", doc_noOfVisits); - newProperties.put("lastVisits", todaysDate()); - retrievedDocument.putProperties(newProperties); - return doc_noOfVisits; - } - } - else{ - Document newdocument = visitHolder.getDocument(memberId); - Map newProperties = new HashMap(); - newProperties.put("noOfVisits", 1); - doc_lastVisit = todaysDate(); - newProperties.put("lastVisits", doc_lastVisit); - newdocument.putProperties(newProperties); - return 1; - } - - - }catch(Exception err){ - Log.e("VISITS", "ERR : " +err.getMessage()); - - } - - return 0; - - } - public String todaysDate(){ - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Calendar cal = Calendar.getInstance(); - System.out.println(dateFormat.format(cal.getTime())); - return dateFormat.format(cal.getTime()); - - } -} - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/LruBitmapCache.java b/app/src/main/java/pbell/offline/ole/org/pbell/LruBitmapCache.java deleted file mode 100644 index 535b00a..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/LruBitmapCache.java +++ /dev/null @@ -1,36 +0,0 @@ -package pbell.offline.ole.org.pbell; -import com.android.volley.toolbox.ImageLoader.ImageCache; -import android.graphics.Bitmap; -import android.support.v4.util.LruCache; - -public class LruBitmapCache extends LruCache implements ImageCache { - public static int getDefaultLruCacheSize() { - final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); - final int cacheSize = maxMemory / 8; - - return cacheSize; - } - - public LruBitmapCache() { - this(getDefaultLruCacheSize()); - } - - public LruBitmapCache(int sizeInKiloBytes) { - super(sizeInKiloBytes); - } - - @Override - protected int sizeOf(String key, Bitmap value) { - return value.getRowBytes() * value.getHeight() / 1024; - } - - @Override - public Bitmap getBitmap(String url) { - return get(url); - } - - @Override - public void putBitmap(String url, Bitmap bitmap) { - put(url, bitmap); - } -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/MainActivity.java b/app/src/main/java/pbell/offline/ole/org/pbell/MainActivity.java deleted file mode 100644 index d0ca49a..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/MainActivity.java +++ /dev/null @@ -1,184 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.support.design.widget.TabLayout; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; - -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.view.ViewPager; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import android.widget.ListView; - -@SuppressWarnings("ALL") -public class MainActivity extends AppCompatActivity { - - /** - * The {@link android.support.v4.view.PagerAdapter} that will provide - * fragments for each of the sections. We use a - * {@link FragmentPagerAdapter} derivative, which will keep every - * loaded fragment in memory. If this becomes too memory intensive, it - * may be best to switch to a - * {@link android.support.v4.app.FragmentStatePagerAdapter}. - */ - private SectionsPagerAdapter mSectionsPagerAdapter; - private ListView libraryList; - - /** - * The {@link ViewPager} that will host the section contents. - */ - private ViewPager mViewPager; - TabFragment1 tab1= new TabFragment1(); - TabFragment2 tab2= new TabFragment2(); - TabFragment3 tab3= new TabFragment3(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); - - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - // Create the adapter that will return a fragment for each of the three - // primary sections of the activity. - mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - - // Set up the ViewPager with the sections adapter. - mViewPager = (ViewPager) findViewById(R.id.container); - mViewPager.setAdapter(mSectionsPagerAdapter); - - TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); - tabLayout.setupWithViewPager(mViewPager); - - ///mViewPager. - - - /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) - .setAction("Action", null).show(); - } - });*/ - - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.menu_main, menu); - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - // Handle action bar item clicks here. The action bar will - // automatically handle clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - int id = item.getItemId(); - - //noinspection SimplifiableIfStatement - if (id == R.id.action_syncserverUrl) { - return true; - }else if (id == R.id.action_about) { - return true; - }else if (id == R.id.action_help) { - return true; - }else if (id == R.id.action_profile) { - return true; - } - - return super.onOptionsItemSelected(item); - } - - - - - /** - * A {@link FragmentPagerAdapter} that returns a fragment corresponding to - * one of the sections/tabs/pages. - */ - public class SectionsPagerAdapter extends FragmentPagerAdapter { - - public SectionsPagerAdapter(FragmentManager fm) { - - super(fm); - } - - @Override - public Fragment getItem(int position) { - - switch (position) { - case 0: - return tab1; - case 1: - return tab2; - case 2: - return tab3; - default: - return null; - } - } - - @Override - public int getCount() { - // Show 3 total pages. - return 3; - } - - @Override - public CharSequence getPageTitle(int position) { - switch (position) { - case 0: - return "Library"; - case 1: - return "Courses Progress"; - case 2: - return "Meetups"; - } - return null; - } - } - - /** - * A placeholder fragment containing a simple view. - */ - public static class PlaceholderFragment extends Fragment { - /** - * The fragment argument representing the section number for this - * fragment. - */ - private static final String ARG_SECTION_NUMBER = "section_number"; - - /** - * Returns a new instance of this fragment for the given section - * number. - */ - public static PlaceholderFragment newInstance(int sectionNumber) { - PlaceholderFragment fragment = new PlaceholderFragment(); - Bundle args = new Bundle(); - args.putInt(ARG_SECTION_NUMBER, sectionNumber); - fragment.setArguments(args); - return fragment; - } - - public PlaceholderFragment() { - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_main, container, false); - return rootView; - } - } -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/MemberListDownloadRes.java b/app/src/main/java/pbell/offline/ole/org/pbell/MemberListDownloadRes.java deleted file mode 100644 index 1d4588c..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/MemberListDownloadRes.java +++ /dev/null @@ -1,520 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.app.Activity; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.os.AsyncTask; -import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.ListView; -import android.widget.Switch; -import android.widget.TextView; -import android.widget.Toast; - -import com.couchbase.lite.Attachment; -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; -import com.couchbase.lite.replicator.Replication; -import com.github.kittinunf.fuel.Fuel; -import com.github.kittinunf.fuel.core.FuelError; -import com.github.kittinunf.fuel.core.Request; -import com.github.kittinunf.fuel.core.Response; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.net.URL; -import java.text.Collator; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@SuppressWarnings("ALL") -public class MemberListDownloadRes extends AppCompatActivity { - - MyCustomAdapter dataAdapter = null; - String[] str_memberIdList,str_memberNameList,str_memberLoginIdList; - int[] str_memberResourceNo; - String[] array_SelectedMembers; - ArrayList lst; - - CouchViews chViews = new CouchViews(); - final Context context = this; - EditText inputSearch; - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate= ""; - Object[] sys_membersWithResource; - AndroidContext androidContext; - - Replication pull; - Database dbResources; - int syncCnt,resourceNo=0; - - Activity mActivity; - ProgressDialog mydialog; - AlertDialog closeDialogue; - - - boolean synchronizing = false; - boolean wipeClearn =false; - - - JSONObject jsonData; - int resourceCntr,attachmentLength; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_member_list_download_res); - - - androidContext = new AndroidContext(this); - // Restore preferences - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - - Set mwr = settings.getStringSet("membersWithResource",null); - try{ - sys_membersWithResource = mwr.toArray(); - Log.e("MYAPP", " membersWithResource = "+sys_membersWithResource.length); - - }catch(Exception err){ - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - - - Bundle b=this.getIntent().getExtras(); - str_memberNameList=b.getStringArray("memberNameList"); - str_memberIdList=b.getStringArray("memberIdList"); - str_memberResourceNo=b.getIntArray("memberResourceNo"); - str_memberLoginIdList=b.getStringArray("memberLoginIdList"); - - inputSearch = (EditText) findViewById(R.id.inputSearch); - mydialog = new ProgressDialog(MemberListDownloadRes.this); - - - - - - /// - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("Resources synchronized successfully. ") - .setCancelable(false) - .setPositiveButton("Okay", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - finish(); - } - }); - /* .setNegativeButton("No", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.cancel(); - } - });*/ - closeDialogue = builder.create(); - - Switch sw_wipeClean = (Switch) findViewById(R.id.switch1); - sw_wipeClean.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - wipeClearn = isChecked; - ///Log.v("Switch State=", ""+isChecked); - } - }); - - displayListView(); - - checkButtonClick(); - - final ArrayList memberList = new ArrayList(); - inputSearch.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { - dataAdapter.getFilter().filter(cs.toString()); - } - - @Override - public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) { - // TODO Auto-generated method stub - } - - @Override - public void afterTextChanged(Editable arg0) { - // TODO Auto-generated method stub - } - }); - - } - - private void displayListView() { - ArrayList countryList = new ArrayList(); - Members member; - for(int cnt=0;cnt parent, View view, int position, long id) { - // When clicked, show a toast with the TextView text - Members country = (Members) parent.getItemAtPosition(position); - Toast.makeText(getApplicationContext(), "Clicked on Row: " + country.getName(),Toast.LENGTH_LONG).show(); - } - }); - - } - - private class MyCustomAdapter extends ArrayAdapter { - private ArrayList memberList; - public MyCustomAdapter(Context context, int textViewResourceId,ArrayList countryList) { - super(context, textViewResourceId, countryList); - this.memberList = new ArrayList(); - this.memberList.addAll(countryList); - } - - private class ViewHolder { - TextView code; - CheckBox name; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - - ViewHolder holder = null; - Log.v("ConvertView", String.valueOf(position)); - - if (convertView == null) { - LayoutInflater vi = (LayoutInflater)getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - convertView = vi.inflate(R.layout.members_list, null); - - holder = new ViewHolder(); - holder.code = (TextView) convertView.findViewById(R.id.code); - holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1); - convertView.setTag(holder); - - holder.name.setOnClickListener( new View.OnClickListener() { - public void onClick(View v) { - CheckBox cb = (CheckBox) v ; - Members member = (Members) cb.getTag(); - member.setSelected(cb.isChecked()); - } - }); - } - else { - holder = (ViewHolder) convertView.getTag(); - } - - Members member = memberList.get(position); - holder.code.setText(" (" + member.getCode() + ") [ "+member.getResNo()+ " ] "); - holder.name.setText(member.getName()); - try{ - if (Arrays.asList(sys_membersWithResource).contains(member.getId())) { - holder.name.setChecked(true); - }else{ - holder.name.setChecked(false); - } - }catch(Exception err){ - holder.name.setChecked(false); - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - holder.name.setTag(member); - - return convertView; - - } - - } - - private void checkButtonClick() { - Button myButton = (Button) findViewById(R.id.findSelected); - myButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ArrayList countryList = dataAdapter.memberList; - int selectedCntr=0; - for(int i=0;i set = new HashSet(Arrays.asList(array_SelectedMembers)); - editor.putStringSet("membersWithResource", set); - editor.commit(); - - CheckShelfForResources(); - } - }); - } - - public void CheckShelfForResources(){ - this.lst = new ArrayList(); - this.lst.clear(); - resourceNo=0; - for(int cnt=0;cnt0) { - if(wipeClearn) { - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - dbResources = manager.getExistingDatabase("resources"); - dbResources.delete(); - Log.e("MyCouch", " Deleted Resources DB"); - } catch (Exception err) { - Log.e("MyCouch", "Delete Error " + err.getLocalizedMessage()); - } - } - - closeDialogue.show(); - mActivity = MemberListDownloadRes.this; - mydialog.setMessage("Downloading, please wait .... "); - mydialog.show(); - - final AsyncTask execute = new TestAsyncPull().execute(); - Thread th = new Thread(new Runnable() { - private long startTime = System.currentTimeMillis(); - - public void run() { - while (synchronizing) { - runOnUiThread(new Runnable() { - @Override - public void run() { - Log.d("runOnUiThread", "running"); - mydialog.setMessage("Downloading, please wait .... " + (syncCnt + 1)); - if (!synchronizing) { - - } - - } - }); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - } - }); - th.start(); - }else{ - mydialog.dismiss(); - } - } - - public void LoadShelfResourceList(String memId) { - String memberId = memId; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("shelf"); - Query orderedQuery = chViews.ReadShelfByIdView(db).createQuery(); - orderedQuery.setDescending(true); - //orderedQuery.setStartKey(memberId); - //orderedQuery.setLimit(0); - QueryEnumerator results = orderedQuery.run(); - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - if(memberId.equals((String) properties.get("memberId"))) { - this.lst.add((String) properties.get("resourceId")); - resourceNo++; - } - } - ///Log.d("PreExceute","Items "+ db.getDocumentCount()); - - db.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - class TestAsyncPull extends AsyncTask { - protected void onPreExecute (){ - synchronizing = true; - Log.d("PreExceute","On pre Exceute......"); - } - - protected Boolean doInBackground(final String... args) { - Log.d("DoINBackGround","On doInBackground..."); - final Manager manager ; - final Database res_Db; - final Fuel ful = new Fuel(); - jsonData = null; - attachmentLength= -1; - try { - URL url = new URL(sys_oldSyncServerURL+"/resources"); - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - dbResources = manager.getDatabase("resources"); - res_Db = manager.getExistingDatabase("resources"); - pull = dbResources.createPullReplication(url); - pull.setFilter("apps/by_resource"); - Map params = new HashMap(); - params.put("_id", lst.get(syncCnt)); - //Log.e("MyCouch", " Resource ID "+ lst.get(syncCnt)); - pull.setFilterParams(params); - pull.setContinuous(false); - ////pull.setAuthenticator(new BasicAuthenticator(userName, userPw)); - pull.addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - if(pull.isRunning()){ - Log.e("MyCouch", " "+event.getChangeCount()); - Log.e("MyCouch", " Document Count "+dbResources.getDocumentCount()); - }else { - Log.e("Finished", ""+dbResources.getDocumentCount()); - ////// CHECK REMOTE ATTACHMENT FILE SIZE VS LOCAL ATTACHMENT FILE SIZE (length) - Document res_doc = res_Db.getExistingDocument(lst.get(syncCnt)); - final List attmentNames = res_doc.getCurrentRevision().getAttachmentNames(); - /// IF local document has attachments - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - resourceCntr = cnt; - Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment((String) attmentNames.get(cnt)); - /// - ful.get(sys_oldSyncServerURL+"/resources/"+lst.get(syncCnt)).responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - jsonData = new JSONObject(s); - //Log.e("MyCouch", "-- "+jsonData); - } catch (JSONException e) { - e.printStackTrace(); - } - try { - JSONObject jsob = jsonData.getJSONObject("_attachments"); - JSONObject jsoAttachments = jsob.getJSONObject((String) attmentNames.get(resourceCntr)); - attachmentLength = jsoAttachments.getInt("length"); - Log.e("MyCouch", "Attachment Object Content "+jsoAttachments); - } catch (JSONException e) { - e.printStackTrace(); - } - } - @Override - public void failure(Request request, Response response, FuelError fuelError) { - Log.e("MyCouch", " "+fuelError); - - } - }); - /// If local attachment length is greater or equal to remote attachment, continue - /// Else run the replication again - if(fileAttachment.getLength() >= attachmentLength){ - Log.e("MyCouch", "Local = "+fileAttachment.getLength() + " Remote = " +attachmentLength); - if(syncCnt < (lst.size()-1)){ - syncCnt++; - new TestAsyncPull().execute(); - }else{ - if (synchronizing){ - mydialog.dismiss(); - } - synchronizing = false; - } - - }else{ - Log.e("MyCouch", "Local = "+fileAttachment.getLength() + " Remote = " +attachmentLength); - - new TestAsyncPull().execute(); - } - } - } else if(syncCnt < (lst.size()-1)){ - syncCnt++; - new TestAsyncPull().execute(); - }else{ - if (synchronizing){ - mydialog.dismiss(); - } - synchronizing = false; - } - ////////////////////// - - } - } - }); - pull.start(); - - - } catch (Exception e) { - Log.e("MyCouch", " "+" Cannot create database", e); - return false; - - } - return true; - } - protected void onProgressUpdate(Integer...a){ - Log.d("onProgress","You are in progress update ... " + a[0]); - } - - protected void onPostExecute(final Boolean success) { - if (success){ - Log.d("MyCouch","Download Triggered"); - }else{ - Log.d("OnPostExec",""); - } - } - } - -} - - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Members.java b/app/src/main/java/pbell/offline/ole/org/pbell/Members.java deleted file mode 100644 index a1475f3..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Members.java +++ /dev/null @@ -1,144 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.Filter; -import android.widget.Filterable; - -import java.util.ArrayList; - -/** - * Created by leonardmensah on 24/05/16. - */ -@SuppressWarnings("ALL") -public class Members extends BaseAdapter implements Filterable { - - String code = null; - String name = null; - String id = null; - int resNo = 0; - boolean selected = false; - - - private ArrayList mOriginalValues; // Original Values - private ArrayList mDisplayedValues; - - public Members(String code, String name,String id,int resNo, boolean selected) { - super(); - this.code = code; - this.name = name; - this.id = id; - this.resNo = resNo; - this.selected = selected; - } - - public String getCode() { - return code; - } - public void setCode(String code) { - this.code = code; - } - public String getName() { - return name; - } - public String getName(int position) { - return name; - } - public void setName(String name) { - this.name = name; - } - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - - public int getResNo() { - return resNo; - } - public void setResNo(int id) { - this.resNo = resNo; - } - - public boolean isSelected() { - return selected; - } - public void setSelected(boolean selected) { - this.selected = selected; - } - - @Override - public int getCount() { - return 0; - } - - @Override - public Object getItem(int position) { - return null; - } - - @Override - public long getItemId(int position) { - return 0; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - return null; - } - - @Override - public Filter getFilter() { - Filter filter = new Filter() { - - @SuppressWarnings("unchecked") - @Override - protected void publishResults(CharSequence constraint,FilterResults results) { - - mDisplayedValues = (ArrayList) results.values; // has the filtered values - notifyDataSetChanged(); // notifies the data with new filtered values - } - - @Override - protected FilterResults performFiltering(CharSequence constraint) { - FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values - ArrayList FilteredArrList = new ArrayList(); - - if (mOriginalValues == null) { - mOriginalValues = new ArrayList(mDisplayedValues); // saves the original data in mOriginalValues - } - - /******** - * - * If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values - * else does the Filtering and returns FilteredArrList(Filtered) - * - ********/ - if (constraint == null || constraint.length() == 0) { - - // set the Original result to return - results.count = mOriginalValues.size(); - results.values = mOriginalValues; - } else { - constraint = constraint.toString().toLowerCase(); - for (int i = 0; i < mOriginalValues.size(); i++) { - String data = mOriginalValues.get(i).getName(); - if (data.toLowerCase().startsWith(constraint.toString())) { - FilteredArrList.add(new Members(mOriginalValues.get(i).getCode(),mOriginalValues.get(i).getName(),mOriginalValues.get(i).getId(),mOriginalValues.get(i).getResNo(),false)); - } - } - // set the Filtered result to return - results.count = FilteredArrList.size(); - results.values = FilteredArrList; - } - return results; - } - }; - return filter; - } - -} - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/MyLibraryArrayAdapter.java b/app/src/main/java/pbell/offline/ole/org/pbell/MyLibraryArrayAdapter.java deleted file mode 100644 index 2c99652..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/MyLibraryArrayAdapter.java +++ /dev/null @@ -1,132 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.content.Context; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.ImageView; -import android.widget.TextView; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by leonardmensah on 17/05/16. - */ -@SuppressWarnings("ALL") -public class MyLibraryArrayAdapter extends ArrayAdapter { - private final Context context; - ///private final String[] values; - private ArrayList data; - //Datahelper dh; - - public TextView text; - public TextView text1; - public TextView textWide; - public ImageView image; - public Map map; - - - ListModel tempValues=null; - int i=0; - - public MyLibraryArrayAdapter(Context context, int textViewResourceId, ArrayList d) { - super(context, textViewResourceId, d); - this.context = context; - //this.values = values; - this.data=d; - map = new HashMap(); - map.put("image1", R.drawable.pdf); - map.put("image2", R.drawable.web); - map.put("image3", R.drawable.mp3); - map.put("image4", R.drawable.video); - // dh = new DataHelper(getApplicationContext()); - } - - /*@Override - public View getView(final int position, final View convertView, ViewGroup parent) { - LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - View vi = convertView; - CustomAdapter.ViewHolder holder; - - if(convertView==null){ - holder = new CustomAdapter.ViewHolder(); - vi = inflater.inflate(R.layout.tabitem, null); - - ///View rowView = inflater.inflate(R.layout.tabitem, parent, false); - holder.text = (TextView) vi.findViewById(R.id.text); - holder.text1 = (TextView) vi.findViewById(R.id.text1); - holder.image = (ImageView) vi.findViewById(R.id.image); - - vi.setTag(holder); - } - else { - holder = (CustomAdapter.ViewHolder) vi.getTag(); - } - - if(data.size()<=0) - { - text.setText("No Data"); - - } - else - { - - tempValues=null; - tempValues = ( ListModel ) data.get( position ); - - - holder.text.setText( tempValues.getTitle() ); - holder.text1.setText( tempValues.getDescription() ); - holder.image.setImageResource(map.get("image3")); - vi.setTag(holder); - Log.e("MYAPP", "Added Id = "+tempValues.getTitle()); - - - } - - - return vi; - } - */ - - public View getView(final int position, View convertView, ViewGroup parent) { - LayoutInflater minflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - final ViewHolder mHolder; - if (convertView == null) { - convertView = minflater.inflate(R.layout.tabitem, null); - mHolder = new ViewHolder(); - - mHolder.mText=(TextView) convertView.findViewById(R.id.text); - mHolder.mText1=(TextView) convertView.findViewById(R.id.text1); - mHolder.mImage=(ImageView) convertView.findViewById(R.id.image); - - //convertView.setTag(mHolder); - - tempValues=null; - tempValues = ( ListModel ) data.get( position ); - mHolder.mText.setText( tempValues.getTitle() ); - mHolder.mText1.setText( tempValues.getDescription() ); - mHolder.mImage.setImageResource(map.get("image3")); - - ///convertView.setTag(mHolder); - Log.e("MYAPP", "Added Id = "+tempValues.getTitle()); - - } else { - /// mHolder = (ViewHolder) convertView.getTag(); - } - - return convertView; - } - - private class ViewHolder { - private TextView mText; - private TextView mText1; - private ImageView mImage; - - } - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/MyPdfViewerActivity.java b/app/src/main/java/pbell/offline/ole/org/pbell/MyPdfViewerActivity.java deleted file mode 100644 index 2360dfb..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/MyPdfViewerActivity.java +++ /dev/null @@ -1,31 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 03/06/16. - */ -import net.sf.andpdf.pdfviewer.PdfViewerActivity; -import android.os.Bundle; - -@SuppressWarnings("ALL") -public class MyPdfViewerActivity extends PdfViewerActivity { - - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // TODO Auto-generated method stub - } - - public int getPreviousPageImageResource() { return R.drawable.left_arrow; } - public int getNextPageImageResource() { return R.drawable.right_arrow; } - public int getZoomInImageResource() { return R.drawable.zoom_in; } - public int getZoomOutImageResource() { return R.drawable.zoom_out; } - public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; } - public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; } - public int getPdfPasswordEditField() { return R.id.etPassword; } - public int getPdfPasswordOkButton() { return R.id.btOK; } - public int getPdfPasswordExitButton() { return R.id.btExit; } - public int getPdfPageNumberEditField() { return R.id.pagenum_edit; } - -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/NewSync.java b/app/src/main/java/pbell/offline/ole/org/pbell/NewSync.java deleted file mode 100644 index 36995b9..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/NewSync.java +++ /dev/null @@ -1,502 +0,0 @@ -package pbell.offline.ole.org.pbell; - - -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.AsyncTask; -import android.os.Bundle; -import android.support.design.widget.FloatingActionButton; -import android.support.design.widget.Snackbar; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.text.method.ScrollingMovementMethod; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.CompoundButton; -import android.widget.Switch; -import android.widget.TextView; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; -import com.couchbase.lite.auth.Authenticator; -import com.couchbase.lite.auth.BasicAuthenticator; -import com.couchbase.lite.replicator.Replication; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -@SuppressWarnings("ALL") -public class NewSync extends AppCompatActivity { - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate= ""; - - CouchViews chViews = new CouchViews(); - - Button btnClose; - - TextView tv; - View clcview; - String message=""; - //////Replication push,pull; - FloatingActionButton fab; - Boolean wipeClearn =false; - final Context context = this; - String[] databaseList = {"members","membercourseprogress","meetups","usermeetups","assignments", - "calendar","groups","invitations","configurations","requests","shelf","languages"}; - - Replication[] push = new Replication[databaseList.length]; - Replication[] pull= new Replication[databaseList.length]; - - Database[] db = new Database[databaseList.length]; - Manager[] manager = new Manager[databaseList.length]; - - ProgressDialog[] progressDialog = new ProgressDialog[databaseList.length]; - - AndroidContext androidContext; - int syncCnt=0; - Button btnStartSyncPush,btnStartSyncPull; - String[] str_memberIdList,str_memberNameList,str_memberLoginIdList; - int[] str_memberResourceNo; - - Boolean synchronizingPull=true; - Boolean openMemberList = false; - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_new_sync); - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_New); - setSupportActionBar(toolbar); - - androidContext = new AndroidContext(this); - // Restore preferences - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - //tv = (TextView)findViewById(R.id.txtLogConsole); - - TextView lblSyncURL = (TextView)findViewById(R.id.lblSyncSyncUrl_New); - lblSyncURL.setText(sys_oldSyncServerURL); - - tv = (TextView)findViewById(R.id.txtLogConsole_New); - tv.setMovementMethod(new ScrollingMovementMethod()); - - btnClose = (Button)findViewById(R.id.btnCloseWindow); - btnClose.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - finish(); - } - - }); - - btnStartSyncPull = (Button)findViewById(R.id.btnstartSyncPull_New); - btnStartSyncPull.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - syncCnt=0; - tv.setText(" Sync Started, please wait ... " ); - tv.scrollTo(0,tv.getTop()); - syncNotifier(); - ///new TestAsyncPull().execute(); - } - - }); - - Switch sw_wipeClean = (Switch) findViewById(R.id.swWipeClean_New); - sw_wipeClean.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - wipeClearn = isChecked; - ///Log.v("Switch State=", ""+isChecked); - } - }); - - - fab = (FloatingActionButton) findViewById(R.id.checkConnection_New); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - clcview = view; - try { - if (checkConnectionURL()) { - fab.setVisibility(View.INVISIBLE); - Snackbar.make(clcview, "Checking connection to "+sys_oldSyncServerURL +".... please wait", Snackbar.LENGTH_INDEFINITE) - .setAction("Action", null).show(); - new TryDownloadTask().execute(sys_oldSyncServerURL); - - } else { - - } - }catch(Exception e) { - Log.v("myErrorTag","Error "+e.getLocalizedMessage()); - - } - } - }); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - } - - public void triggerMemberResourceDownload(){ - ///if(!synchronizingPull) { - //synchronizingPull = true; - Log.e("MyCouch", "Sync Variable false"); - if (BuildMemberListArray()) { - for (int cnt = 0; cnt < str_memberIdList.length; cnt++) { - ArrayList strings = CheckShelfForResources(cnt); - } - Bundle b = new Bundle(); - b.putStringArray("memberNameList", str_memberNameList); - b.putStringArray("memberIdList", str_memberIdList); - b.putIntArray("memberResourceNo", str_memberResourceNo); - b.putStringArray("memberLoginIdList", str_memberLoginIdList); - Intent intent = new Intent(this, MemberListDownloadRes.class); - intent.putExtras(b); - startActivity(intent); - } else { - Log.e("MyCouch", "triggerMemberResourceDownload function error"); - } - openMemberList = false; - synchronizingPull = false; - - ///}else{ - // Log.e("MyCouch", "Sync Variable True"); - //} - } - - public void syncNotifier(){ - final AsyncTask execute = new TestAsyncPull().execute(); - Log.e("MyCouch", "syncNotifier Running"); - final Thread th = new Thread(new Runnable() { - private long startTime = System.currentTimeMillis(); - public void run() { - while (synchronizingPull) { - runOnUiThread(new Runnable() { - @Override - public void run() { - if(openMemberList) { - triggerMemberResourceDownload(); - openMemberList=false; - } - Log.d("runOnUiThread", "running"); - //mydialog.setMessage("Downloading, please wait .... " + (syncCnt + 1)); - } - }); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - th.start(); - } - - private boolean checkConnectionURL() { - ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); - if (networkInfo != null && networkInfo.isConnected()) { - Log.v("myErrorTag","Network Connected"); - return true; - // fetch data - } else { - - Log.v("myErrorTag","Network Not Connected"); - return false; - } - - } - - private class TryDownloadTask extends AsyncTask { - @Override - protected String doInBackground(String... urls) { - - // params comes from the execute() call: params[0] is the url. - InputStream is = null; - int response=0; - try { - URL url = new URL(sys_oldSyncServerURL); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setReadTimeout(5000 /* milliseconds */); - conn.setConnectTimeout(10000 /* milliseconds */); - conn.setRequestMethod("GET"); - conn.setDoInput(true); - // Starts the query - conn.connect(); - response = conn.getResponseCode(); - Log.d("Responce", "The response is: " + response); - is = conn.getInputStream(); - return ""; - }catch (Exception err) { - - }finally - { - if(response!=200){ - displayDownMesage(false); - }else{ - displayDownMesage(true); - } - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return ""; - } - } - // onPostExecute displays the results of the AsyncTask. - @Override - protected void onPostExecute(String result) { - /// textView.setText(result); - } - } - - public void displayDownMesage(boolean status){ - if(status){ - Snackbar.make(clcview, "Connection to established successful", Snackbar.LENGTH_LONG) - .setAction("Action", null).show(); - }else{ - Snackbar.make(clcview, "Sorry , server was unreachable, check url and device connection", Snackbar.LENGTH_LONG) - .setAction("Action", null).show(); - } - } - - class TestAsyncPull extends AsyncTask { - protected void onPreExecute (){ - Log.d("PreExceute","On pre Exceute......"); - } - - protected String doInBackground(Void...arg0) { - Log.d("DoINBackGround","On doInBackground..."); - synchronizingPull=true; - pull= new Replication[databaseList.length]; - db = new Database[databaseList.length]; - manager = new Manager[databaseList.length]; - try { - manager[syncCnt] = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - if(wipeClearn){ - try{ - db[syncCnt] = manager[syncCnt].getExistingDatabase(databaseList[syncCnt]); - db[syncCnt].delete(); - }catch(Exception err){ - Log.e("MyCouch", "Delete Error "+ err.getLocalizedMessage()); - } - } - - db[syncCnt] = manager[syncCnt].getDatabase(databaseList[syncCnt]); - URL url = new URL(sys_oldSyncServerURL+"/"+databaseList[syncCnt]); - pull[syncCnt]= db[syncCnt].createPullReplication(url); - pull[syncCnt].setContinuous(false); - pull[syncCnt].addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - if(pull[syncCnt] .isRunning()){ - Log.e("MyCouch", databaseList[syncCnt]+" "+event.getChangeCount()); - message = String.valueOf(event.getChangeCount()); - }else { - Log.e("Finished", databaseList[syncCnt]+" "+ db[syncCnt].getDocumentCount()); - if(syncCnt < (databaseList.length-2)){ - syncCnt++; - new TestAsyncPull().execute(); - }else{ - Log.e("MyCouch","Sync Completed"); - if(!openMemberList) { - openMemberList = true; - } - //triggerMemberResourceDownload(); - ///synchronizingPull=true; - } - - } - } - }); - pull[syncCnt].start(); - - } catch (Exception e) { - Log.e("MyCouch", databaseList[syncCnt]+" "+" Cannot create database", e); - - - } - publishProgress(syncCnt); - return "You are at PostExecute"; - } - protected void onProgressUpdate(Integer...a){ - Log.d("onProgress","You are in progress update ... " + a[0]); - if(syncCnt != (databaseList.length-2)){ - tv.setText(tv.getText().toString()+" \n Pulled "+databaseList[syncCnt]+ "\n Pulling "+ databaseList[syncCnt+1]+"....." ); - tv.scrollTo(0,(tv.getLineCount()*20+syncCnt)); - - tv.requestFocus(); - }else{ - tv.setText(tv.getText().toString()+" \n Pulled "+ databaseList[syncCnt] ); - tv.scrollTo(0,(tv.getLineCount()*20)+syncCnt); - - tv.requestFocus(); - } - } - - protected void onPostExecute(String result) { - Log.d("OnPostExec",""+result); - } - } - - class TestAsyncPush extends AsyncTask { - protected void onPreExecute (){ - Log.d("PreExceute","On pre Exceute......"); - } - - protected String doInBackground(Void...arg0) { - Log.d("DoINBackGround","On doInBackground..."); - push = new Replication[databaseList.length]; - db = new Database[databaseList.length]; - manager = new Manager[databaseList.length]; - try { - manager[syncCnt] = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - db[syncCnt] = manager[syncCnt].getDatabase(databaseList[syncCnt]); - URL url = new URL(sys_oldSyncServerURL+"/"+databaseList[syncCnt]); - - push[syncCnt]= db[syncCnt].createPushReplication(url); - push[syncCnt].setContinuous(false); - Authenticator auth = new BasicAuthenticator("appuser", "appuser"); - push[syncCnt].setAuthenticator(auth); - push[syncCnt].addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - if(push[syncCnt] .isRunning()){ - Log.e("MyCouch", databaseList[syncCnt]+" "+event.getChangeCount()); - }else { - Log.e("Finished", databaseList[syncCnt]+" "+ db[syncCnt].getDocumentCount()); - if(syncCnt < (databaseList.length-2)){ - syncCnt++; - new TestAsyncPush().execute(); - } - } - } - }); - push[syncCnt].start(); - } catch (Exception e) { - Log.e("MyCouch", databaseList[syncCnt]+" "+" Cannot create database", e); - - } - - publishProgress(syncCnt); - return "You are at PostExecute"; - } - - protected void onProgressUpdate(Integer...a){ - Log.d("onProgress","You are in progress update ... " + a[0]); - if(syncCnt != (databaseList.length-2)){ - tv.setText(tv.getText().toString()+" \n Pushed "+databaseList[syncCnt]+ "\n Pushing "+ databaseList[syncCnt+1]+"....." ); - tv.scrollTo(0,(tv.getLineCount()*20+syncCnt)); - tv.requestFocus(); - }else{ - tv.setText(tv.getText().toString()+" \n Pushed "+ databaseList[syncCnt] ); - tv.scrollTo(0,(tv.getLineCount()*20)+syncCnt); - tv.requestFocus(); - } - - - } - protected void onPostExecute(String result) { - - Log.d("OnPostExec",""+result); - - } - } - - public ArrayList CheckShelfForResources(int index) { - int array_index = index; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("shelf"); - Query orderedQuery = chViews.ReadShelfByIdView(db).createQuery(); - orderedQuery.setDescending(true); - //Todo startKey and EndKey generate inaccurate result - ///orderedQuery.setStartKey(str_memberIdList[array_index]); - //orderedQuery.setLimit(0); - ArrayList lst = new ArrayList(); - QueryEnumerator results = orderedQuery.run(); - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - if(str_memberIdList[array_index].equals((String)properties.get("memberId"))){ - lst.add((String)properties.get("resourceId")); - } - } - Object[] st = lst.toArray(); - for (Object s : st) { - if (lst.indexOf(s) != lst.lastIndexOf(s)) { - lst.remove(lst.lastIndexOf(s)); - } - } - str_memberResourceNo[array_index]=lst.size(); - - db.close(); - return lst; - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public boolean BuildMemberListArray(){ - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("members"); - Query orderedQuery = chViews.CreateListByNameView(db).createQuery(); - int memberCounter = 0; - orderedQuery.setStartKey("A"); - //orderedQuery.setEndKey("a"); - ///orderedQuery.setDescending(false); - //orderedQuery.setLimit(0); - QueryEnumerator results = orderedQuery.run(); - str_memberIdList = new String[results.getCount()]; - str_memberNameList = new String[results.getCount()]; - str_memberLoginIdList = new String[results.getCount()]; - str_memberResourceNo = new int[results.getCount()]; - for (Iterator it = results; it.hasNext();) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - str_memberIdList[memberCounter] = (String) properties.get("_id"); - str_memberNameList[memberCounter] = (String) properties.get("firstName") +" "+(String) properties.get("lastName"); - str_memberLoginIdList[memberCounter] = (String) properties.get("login"); - str_memberResourceNo[memberCounter] = 0; - Log.e("MYAPP", " Member Name List: " + str_memberNameList[memberCounter] +" ("+str_memberLoginIdList[memberCounter]+")"); - memberCounter++; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Obj_Holder.java b/app/src/main/java/pbell/offline/ole/org/pbell/Obj_Holder.java deleted file mode 100644 index 353caf9..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Obj_Holder.java +++ /dev/null @@ -1,168 +0,0 @@ -package pbell.offline.ole.org.pbell; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.lightcouch.Attachment; -/** - * Created by leonardmensah on 07/03/2017. - */ - - -@SuppressWarnings("ALL") -public class Obj_Holder { - - @SuppressWarnings("unused") - private final String Type = "Foo"; - - private String _id; - private String _rev; - - private String title; - private String content; - private int position; - private List tags; - private int[] complexDate; - private Set bars; - private Date date; - private Map _attachments; - private List _revs_info; - - public Obj_Holder() { - super(); - } - - public Obj_Holder(String _id) { - this._id = _id; - } - - public Obj_Holder(String _id, String title) { - this._id = _id; - this.title = title; - } - - public String get_id() { - return _id; - } - - public String get_rev() { - return _rev; - } - - public String getTitle() { - return title; - } - - public String getContent() { - return content; - } - - public int getPosition() { - return position; - } - - public List getTags() { - return tags; - } - - public int[] getComplexDate() { - return complexDate; - } - - public Set getBars() { - return bars; - } - - public Date getDate() { - return date; - } - - public Map get_attachments() { - return _attachments; - } - - public List get_revs_info() { - return _revs_info; - } - - public void set_id(String _id) { - this._id = _id; - } - - public void set_rev(String _rev) { - this._rev = _rev; - } - - public void setTitle(String title) { - this.title = title; - } - - public void setContent(String content) { - this.content = content; - } - - public void setPosition(int position) { - this.position = position; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public void setComplexDate(int[] complexDate) { - this.complexDate = complexDate; - } - - public void setBars(Set bars) { - this.bars = bars; - } - - public void setDate(Date date) { - this.date = date; - } - - public void set_attachments(Map _attachments) { - this._attachments = _attachments; - } - - public void set_revs_info(List _revs_info) { - this._revs_info = _revs_info; - } - - @Override - public String toString() { - return "Obj_Holder [_id=" + _id + ", _rev=" + _rev + ", title=" + title + ", position=" - + position + ", tags=" + tags + ", complexDate=" - + Arrays.toString(complexDate) + ", bars=" + bars + ", _revs_info=" - + _revs_info + "]"; - } - - public static class RevInfo { - private String rev; - private String status; - - public String getRev() { - return rev; - } - - public void setRev(String rev) { - this.rev = rev; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - @Override - public String toString() { - return "RevInfo [rev=" + rev + ", status=" + status + "]"; - } - } // end RevInfo - -} // end Obj_Holder \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/PagerAdapter.java b/app/src/main/java/pbell/offline/ole/org/pbell/PagerAdapter.java deleted file mode 100644 index 316ee6d..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/PagerAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 17/05/16. - */ -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentStatePagerAdapter; - -@SuppressWarnings("ALL") -public class PagerAdapter extends FragmentStatePagerAdapter { - int mNumOfTabs; - - public PagerAdapter(FragmentManager fm, int NumOfTabs) { - super(fm); - this.mNumOfTabs = NumOfTabs; - } - - @Override - public Fragment getItem(int position) { - - switch (position) { - case 0: - //TabFragment1 tab1 = new TabFragment1(); - //return tab1; - return null; - case 1: - TabFragment2 tab2 = new TabFragment2(); - return tab2; - case 2: - TabFragment3 tab3 = new TabFragment3(); - return tab3; - default: - return null; - } - } - - @Override - public int getCount() { - return mNumOfTabs; - } -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/PdfViewerActivity.java b/app/src/main/java/pbell/offline/ole/org/pbell/PdfViewerActivity.java deleted file mode 100644 index 57fa570..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/PdfViewerActivity.java +++ /dev/null @@ -1,933 +0,0 @@ -package pbell.offline.ole.org.pbell; - import java.io.File; - import java.io.FileOutputStream; - import java.io.IOException; - import java.io.InputStream; - import java.io.OutputStream; - import java.io.RandomAccessFile; - import java.nio.channels.FileChannel; - - import net.sf.andpdf.nio.ByteBuffer; - import net.sf.andpdf.pdfviewer.gui.FullScrollView; - import net.sf.andpdf.refs.HardReference; - import android.app.Activity; - import android.app.AlertDialog; - import android.app.Dialog; - import android.app.ProgressDialog; - import android.content.Context; - import android.content.DialogInterface; - import android.content.Intent; - import android.graphics.Bitmap; - import android.graphics.Color; - import android.graphics.RectF; - import android.net.Uri; - import android.os.Bundle; - import android.os.Environment; - import android.os.Handler; - import android.util.Log; - import android.view.KeyEvent; - import android.view.LayoutInflater; - import android.view.Menu; - import android.view.MenuItem; - import android.view.View; - import android.view.ViewGroup; - import android.view.View.OnClickListener; - import android.view.inputmethod.InputMethodManager; - import android.widget.Button; - import android.widget.EditText; - import android.widget.ImageButton; - import android.widget.ImageView; - import android.widget.LinearLayout; - import android.widget.TextView; - - import com.sun.pdfview.PDFFile; - import com.sun.pdfview.PDFImage; - import com.sun.pdfview.PDFPage; - import com.sun.pdfview.PDFPaint; - import com.sun.pdfview.decrypt.PDFAuthenticationFailureException; - import com.sun.pdfview.decrypt.PDFPassword; - import com.sun.pdfview.font.PDFFont; - - -/** - * U:\Android\android-sdk-windows-1.5_r1\tools\adb push u:\Android\simple_T.pdf /data/test.pdf - * @author ferenc.hechler - */ -@SuppressWarnings("ALL") -public abstract class PdfViewerActivity extends Activity { - - private static final int STARTPAGE = 1; - private static final float STARTZOOM = 1.0f; - - private static final float MIN_ZOOM = 0.25f; - private static final float MAX_ZOOM = 3.0f; - private static final float ZOOM_INCREMENT = 1.5f; - - private static final String TAG = "PDFVIEWER"; - - public static final String EXTRA_PDFFILENAME = "net.sf.andpdf.extra.PDFFILENAME"; - public static final String EXTRA_SHOWIMAGES = "net.sf.andpdf.extra.SHOWIMAGES"; - public static final String EXTRA_ANTIALIAS = "net.sf.andpdf.extra.ANTIALIAS"; - public static final String EXTRA_USEFONTSUBSTITUTION = "net.sf.andpdf.extra.USEFONTSUBSTITUTION"; - public static final String EXTRA_KEEPCACHES = "net.sf.andpdf.extra.KEEPCACHES"; - - public static final boolean DEFAULTSHOWIMAGES = true; - public static final boolean DEFAULTANTIALIAS = true; - public static final boolean DEFAULTUSEFONTSUBSTITUTION = false; - public static final boolean DEFAULTKEEPCACHES = false; - - private final static int MENU_NEXT_PAGE = 1; - private final static int MENU_PREV_PAGE = 2; - private final static int MENU_GOTO_PAGE = 3; - private final static int MENU_ZOOM_IN = 4; - private final static int MENU_ZOOM_OUT = 5; - private final static int MENU_BACK = 6; - private final static int MENU_CLEANUP = 7; - - private final static int DIALOG_PAGENUM = 1; - - private GraphView mOldGraphView; - private GraphView mGraphView; - private String pdffilename; - private PDFFile mPdfFile; - private int mPage; - private float mZoom; - private File mTmpFile; - private ProgressDialog progress; - - /*private View navigationPanel; - private Handler closeNavigationHandler; - private Thread closeNavigationThread;*/ - - - private PDFPage mPdfPage; - - private Thread backgroundThread; - private Handler uiHandler; - - - @Override - public Object onRetainNonConfigurationInstance() { - // return a reference to the current instance - Log.e(TAG, "onRetainNonConfigurationInstance"); - return this; - } - /** - * restore member variables from previously saved instance - * @see onRetainNonConfigurationInstance - * @return true if instance to restore from was found - */ - private boolean restoreInstance() { - mOldGraphView = null; - Log.e(TAG, "restoreInstance"); - if (getLastNonConfigurationInstance()==null) - return false; - PdfViewerActivity inst =(PdfViewerActivity)getLastNonConfigurationInstance(); - if (inst != this) { - Log.e(TAG, "restoring Instance"); - mOldGraphView = inst.mGraphView; - mPage = inst.mPage; - mPdfFile = inst.mPdfFile; - mPdfPage = inst.mPdfPage; - mTmpFile = inst.mTmpFile; - mZoom = inst.mZoom; - pdffilename = inst.pdffilename; - backgroundThread = inst.backgroundThread; - // mGraphView.invalidate(); - } - return true; - } - - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Log.i(TAG, "onCreate"); - //progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page"); - /*closeNavigationHandler = new Handler(); - closeNavigationThread = new Thread(new Runnable() { - - public void run() { - navigationPanel.startAnimation(AnimationUtils.loadAnimation(PdfViewerActivity.this, - R.anim.slide_out)); - navigationPanel.setVisibility(View.GONE); - } - });*/ - - /*if (navigationPanel == null) { - navigationPanel = ((ViewStub) findViewById(R.id.stub_navigation)).inflate(); - navigationPanel.setVisibility(View.GONE); - ImageButton previous = (ImageButton)navigationPanel.findViewById(R.id.navigation_previous); - previous.setBackgroundDrawable(null); - }*/ - - uiHandler = new Handler(); - restoreInstance(); - if (mOldGraphView != null) { - mGraphView = new GraphView(this); - //mGraphView.fileMillis = mOldGraphView.fileMillis; - mGraphView.mBi = mOldGraphView.mBi; - //mGraphView.mLine1 = mOldGraphView.mLine1; - //mGraphView.mLine2 = mOldGraphView.mLine2; - //mGraphView.mLine3 = mOldGraphView.mLine3; - //mGraphView.mText = mOldGraphView.mText; - //mGraphView.pageParseMillis= mOldGraphView.pageParseMillis; - //mGraphView.pageRenderMillis= mOldGraphView.pageRenderMillis; - mOldGraphView = null; - mGraphView.mImageView.setImageBitmap(mGraphView.mBi); - mGraphView.updateTexts(); - setContentView(mGraphView); - } - else { - mGraphView = new GraphView(this); - Intent intent = getIntent(); - Log.i(TAG, ""+intent); - - boolean showImages = getIntent().getBooleanExtra(PdfViewerActivity.EXTRA_SHOWIMAGES, PdfViewerActivity.DEFAULTSHOWIMAGES); - PDFImage.sShowImages = showImages; - boolean antiAlias = getIntent().getBooleanExtra(PdfViewerActivity.EXTRA_ANTIALIAS, PdfViewerActivity.DEFAULTANTIALIAS); - PDFPaint.s_doAntiAlias = antiAlias; - boolean useFontSubstitution = getIntent().getBooleanExtra(PdfViewerActivity.EXTRA_USEFONTSUBSTITUTION, PdfViewerActivity.DEFAULTUSEFONTSUBSTITUTION); - PDFFont.sUseFontSubstitution= useFontSubstitution; - boolean keepCaches = getIntent().getBooleanExtra(PdfViewerActivity.EXTRA_KEEPCACHES, PdfViewerActivity.DEFAULTKEEPCACHES); - HardReference.sKeepCaches= keepCaches; - - if (intent != null) { - if ("android.intent.action.VIEW".equals(intent.getAction())) { - pdffilename = storeUriContentToFile(intent.getData()); - } - else { - pdffilename = getIntent().getStringExtra(PdfViewerActivity.EXTRA_PDFFILENAME); - } - } - - if (pdffilename == null) - pdffilename = "no file selected"; - - mPage = STARTPAGE; - mZoom = STARTZOOM; - - setContent(null); - - } - } - - - - private void setContent(String password) { - try { - parsePDF(pdffilename, password); - setContentView(mGraphView); - startRenderThread(mPage, mZoom); - } - catch (PDFAuthenticationFailureException e) { - setContentView(getPdfPasswordLayoutResource()); - final EditText etPW= (EditText) findViewById(getPdfPasswordEditField()); - Button btOK= (Button) findViewById(getPdfPasswordOkButton()); - Button btExit = (Button) findViewById(getPdfPasswordExitButton()); - btOK.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - String pw = etPW.getText().toString(); - setContent(pw); - } - }); - btExit.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - finish(); - } - }); - } - } - private synchronized void startRenderThread(final int page, final float zoom) { - if (backgroundThread != null) - return; - - mGraphView.showText("reading page "+ page+", zoom:"+zoom); - //progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page"); - backgroundThread = new Thread(new Runnable() { - public void run() { - try { - if (mPdfFile != null) { - //progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page"); - -// File f = new File("/sdcard/andpdf.trace"); -// f.delete(); -// Log.e(TAG, "DEBUG.START"); -// Debug.startMethodTracing("andpdf"); - showPage(page, zoom); -// Debug.stopMethodTracing(); -// Log.e(TAG, "DEBUG.STOP"); - - /*if (progress != null) - progress.dismiss();*/ - } - } catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } - backgroundThread = null; - } - }); - updateImageStatus(); - backgroundThread.start(); - } - - - private void updateImageStatus() { -// Log.i(TAG, "updateImageStatus: " + (System.currentTimeMillis()&0xffff)); - if (backgroundThread == null) { - mGraphView.updateUi(); - - /*if (progress != null) - progress.dismiss();*/ - return; - } - mGraphView.updateUi(); - mGraphView.postDelayed(new Runnable() { - public void run() { - updateImageStatus(); - - /*if (progress != null) - progress.dismiss();*/ - } - }, 1000); - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - menu.add(Menu.NONE, MENU_PREV_PAGE, Menu.NONE, "Previous Page").setIcon(getPreviousPageImageResource()); - menu.add(Menu.NONE, MENU_NEXT_PAGE, Menu.NONE, "Next Page").setIcon(getNextPageImageResource()); - menu.add(Menu.NONE, MENU_GOTO_PAGE, Menu.NONE, "Goto Page"); - menu.add(Menu.NONE, MENU_ZOOM_OUT, Menu.NONE, "Zoom Out").setIcon(getZoomOutImageResource()); - menu.add(Menu.NONE, MENU_ZOOM_IN, Menu.NONE, "Zoom In").setIcon(getZoomInImageResource()); - if (HardReference.sKeepCaches) - menu.add(Menu.NONE, MENU_CLEANUP, Menu.NONE, "Clear Caches"); - - return true; - } - - /** - * Called when a menu item is selected. - */ - @Override - public boolean onOptionsItemSelected(MenuItem item) { - super.onOptionsItemSelected(item); - switch (item.getItemId()) { - case MENU_NEXT_PAGE: { - nextPage(); - break; - } - case MENU_PREV_PAGE: { - prevPage(); - break; - } - case MENU_GOTO_PAGE: { - gotoPage(); - break; - } - case MENU_ZOOM_IN: { - zoomIn(); - break; - } - case MENU_ZOOM_OUT: { - zoomOut(); - break; - } - case MENU_BACK: { - finish(); - break; - } - case MENU_CLEANUP: { - HardReference.cleanup(); - break; - } - } - return true; - } - - - private void zoomIn() { - if (mPdfFile != null) { - if (mZoom < MAX_ZOOM) { - mZoom *= ZOOM_INCREMENT; - if (mZoom > MAX_ZOOM) - mZoom = MAX_ZOOM; - - if (mZoom >= MAX_ZOOM) { - Log.d(TAG, "Disabling zoom in button"); - mGraphView.bZoomIn.setEnabled(false); - } - else - mGraphView.bZoomIn.setEnabled(true); - - mGraphView.bZoomOut.setEnabled(true); - - //progress = ProgressDialog.show(PdfViewerActivity.this, "Rendering", "Rendering PDF Page"); - startRenderThread(mPage, mZoom); - } - } - } - - private void zoomOut() { - if (mPdfFile != null) { - if (mZoom > MIN_ZOOM) { - mZoom /= ZOOM_INCREMENT; - if (mZoom < MIN_ZOOM) - mZoom = MIN_ZOOM; - - if (mZoom <= MIN_ZOOM) { - Log.d(TAG, "Disabling zoom out button"); - mGraphView.bZoomOut.setEnabled(false); - } - else - mGraphView.bZoomOut.setEnabled(true); - - mGraphView.bZoomIn.setEnabled(true); - - //progress = ProgressDialog.show(PdfViewerActivity.this, "Rendering", "Rendering PDF Page"); - startRenderThread(mPage, mZoom); - } - } - } - - private void nextPage() { - if (mPdfFile != null) { - if (mPage < mPdfFile.getNumPages()) { - mPage += 1; - mGraphView.bZoomOut.setEnabled(true); - mGraphView.bZoomIn.setEnabled(true); - progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page " + mPage, true, true); - startRenderThread(mPage, mZoom); - } - } - } - - private void prevPage() { - if (mPdfFile != null) { - if (mPage > 1) { - mPage -= 1; - mGraphView.bZoomOut.setEnabled(true); - mGraphView.bZoomIn.setEnabled(true); - progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page " + mPage, true, true); - startRenderThread(mPage, mZoom); - } - } - } - - private void gotoPage() { - if (mPdfFile != null) { - showDialog(DIALOG_PAGENUM); - } - } - - @Override - protected Dialog onCreateDialog(int id) { - switch (id) { - case DIALOG_PAGENUM: - LayoutInflater factory = LayoutInflater.from(this); - final View pagenumView = factory.inflate(getPdfPageNumberResource(), null); - final EditText edPagenum = (EditText)pagenumView.findViewById(getPdfPageNumberEditField()); - edPagenum.setText(Integer.toString(mPage)); - edPagenum.setOnEditorActionListener(new TextView.OnEditorActionListener() { - - public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (event == null || ( event.getAction() == 1)) { - // Hide the keyboard - InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(edPagenum.getWindowToken(), 0); - } - return true; - } - }); - return new AlertDialog.Builder(this) - //.setIcon(R.drawable.icon) - .setTitle("Jump to page") - .setView(pagenumView) - .setPositiveButton("OK", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String strPagenum = edPagenum.getText().toString(); - int pageNum = mPage; - try { - pageNum = Integer.parseInt(strPagenum); - } - catch (NumberFormatException ignore) {} - if ((pageNum!=mPage) && (pageNum>=1) && (pageNum <= mPdfFile.getNumPages())) { - mPage = pageNum; - mGraphView.bZoomOut.setEnabled(true); - mGraphView.bZoomIn.setEnabled(true); - progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page " + mPage, true, true); - startRenderThread(mPage, mZoom); - } - } - }) - .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - } - }) - .create(); - } - return null; - } - - private class GraphView extends FullScrollView { - //private String mText; - //private long fileMillis; - //private long pageParseMillis; - //private long pageRenderMillis; - private Bitmap mBi; - //private String mLine1; - //private String mLine2; - //private String mLine3; - private ImageView mImageView; - //private TextView mLine1View; - //private TextView mLine2View; - //private TextView mLine3View; - private Button mBtPage; - private Button mBtPage2; - - ImageButton bZoomOut; - ImageButton bZoomIn; - - public GraphView(Context context) { - super(context); - - //setContentView(R.layout.graphics_view); - // layout params - LinearLayout.LayoutParams lpWrap1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1); - LinearLayout.LayoutParams lpWrap10 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,10); - - // vertical layout - LinearLayout vl=new LinearLayout(context); - vl.setLayoutParams(lpWrap10); - vl.setOrientation(LinearLayout.VERTICAL); - - if (mOldGraphView == null) - progress = ProgressDialog.show(PdfViewerActivity.this, "Loading", "Loading PDF Page", true, true); - - addNavButtons(vl); - // remember page button for updates - mBtPage2 = mBtPage; - - mImageView = new ImageView(context); - setPageBitmap(null); - updateImage(); - mImageView.setLayoutParams(lpWrap1); - mImageView.setPadding(5, 5, 5, 5); - vl.addView(mImageView); - /*mImageView = (ImageView) findViewById(R.id.pdf_image); - if (mImageView == null) { - Log.i(TAG, "mImageView is null!!!!!!"); - } - setPageBitmap(null); - updateImage();*/ - - /* - navigationPanel = new ViewStub(PdfViewerActivity.this, R.layout.navigation_overlay); - final ImageButton previous = (ImageButton)navigationPanel.findViewById(R.id.navigation_previous); - previous.setBackgroundDrawable(null); - previous.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - prevPage(); - } - }); - - final ImageButton next = (ImageButton)navigationPanel.findViewById(R.id.navigation_next); - next.setBackgroundDrawable(null); - previous.setOnClickListener(new OnClickListener() { - - @Override - public void onClick(View v) { - nextPage(); - } - }); - - //stub.setLayoutParams(Layou) - vl.addView(navigationPanel); - - vl.setOnTouchListener(new OnTouchListener() { - - @Override - public boolean onTouch(View v, MotionEvent event) { - if (navigationPanel.getVisibility() != View.VISIBLE) { - navigationPanel.startAnimation(AnimationUtils.loadAnimation(PdfViewerActivity.this, - R.anim.slide_in)); - navigationPanel.setVisibility(View.VISIBLE); - } - - return false; - } - }); - */ - - //addNavButtons(vl); - - setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 100)); - setBackgroundColor(Color.LTGRAY); - setHorizontalScrollBarEnabled(true); - setHorizontalFadingEdgeEnabled(true); - setVerticalScrollBarEnabled(true); - setVerticalFadingEdgeEnabled(true); - addView(vl); - } - - private void addNavButtons(ViewGroup vg) { - - addSpace(vg, 6, 6); - - LinearLayout.LayoutParams lpChild1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1); - LinearLayout.LayoutParams lpWrap10 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,10); - - Context context = vg.getContext(); - LinearLayout hl=new LinearLayout(context); - hl.setLayoutParams(lpWrap10); - hl.setOrientation(LinearLayout.HORIZONTAL); - - // zoom out button - bZoomOut=new ImageButton(context); - bZoomOut.setBackgroundDrawable(null); - bZoomOut.setLayoutParams(lpChild1); - //bZoomOut.setText("-"); - //bZoomOut.setWidth(40); - bZoomOut.setImageResource(getZoomOutImageResource()); - bZoomOut.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - zoomOut(); - } - }); - hl.addView(bZoomOut); - - // zoom in button - bZoomIn=new ImageButton(context); - bZoomIn.setBackgroundDrawable(null); - bZoomIn.setLayoutParams(lpChild1); - //bZoomIn.setText("+"); - //bZoomIn.setWidth(40); - bZoomIn.setImageResource(getZoomInImageResource()); - bZoomIn.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - zoomIn(); - } - }); - hl.addView(bZoomIn); - - addSpace(hl, 6, 6); - - // prev button - ImageButton bPrev=new ImageButton(context); - bPrev.setBackgroundDrawable(null); - bPrev.setLayoutParams(lpChild1); - //bPrev.setText("<"); - //bPrev.setWidth(40); - bPrev.setImageResource(getPreviousPageImageResource()); - bPrev.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - prevPage(); - } - }); - hl.addView(bPrev); - - // page button - mBtPage=new Button(context); - mBtPage.setLayoutParams(lpChild1); - String maxPage = ((mPdfFile==null)?"0":Integer.toString(mPdfFile.getNumPages())); - mBtPage.setText(mPage+"/"+maxPage); - mBtPage.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - gotoPage(); - } - }); - hl.addView(mBtPage); - - // next button - ImageButton bNext=new ImageButton(context); - bNext.setBackgroundDrawable(null); - bNext.setLayoutParams(lpChild1); - //bNext.setText(">"); - //bNext.setWidth(40); - bNext.setImageResource(getNextPageImageResource()); - bNext.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - nextPage(); - } - }); - hl.addView(bNext); - - addSpace(hl, 20, 20); - - // exit button - /* - Button bExit=new Button(context); - bExit.setLayoutParams(lpChild1); - bExit.setText("Back"); - bExit.setWidth(60); - bExit.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - finish(); - } - }); - hl.addView(bExit);*/ - - vg.addView(hl); - - addSpace(vg, 6, 6); - } - - private void addSpace(ViewGroup vg, int width, int height) { - TextView tvSpacer=new TextView(vg.getContext()); - tvSpacer.setLayoutParams(new LinearLayout.LayoutParams(width,height,1)); - tvSpacer.setText(""); -// tvSpacer.setWidth(width); -// tvSpacer.setHeight(height); - vg.addView(tvSpacer); - - } - - private void showText(String text) { - Log.i(TAG, "ST='"+text+"'"); - //mText = text; - updateUi(); - } - - private void updateUi() { - uiHandler.post(new Runnable() { - public void run() { - updateTexts(); - } - }); - } - - private void updateImage() { - uiHandler.post(new Runnable() { - public void run() { - mImageView.setImageBitmap(mBi); - - /*if (progress != null) - progress.dismiss();*/ - } - }); - } - - private void setPageBitmap(Bitmap bi) { - if (bi != null) - mBi = bi; - else { - /* - mBi = Bitmap.createBitmap(100, 100, Config.RGB_565); - Canvas can = new Canvas(mBi); - can.drawColor(Color.RED); - - Paint paint = new Paint(); - paint.setColor(Color.BLUE); - can.drawCircle(50, 50, 50, paint); - - paint.setStrokeWidth(0); - paint.setColor(Color.BLACK); - can.drawText("Bitmap", 10, 50, paint); - */ - } - } - - protected void updateTexts() { - /* - mLine1 = "PdfViewer: "+mText; - float fileTime = fileMillis*0.001f; - float pageRenderTime = pageRenderMillis*0.001f; - float pageParseTime = pageParseMillis*0.001f; - mLine2 = "render page="+format(pageRenderTime,2)+", parse page="+format(pageParseTime,2)+", parse file="+format(fileTime,2); - int maxCmds = PDFPage.getParsedCommands(); - int curCmd = PDFPage.getLastRenderedCommand()+1; - mLine3 = "PDF-Commands: "+curCmd+"/"+maxCmds; - //mLine1View.setText(mLine1); - //mLine2View.setText(mLine2); - //mLine3View.setText(mLine3); - */ - if (mPdfPage != null) { - if (mBtPage != null) - mBtPage.setText(mPdfPage.getPageNumber()+"/"+mPdfFile.getNumPages()); - if (mBtPage2 != null) - mBtPage2.setText(mPdfPage.getPageNumber()+"/"+mPdfFile.getNumPages()); - } - } - - /*private String format(double value, int num) { - NumberFormat nf = NumberFormat.getNumberInstance(); - nf.setGroupingUsed(false); - nf.setMaximumFractionDigits(num); - String result = nf.format(value); - return result; - }*/ - } - - - - private void showPage(int page, float zoom) throws Exception { - //long startTime = System.currentTimeMillis(); - //long middleTime = startTime; - try { - // free memory from previous page - mGraphView.setPageBitmap(null); - mGraphView.updateImage(); - - // Only load the page if it's a different page (i.e. not just changing the zoom level) - if (mPdfPage == null || mPdfPage.getPageNumber() != page) { - mPdfPage = mPdfFile.getPage(page, true); - } - //int num = mPdfPage.getPageNumber(); - //int maxNum = mPdfFile.getNumPages(); - float width = mPdfPage.getWidth(); - float height = mPdfPage.getHeight(); - //String pageInfo= new File(pdffilename).getName() + " - " + num +"/"+maxNum+ ": " + width + "x" + height; - //mGraphView.showText(pageInfo); - //Log.i(TAG, pageInfo); - RectF clip = null; - //middleTime = System.currentTimeMillis(); - Bitmap bi = mPdfPage.getImage((int)(width*zoom), (int)(height*zoom), clip, true, true); - mGraphView.setPageBitmap(bi); - mGraphView.updateImage(); - - if (progress != null) - progress.dismiss(); - } catch (Throwable e) { - Log.e(TAG, e.getMessage(), e); - mGraphView.showText("Exception: "+e.getMessage()); - } - //long stopTime = System.currentTimeMillis(); - //mGraphView.pageParseMillis = middleTime-startTime; - //mGraphView.pageRenderMillis = stopTime-middleTime; - } - - private void parsePDF(String filename, String password) throws PDFAuthenticationFailureException { - //long startTime = System.currentTimeMillis(); - try { - File f = new File(filename); - long len = f.length(); - if (len == 0) { - mGraphView.showText("file '" + filename + "' not found"); - } - else { - mGraphView.showText("file '" + filename + "' has " + len + " bytes"); - openFile(f, password); - } - } - catch (PDFAuthenticationFailureException e) { - throw e; - } catch (Throwable e) { - e.printStackTrace(); - mGraphView.showText("Exception: "+e.getMessage()); - } - //long stopTime = System.currentTimeMillis(); - //mGraphView.fileMillis = stopTime-startTime; - } - - - /** - *

Open a specific pdf file. Creates a DocumentInfo from the file, - * and opens that.

- * - *

Note: Mapping the file locks the file until the PDFFile - * is closed.

- * - * @param file the file to open - * @throws IOException - */ - public void openFile(File file, String password) throws IOException { - // first open the file for random access - RandomAccessFile raf = new RandomAccessFile(file, "r"); - - // extract a file channel - FileChannel channel = raf.getChannel(); - - // now memory-map a byte-buffer - ByteBuffer bb = - ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size())); - // create a PDFFile from the data - if (password == null) - mPdfFile = new PDFFile(bb); - else - mPdfFile = new PDFFile(bb, new PDFPassword(password)); - - mGraphView.showText("Anzahl Seiten:" + mPdfFile.getNumPages()); - } - - - /*private byte[] readBytes(File srcFile) throws IOException { - long fileLength = srcFile.length(); - int len = (int)fileLength; - byte[] result = new byte[len]; - FileInputStream fis = new FileInputStream(srcFile); - int pos = 0; - int cnt = fis.read(result, pos, len-pos); - while (cnt > 0) { - pos += cnt; - cnt = fis.read(result, pos, len-pos); - } - return result; - }*/ - - private String storeUriContentToFile(Uri uri) { - String result = null; - try { - if (mTmpFile == null) { - File root = Environment.getExternalStorageDirectory(); - if (root == null) - throw new Exception("external storage dir not found"); - mTmpFile = new File(root,"AndroidPdfViewer/AndroidPdfViewer_temp.pdf"); - mTmpFile.getParentFile().mkdirs(); - mTmpFile.delete(); - } - else { - mTmpFile.delete(); - } - InputStream is = getContentResolver().openInputStream(uri); - OutputStream os = new FileOutputStream(mTmpFile); - byte[] buf = new byte[1024]; - int cnt = is.read(buf); - while (cnt > 0) { - os.write(buf, 0, cnt); - cnt = is.read(buf); - } - os.close(); - is.close(); - result = mTmpFile.getCanonicalPath(); - mTmpFile.deleteOnExit(); - } - catch (Exception e) { - Log.e(TAG, e.getMessage(), e); - } - return result; - } - - - @Override - protected void onDestroy() { - super.onDestroy(); - if (mTmpFile != null) { - mTmpFile.delete(); - mTmpFile = null; - } - } - - /*private void postHideNavigation() { - // Start a time to hide the panel after 3 seconds - closeNavigationHandler.removeCallbacks(closeNavigationThread); - closeNavigationHandler.postDelayed(closeNavigationThread, 3000); - }*/ - - public abstract int getPreviousPageImageResource(); // R.drawable.left_arrow - public abstract int getNextPageImageResource(); // R.drawable.right_arrow - public abstract int getZoomInImageResource(); // R.drawable.zoom_int - public abstract int getZoomOutImageResource(); // R.drawable.zoom_out - - public abstract int getPdfPasswordLayoutResource(); // R.layout.pdf_file_password - public abstract int getPdfPageNumberResource(); // R.layout.dialog_pagenumber - - public abstract int getPdfPasswordEditField(); // R.id.etPassword - public abstract int getPdfPasswordOkButton(); // R.id.btOK - public abstract int getPdfPasswordExitButton(); // R.id.btExit - public abstract int getPdfPageNumberEditField(); // R.id.pagenum_edit -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/Resource.java b/app/src/main/java/pbell/offline/ole/org/pbell/Resource.java deleted file mode 100644 index 537113f..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/Resource.java +++ /dev/null @@ -1,70 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import java.util.ArrayList; - -/** - * Created by leonardmensah on 01/06/16. - */ -@SuppressWarnings("ALL") -public class Resource { - private String title; - private int thumbnailUrl; - private String rating; - private String descr; - private ArrayList genre; - - public Resource() { - - } - - public Resource(String name, int thumbnailUrl, String rating, String descr, - ArrayList genre) { - this.title = name; - this.thumbnailUrl = thumbnailUrl; - this.rating = rating; - this.descr = descr; - this.genre = genre; - } - - public String getTitle() { - return title; - } - - public void setTitle(String name) { - this.title = name; - } - - public int getThumbnailUrl() { - return thumbnailUrl; - } - - public void setThumbnailUrl(int thumbnailUrl) { - this.thumbnailUrl = thumbnailUrl; - } - - public String getRating() { - return rating; - } - - public void setRating(String rating) { - this.rating = rating; - } - - public String getDescription() { - return descr; - } - - public void setDescription(String descr) { - this.descr = descr; - } - - public ArrayList getGenre() { - return genre; - } - - public void setGenre(ArrayList genre) { - this.genre = genre; - } - - -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/SyncDevice.java b/app/src/main/java/pbell/offline/ole/org/pbell/SyncDevice.java deleted file mode 100644 index eafc911..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/SyncDevice.java +++ /dev/null @@ -1,828 +0,0 @@ -package pbell.offline.ole.org.pbell; - -import android.app.ProgressDialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.AsyncTask; -import android.os.Bundle; -import android.support.design.widget.FloatingActionButton; -import android.support.design.widget.Snackbar; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.text.method.ScrollingMovementMethod; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.CompoundButton; -import android.widget.Switch; -import android.widget.TextView; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; -import com.couchbase.lite.replicator.Replication; -import com.github.kittinunf.fuel.Fuel; -import com.github.kittinunf.fuel.core.FuelError; -import com.github.kittinunf.fuel.core.Request; -import com.github.kittinunf.fuel.core.Response; -import com.google.gson.JsonObject; - -import org.json.JSONException; -import org.json.JSONObject; -import org.lightcouch.CouchDbClientAndroid; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URL; -import java.net.URLEncoder; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -@SuppressWarnings("ALL") -public class SyncDevice extends AppCompatActivity { - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate= ""; - - CouchViews chViews = new CouchViews(); - - TextView tv; - View clcview; - String message =""; - String str_memberID,str_resourceId; - //////Replication push,pull; - FloatingActionButton fab; - Boolean wipeClearn =false; - final Context context = this; - String[] databaseList = {"members","membercourseprogress","meetups","usermeetups","assignments","coursestep", - "calendar","groups","invitations","configurations","requests","shelf","languages"}; - Replication[] pull= new Replication[databaseList.length]; - Database[] db = new Database[databaseList.length]; - Manager[] manager = new Manager[databaseList.length]; - - String[] pushdatabaseList = {"members"}; - Replication[] push = new Replication[pushdatabaseList.length]; - Database[] push_db = new Database[pushdatabaseList.length]; - Manager[] push_manager = new Manager[pushdatabaseList.length]; - - ProgressDialog[] progressDialog = new ProgressDialog[databaseList.length]; - - JSONObject designViewDoc; - - AndroidContext androidContext; - int syncCnt=0; - int pushsyncCnt=0; - Button btnStartSyncPush,btnStartSyncPull; - String[] str_memberIdList,str_memberNameList,str_memberLoginIdList; - int[] str_memberResourceNo; - - Boolean synchronizingPull = true; - Boolean synchronizingPush = true; - JSONObject jsonData; - int doc_rating,doc_timesRated; - ArrayList doc_comments; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_sync_device); - Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); - setSupportActionBar(toolbar); - - androidContext = new AndroidContext(this); - // Restore preferences - settings = getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - //tv = (TextView)findViewById(R.id.txtLogConsole); - - TextView lblSyncURL = (TextView)findViewById(R.id.lblSyncSyncUrl); - lblSyncURL.setText(sys_oldSyncServerURL); - - TextView lblLastSyncDate = (TextView)findViewById(R.id.lblLastDateSync); - lblLastSyncDate.setText(sys_lastSyncDate); - - tv = (TextView)findViewById(R.id.txtLogConsole); - tv.setMovementMethod(new ScrollingMovementMethod()); - - btnStartSyncPull = (Button)findViewById(R.id.btnstartSyncPull); - btnStartSyncPull.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - pushsyncCnt=0; - tv.setText(" Sync Started, please wait ... " ); - tv.scrollTo(0,tv.getTop()); - pullSyncNotifier(); - ///new TestAsyncPull().execute(); - } - - }); - - btnStartSyncPush = (Button)findViewById(R.id.btnstartSyncPush); - btnStartSyncPush.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - syncCnt=0; - tv.setText(" Sync Started, please wait ... " ); - tv.scrollTo(0,tv.getTop()); - pushSyncNotifier(); - } - - }); - - Button btnSyncResources = (Button)findViewById(R.id.btnsyncResources); - btnSyncResources.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - synchronizingPull=false; - - try{ - designViewDoc = new JSONObject(); - JSONObject filter = new JSONObject(); - try { - filter.put("by_resource","function(doc, req){return doc._id === req.query._id;}"); - designViewDoc.put("filters",filter); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - new RunCreateDocTask().execute(""); - }catch(Exception err){ - ///err.printStackTrace(); - } - - triggerMemberResourceDownload(); - } - - }); - - Switch sw_wipeClean = (Switch) findViewById(R.id.swWipeClean); - sw_wipeClean.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - wipeClearn = isChecked; - ///Log.v("Switch State=", ""+isChecked); - } - }); - - - fab = (FloatingActionButton) findViewById(R.id.checkConnection); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - clcview = view; - try { - if (checkConnectionURL()) { - fab.setVisibility(View.INVISIBLE); - Snackbar.make(clcview, "Checking connection to "+sys_oldSyncServerURL +".... please wait", Snackbar.LENGTH_INDEFINITE) - .setAction("Action", null).show(); - new TryDownloadTask().execute(sys_oldSyncServerURL); - - } else { - - } - }catch(Exception e) { - Log.v("myErrorTag","Error "+e.getLocalizedMessage()); - - } - } - }); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - } - class RunCreateDocTask extends AsyncTask { - private Exception exception; - private String cls_SyncServerURL; - private String cls_DbName; - private String cls_DocNameId; - private JsonObject cls_ViewContent; - public String getSyncServerURL(){ - return cls_SyncServerURL; - } - public void setSyncServerURL(String oldSyncServerURL){ - cls_SyncServerURL = oldSyncServerURL; - } - public String getDbName(){ - return cls_DbName; - } - public void setDbName(String dbName){ - cls_DbName = dbName; - } - public String getDocNameId(){ - return cls_DocNameId; - } - public void setDocNameId(String docNameId){ - cls_DocNameId = docNameId; - } - public JsonObject getViewContent(){ - return cls_ViewContent; - } - public JsonObject setViewContent(JsonObject viewContent) { - cls_ViewContent = viewContent; - return cls_ViewContent; - } - protected Boolean doInBackground(String... urls) { - try { - Log.e("MyCouch", "URL = "+getSyncServerURL()); - URI uri = URI.create(getSyncServerURL()); - String url_Scheme = uri.getScheme(); - String url_Host = uri.getHost(); - int url_Port = uri.getPort(); - String url_user = "", url_pwd = ""; - if (uri.getUserInfo() != null) { - String[] userinfo = uri.getUserInfo().split(":"); - url_user = userinfo[0]; - url_pwd = userinfo[1]; - } - CouchDbClientAndroid dbClient = new CouchDbClientAndroid(getDbName(), true, url_Scheme, url_Host, url_Port, url_user, url_pwd); - Log.e("MyCouch", "Creating design document "+getDocNameId()+" --- "+getDbName()+" --- "+url_Scheme+" --- " +url_Host+" --- " +url_Port+" --- " + url_user+" --- " + url_pwd); - if(!dbClient.contains(URLEncoder.encode(getDocNameId(), "UTF-8"))){ - JsonObject json = new JsonObject(); - json.addProperty("_id", getDocNameId()); - json.add("filters", getViewContent()); - dbClient.save(json); - } - return true; - } catch (Exception e) { - this.exception = e; - Log.e("MyCouch", e.toString()); - return false; - } - } - protected void onPostExecute(Boolean docResult) { - - } - } - - /////// End Filtered Replication View File - - public void triggerMemberResourceDownload(){ - if(!synchronizingPull) { - synchronizingPull = true; - Log.e("MyCouch", "Sync Variable false"); - if (BuildMemberListArray()) { - for (int cnt = 0; cnt < str_memberIdList.length; cnt++) { - ArrayList strings = CheckShelfForResources(cnt); - } - Bundle b = new Bundle(); - b.putStringArray("memberNameList", str_memberNameList); - b.putStringArray("memberIdList", str_memberIdList); - b.putIntArray("memberResourceNo", str_memberResourceNo); - b.putStringArray("memberLoginIdList", str_memberLoginIdList); - Intent intent = new Intent(this, MemberListDownloadRes.class); - intent.putExtras(b); - startActivity(intent); - } else { - Log.e("MyCouch", "triggerMemberResourceDownload function error"); - } - synchronizingPull = true; - }else{ - Log.e("MyCouch", "Sync Variable True"); - } - } - - public void pullSyncNotifier(){ - final AsyncTask execute = new TestAsyncPull().execute(); - Log.e("MyCouch", "pull_syncNotifier Running"); - final Thread th = new Thread(new Runnable() { - private long startTime = System.currentTimeMillis(); - public void run() { - while (synchronizingPull) { - runOnUiThread(new Runnable() { - @Override - public void run() { - ///triggerMemberResourceDownload(); - ///Log.d("runOnUiThread", "running"); - //mydialog.setMessage("Downloading, please wait .... " + (syncCnt + 1)); - } - }); - try { - Thread.sleep(9000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - th.start(); - } - - public void pushSyncNotifier(){ - BuildMemberListArray(); - for(int cnt=0;cnt it = result; it.hasNext(); ) { - QueryRow row = it.next(); - if (row.getConflictingRevisions().size() > 0) { - Log.e("MyCouch", "Resource Id "+row.getDocumentId());; - // Log.w("MYAPP", "Conflict in document: %s", row.getDocumentId()); - /// beginConflictResolution(row.getDocument()); - } - } - - }catch(Exception err){ - - } - - - /////updateLocalResources(resourceId); - /* - final AsyncTask execute = new TestAsyncPush().execute(); - Log.e("MyCouch", "push_SyncNotifier Running"); - final Thread th = new Thread(new Runnable() { - private long startTime = System.currentTimeMillis(); - public void run() { - while (synchronizingPush) { - runOnUiThread(new Runnable() { - @Override - public void run() { - } - }); - try { - Thread.sleep(9000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - th.start(); - - */ - - } - - private boolean checkConnectionURL() { - ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); - if (networkInfo != null && networkInfo.isConnected()) { - Log.v("myErrorTag","Network Connected"); - return true; - // fetch data - } else { - - Log.v("myErrorTag","Network Not Connected"); - return false; - } - - } - - private class TryDownloadTask extends AsyncTask { - @Override - protected String doInBackground(String... urls) { - - // params comes from the execute() call: params[0] is the url. - InputStream is = null; - int response=0; - try { - URL url = new URL(sys_oldSyncServerURL); - HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setReadTimeout(5000 /* milliseconds */); - conn.setConnectTimeout(10000 /* milliseconds */); - conn.setRequestMethod("GET"); - conn.setDoInput(true); - // Starts the query - conn.connect(); - response = conn.getResponseCode(); - Log.d("Responce", "The response is: " + response); - is = conn.getInputStream(); - return ""; - }catch (Exception err) { - - }finally - { - if(response!=200){ - displayDownMesage(false); - }else{ - displayDownMesage(true); - } - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return ""; - } - } - // onPostExecute displays the results of the AsyncTask. - @Override - protected void onPostExecute(String result) { - /// textView.setText(result); - } - } - - public void displayDownMesage(boolean status){ - if(status){ - Snackbar.make(clcview, "Connection to established successful", Snackbar.LENGTH_LONG) - .setAction("Action", null).show(); - }else{ - Snackbar.make(clcview, "Sorry , server was unreachable, check url and device connection", Snackbar.LENGTH_LONG) - .setAction("Action", null).show(); - } - } - - class TestAsyncPull extends AsyncTask { - protected void onPreExecute (){ - Log.d("PreExceute","On pre Exceute......"); - } - - protected String doInBackground(Void...arg0) { - Log.d("DoINBackGround","On doInBackground..."); - synchronizingPull=true; - pull= new Replication[databaseList.length]; - db = new Database[databaseList.length]; - manager = new Manager[databaseList.length]; - try { - manager[syncCnt] = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - if(wipeClearn){ - try{ - db[syncCnt] = manager[syncCnt].getExistingDatabase(databaseList[syncCnt]); - db[syncCnt].delete(); - }catch(Exception err){ - Log.e("MyCouch", "Delete Error "+ err.getLocalizedMessage()); - } - } - - db[syncCnt] = manager[syncCnt].getDatabase(databaseList[syncCnt]); - URL url = new URL(sys_oldSyncServerURL+"/"+databaseList[syncCnt]); - pull[syncCnt]= db[syncCnt].createPullReplication(url); - pull[syncCnt].setContinuous(false); - pull[syncCnt].addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - if(pull[syncCnt] .isRunning()){ - Log.e("MyCouch", databaseList[syncCnt]+" "+event.getChangeCount()); - message = String.valueOf(event.getChangeCount()); - }else { - Log.e("Finished", databaseList[syncCnt]+" "+ db[syncCnt].getDocumentCount()); - if(syncCnt < (databaseList.length-2)){ - syncCnt++; - new TestAsyncPull().execute(); - }else{ - Log.e("MyCouch","Sync Completed"); - triggerMemberResourceDownload(); - synchronizingPull=true; - } - - } - } - }); - pull[syncCnt].start(); - - } catch (Exception e) { - Log.e("MyCouch", databaseList[syncCnt]+" "+" Cannot create database", e); - - - } - publishProgress(syncCnt); - return "You are at PostExecute"; - } - protected void onProgressUpdate(Integer...a){ - Log.d("onProgress","You are in progress update ... " + a[0]); - if(syncCnt != (databaseList.length-2)){ - tv.setText(tv.getText().toString()+" \n Pulled "+databaseList[syncCnt]+ "\n Pulling "+ databaseList[syncCnt+1]+"....." ); - tv.scrollTo(0,(tv.getLineCount()*20+syncCnt)); - - tv.requestFocus(); - }else{ - tv.setText(tv.getText().toString()+" \n Pulled "+ databaseList[syncCnt] ); - tv.scrollTo(0,(tv.getLineCount()*20)+syncCnt); - - tv.requestFocus(); - } - } - - protected void onPostExecute(String result) { - Log.d("OnPostExec",""+result); - } - } - - class TestAsyncPush extends AsyncTask { - protected void onPreExecute (){ - Log.d("PreExceute","On pre Exceute......"); - } - - protected String doInBackground(Void...arg0) { - Log.d("DoINBackGround","On doInBackground..."); - synchronizingPush=true; - push = new Replication[pushdatabaseList.length]; - push_db = new Database[pushdatabaseList.length]; - push_manager = new Manager[pushdatabaseList.length]; - try { - push_manager[pushsyncCnt] = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - push_db[pushsyncCnt] = push_manager[syncCnt].getDatabase(pushdatabaseList[pushsyncCnt]); - URL url = new URL(sys_oldSyncServerURL+"/"+pushdatabaseList[pushsyncCnt]); - push[pushsyncCnt]= push_db[pushsyncCnt].createPushReplication(url); - push[pushsyncCnt].setContinuous(false); - push[pushsyncCnt].addChangeListener(new Replication.ChangeListener() { - @Override - public void changed(Replication.ChangeEvent event) { - if(push[pushsyncCnt] .isRunning()){ - Log.e("MyCouch", pushdatabaseList[pushsyncCnt]+" "+event.getChangeCount()); - message = String.valueOf(event.getChangeCount()); - }else { - Log.e("Finished", pushdatabaseList[pushsyncCnt]+" "+ push_db[pushsyncCnt].getDocumentCount()); - if(pushsyncCnt+1 < (pushdatabaseList.length)){ - pushsyncCnt++; - new TestAsyncPush().execute(); - }else{ - Log.e("MyCouch","Sync Completed"); - synchronizingPush=false; - mydeleteDatabase("visits"); - } - - } - } - }); - push[pushsyncCnt].start(); - - } catch (Exception e) { - Log.e("MyCouch", pushdatabaseList[pushsyncCnt]+" "+" Cannot create database", e); - - - } - publishProgress(pushsyncCnt); - return "You are at PostExecute"; - } - protected void onProgressUpdate(Integer...a){ - Log.d("onProgress","You are in progress update ... " + a[0]); - tv.setText(tv.getText().toString()+" \n Pushed "+ pushdatabaseList[pushsyncCnt] ); - tv.scrollTo(0,(tv.getLineCount()*20)+pushsyncCnt); - - tv.requestFocus(); - } - - protected void onPostExecute(String result) { - Log.d("OnPostExec",""+result); - } - } - - public ArrayList CheckShelfForResources(int index) { - int array_index = index; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("shelf"); - Query orderedQuery = chViews.ReadShelfByIdView(db).createQuery(); - orderedQuery.setDescending(true); - //Todo startKey and EndKey generate inaccurate result - ///orderedQuery.setStartKey(str_memberIdList[array_index]); - //orderedQuery.setLimit(0); - ArrayList lst = new ArrayList(); - QueryEnumerator results = orderedQuery.run(); - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - if(str_memberIdList[array_index].equals((String)properties.get("memberId"))){ - lst.add((String)properties.get("resourceId")); - } - } - Object[] st = lst.toArray(); - for (Object s : st) { - if (lst.indexOf(s) != lst.lastIndexOf(s)) { - lst.remove(lst.lastIndexOf(s)); - } - } - str_memberResourceNo[array_index]=lst.size(); - - db.close(); - return lst; - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - - - public boolean BuildMemberListArray(){ - AndroidContext androidContext = new AndroidContext(this); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("members"); - Query orderedQuery = chViews.CreateListByNameView(db).createQuery(); - int memberCounter = 0; - orderedQuery.setStartKey("A"); - //orderedQuery.setEndKey("a"); - ///orderedQuery.setDescending(false); - //orderedQuery.setLimit(0); - - - QueryEnumerator results = orderedQuery.run(); - str_memberIdList = new String[results.getCount()]; - str_memberNameList = new String[results.getCount()]; - str_memberLoginIdList = new String[results.getCount()]; - str_memberResourceNo = new int[results.getCount()]; - for (Iterator it = results; it.hasNext();) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - str_memberIdList[memberCounter] = (String) properties.get("_id"); - str_memberNameList[memberCounter] = (String) properties.get("firstName") +" "+(String) properties.get("lastName"); - str_memberLoginIdList[memberCounter] = (String) properties.get("login"); - str_memberResourceNo[memberCounter] = 0; - Log.e("MYAPP", " Member Name List: " + str_memberNameList[memberCounter] +" ("+str_memberLoginIdList[memberCounter]+")"); - memberCounter++; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - - - - } - - public void updateLocalResources(String resourceId){ - str_resourceId = resourceId; - final Fuel ful = new Fuel(); - - ful.get(sys_oldSyncServerURL+"/resources/"+resourceId).responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - jsonData = new JSONObject(s); - Log.e("MyCouch", "-- "+jsonData); - } catch (JSONException e) { - e.printStackTrace(); - } - try { - int remote_rating = (int) jsonData.get("sum"); - int remote_timesRated = (int) jsonData.get("timesRated"); - ArrayList remote_comments = (ArrayList) jsonData.get("comments"); - Manager manager = null; - Database ratingHolder; - //int doc_noOfVisits; - //int total_visits=0; - //String max_lastLoginDate=""; - - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - ratingHolder = manager.getDatabase("resourcerating"); - Document retrievedDocument = ratingHolder.getExistingDocument(str_resourceId); - if(retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if (properties.containsKey("sum")) { - doc_rating = (int) properties.get("sum"); - doc_timesRated = (int) properties.get("timesRated"); - ArrayList doc_comments = (ArrayList) properties.get("comments"); - ///total_visits = doc_noOfVisits + remote_NoOfVisits; - - Database resources_db = manager.getExistingDatabase("resources"); - Document resourceDoc = resources_db.getExistingDocument(str_resourceId); - - /// Save total no of visits for member in member database - Map doc_properties = new HashMap(); - doc_properties.putAll(resourceDoc.getProperties()); - doc_properties.put("sum", (doc_rating+remote_rating)); - doc_properties.put("timesRated", (doc_timesRated+remote_timesRated)); - doc_properties.put("timesRated", (doc_timesRated+remote_timesRated)); - resourceDoc.putProperties(doc_properties); - - Log.e("MyCouch Remote", "Rating Sum : ----- "+(doc_rating+remote_rating)); - Log.e("MyCouch Remote", "Times rated : ----- "+ (doc_timesRated+remote_timesRated)); - Log.e("MyCouch Remote", "Times rated : ----- "+ (doc_timesRated+remote_timesRated)); - - } - } - }catch(Exception Err){ - Log.e("MyCouch Remote Error", " : "+ Err.getMessage()); - - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - @Override - public void failure(Request request, Response response, FuelError fuelError) { - Log.e("MyCouch", " "+fuelError); - - } - }); - } - - public void updateLocalMembers(String memberId){ - str_memberID = memberId; - final Fuel ful = new Fuel(); - ful.get(sys_oldSyncServerURL+"/members/"+memberId).responseString(new com.github.kittinunf.fuel.core.Handler() { - @Override - public void success(Request request, Response response, String s) { - try { - jsonData = new JSONObject(s); - Log.e("MyCouch", "-- "+jsonData); - } catch (JSONException e) { - e.printStackTrace(); - } - try { - int remote_NoOfVisits = (int) jsonData.get("visits"); - String remote_lastLoginDate = (String) jsonData.get("lastLoginDate"); - Manager manager = null; - Database visitHolder; - int doc_noOfVisits; - int total_visits=0; - String max_lastLoginDate=""; - - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - visitHolder = manager.getDatabase("visits"); - Document retrievedDocument = visitHolder.getExistingDocument(str_memberID); - if(retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if (properties.containsKey("noOfVisits")) { - doc_noOfVisits = (int) properties.get("noOfVisits"); - total_visits = doc_noOfVisits + remote_NoOfVisits; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - String localLastVisit = (String) properties.get("lastVisits"); - Date localDate = sdf.parse(localLastVisit.substring(0,10)); - Date remoteDate = sdf.parse(remote_lastLoginDate.substring(0,10)); - if(localDate.after(remoteDate)){ - System.out.println("Local is latest date"); - max_lastLoginDate = localLastVisit.toString(); - - }else if(remoteDate.before(localDate)){ - System.out.println("Remote is latest date"); - max_lastLoginDate = remote_lastLoginDate.toString(); - - }else if(localDate.equals(remoteDate)){ - System.out.println("Remote is equal to Local"); - max_lastLoginDate = localLastVisit.toString(); - - } - - Database members_db = manager.getExistingDatabase("members"); - Document memberDoc = members_db.getExistingDocument(str_memberID); - - /// Save total no of visits for member in member database - Map doc_properties = new HashMap(); - doc_properties.putAll(memberDoc.getProperties()); - doc_properties.put("visits", doc_noOfVisits); - doc_properties.put("lastLoginDate", max_lastLoginDate); - memberDoc.putProperties(doc_properties); - - Log.e("MyCouch Remote", "Visits : ----- "+total_visits); - Log.e("MyCouch Remote", "Visit Max Date : ----- "+max_lastLoginDate); - - } - } - }catch(Exception Err){ - Log.e("MyCouch Remote Error", " : "+ Err.getMessage()); - - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - @Override - public void failure(Request request, Response response, FuelError fuelError) { - Log.e("MyCouch", " "+fuelError); - - } - }); - } - - public boolean mydeleteDatabase(String databaseName){ - ///// Delete local visit database (truncate it) - try { - Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database visitHolder = manager.getDatabase(databaseName); - visitHolder.delete(); - return true; - }catch(Exception err){ - Log.e("VISITS", "ERR : " +err.getMessage()); - return false; - } - } - -} diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment0.java b/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment0.java deleted file mode 100644 index 88be6f7..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment0.java +++ /dev/null @@ -1,60 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 20/05/16. - */ -import android.content.SharedPreferences; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -@SuppressWarnings("ALL") -public class TabFragment0 extends Fragment { - TextView lblWelcome,lblNoResouces,lblVisits; - View rootView; - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate, - sys_password,sys_usercouchId,sys_userfirstname,sys_userlastname, - sys_usergender, sys_uservisits= ""; - int sys_uservisits_Int=0; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - rootView = inflater.inflate(R.layout.tab_fragment_0, container, false); - // Restore preferences - settings = getActivity().getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - sys_password = settings.getString("pf_password",""); - sys_usercouchId = settings.getString("pf_usercouchId",""); - sys_userfirstname = settings.getString("pf_userfirstname",""); - sys_userlastname = settings.getString("pf_userlastname",""); - sys_usergender = settings.getString("pf_usergender",""); - sys_uservisits_Int = settings.getInt("pf_uservisits_Int",0); - sys_uservisits= settings.getString("pf_uservisits",""); - - updateUI(); - - return rootView; - - - } - public void updateUI(){ - lblWelcome = (TextView)rootView.findViewById(R.id.lblWelcome); - lblWelcome.setText("Welcome "+sys_userfirstname +" "+sys_userlastname); - - lblVisits= (TextView)rootView.findViewById(R.id.lblVisits); - if(sys_uservisits==""){ - lblVisits.setText(""+sys_uservisits_Int); - }else{ - lblVisits.setText(""+sys_uservisits); - } - - } -} \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment1.java b/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment1.java deleted file mode 100644 index 17f5d3c..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment1.java +++ /dev/null @@ -1,974 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 17/05/16. - */ -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.ProgressDialog; -import android.content.ComponentName; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.AssetFileDescriptor; -import android.content.res.AssetManager; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.support.v4.app.Fragment; -import android.support.v4.content.AsyncTaskLoader; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.RatingBar; -import android.widget.TextView; -import android.widget.Toast; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import net.sf.andpdf.pdfviewer.PdfViewerActivity; - -import com.couchbase.lite.Attachment; -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; - -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -import com.coremedia.iso.boxes.Container; -import com.googlecode.mp4parser.authoring.Movie; -import com.googlecode.mp4parser.authoring.Track; -import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder; -import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator; -import com.googlecode.mp4parser.authoring.tracks.AppendTrack; -import com.googlecode.mp4parser.authoring.tracks.CroppedTrack; -import com.googlecode.mp4parser.authoring.tracks.TextTrackImpl; - -@SuppressWarnings("ALL") -public class TabFragment1 extends Fragment { - - ListView list; - public TabFragment1 CustomListView = null; - public ArrayList CustomListViewValuesArr = new ArrayList(); - - - - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - CouchViews chViews = new CouchViews(); - Context context = null; - - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate, - sys_password,sys_usercouchId,sys_userfirstname,sys_userlastname, - sys_usergender, sys_uservisits= ""; - Object[] sys_membersWithResource; - int resourceNo=0; - - String resourceIdList[]; - String resourceTitleList[]; - int rsLstCnt=0; - - ImageView[] imageView; - static Uri videoURl; - static Intent intent; - - /////////////////////////// - private RatingBar ratingBar; - private TextView txtRatingValue; - private EditText txtComment; - - /////////////////// - // Log tag - private static final String TAG = TabFragment1.class.getSimpleName(); - - // Movies json url - private static final String url = "http://api.androidhive.info/json/movies.json"; - private ProgressDialog pDialog; - private List resourceList = new ArrayList(); - private ListView listView; - private CustomListAdapter adapter; - - AssetManager assetManager; - AssetFileDescriptor afd; - String indexFilePath; - - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - context = container.getContext(); - - CustomListView = this; - assetManager = getActivity().getAssets(); - - settings = context.getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - sys_password = settings.getString("pf_password",""); - sys_usercouchId = settings.getString("pf_usercouchId",""); - sys_userfirstname = settings.getString("pf_userfirstname",""); - sys_userlastname = settings.getString("pf_userlastname",""); - sys_usergender = settings.getString("pf_usergender",""); - sys_uservisits = settings.getString("pf_uservisits",""); - - - Set mwr = settings.getStringSet("membersWithResource",null); - try{ - sys_membersWithResource = mwr.toArray(); - Log.e("MYAPP", " membersWithResource = "+sys_membersWithResource.length); - - }catch(Exception err){ - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - - - resourceList.clear(); - LoadShelfResourceList(); - - View rootView = inflater.inflate(R.layout.tab_fragment_1, container, false); - - listView = (ListView) rootView.findViewById(R.id.list); - adapter = new CustomListAdapter(this.getActivity(), resourceList); - try { - adapter = new CustomListAdapter(this.getActivity(), resourceList); - listView.setAdapter(adapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(AdapterView adapter, View v, int position, long id) { - // todo change rating style - RateResourceDialog(resourceIdList[position],resourceTitleList[position]); - openDoc(resourceIdList[position]); - } - }); - }catch (Exception err){ - Log.e("adapter", " "+err); - } - - //////copyAssets(); - //copyAPK(R.raw.adobe_reader, "adobe_reader.apk"); - //copyAPK(R.raw.firefox_49_0_multi_android, "firefox_49_0_multi_android.apk"); - //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b"))); - return rootView; - - } - - private void copyFile(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024]; - int read; - while ((read = in.read(buffer)) != -1) - { - out.write(buffer, 0, read); - } - } - - - private void copyAPK(int resource, String apkUrl) { - InputStream in = getResources().openRawResource(resource); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp2"); - if (!myDir.exists()){ - myDir.mkdirs(); - } - File dst = new File(myDir,apkUrl); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", "Adobe Reader Copied "+ dst.toString()); - }catch(Exception err){ - err.printStackTrace(); - } /// - - - } - - public void openDoc(String docId) { - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - String oppenwith = (String) res_doc.getProperty("openWith"); - Log.e("MYAPP", " membersWithID = " + docId +"and Open with "+ oppenwith); - List attmentNames = res_doc.getCurrentRevision().getAttachmentNames(); - if(oppenwith.equalsIgnoreCase("HTML")){ - /*if (attmentNames.size() <= 1) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openImage(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - } - }*/ - indexFilePath=null; - if (attmentNames.size() > 1) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - downloadHTMLContent(docId, (String) attmentNames.get(cnt)); - } - if(indexFilePath!=null){ - openHTML(indexFilePath); - } - }else{ - openImage(docId, (String) attmentNames.get(0), getExtension(attmentNames.get(0))); - } - - }else if(oppenwith.equalsIgnoreCase("PDF.js")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openPDF(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - - }else if(oppenwith.equalsIgnoreCase("MP3")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - - }else if(oppenwith.equalsIgnoreCase("Bell-Reader")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openPDF(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - }else if(oppenwith.equalsIgnoreCase("Flow Video Player")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - - }else if(oppenwith.equalsIgnoreCase("BeLL Video Book Player")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - - } - } - - }else if(oppenwith.equalsIgnoreCase("Native Video")){ - if (attmentNames.size() > 0) { - for (int cnt = 0; cnt < attmentNames.size(); cnt++) { - openAudioVideo(docId, (String) attmentNames.get(cnt), getExtension(attmentNames.get(cnt))); - break; - } - } - - } - } catch (Exception Er) { - - } - } - - public void openHTML(String index) { - final String mainFile = index; - try { - try{ - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setPackage("org.mozilla.firefox"); - intent.setDataAndType(Uri.parse(mainFile),"text/html"); - intent.setComponent(new ComponentName("org.mozilla.firefox", "org.mozilla.firefox.App")); - this.startActivity(intent); - ///intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - }catch(Exception err){ - Log.e("Error", err.getMessage()); - File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir,"firefox_49_0_multi_android.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - - } catch (Exception Er) { - Er.printStackTrace(); - - } - - } - - public void downloadHTMLContent(String docId, final String fileName) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - int lth= (int) fileAttachment.getLength(); - try{ - InputStream in = fileAttachment.getContent(); - String root = Environment.getExternalStorageDirectory().toString(); - File newDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2/"+docId); - if (!newDir.exists()){ - newDir.mkdirs(); - } - - File myDir = new File(root + "/ole_temp2/"+docId); - File dst = new File(myDir,fileAttachment.getName().replace(" ", "")); - String filepath[]= dst.toString().split("/"); - int defaultLength = myDir.getPath().split("/").length; - String path= myDir.getPath(); - //Log.e("tag", " Location "+ dst.toString() + " Default :" + defaultLength + " fpath: "+filepath.length); - for(int cnt= defaultLength; cnt < (filepath.length-1);cnt++){ - path = path +"/"+ filepath[cnt]; - myDir = new File(path); - if (!myDir.exists()){ - myDir.mkdirs(); - } - } - try { - BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dst)); - byte[] buff = new byte[1024]; - int len; - while ((len = in.read(buff)) > 0) { - out.write(buff, 0, len); - } - - Log.e("tag", " Saved "+ dst.toString()+" Original length: "+ lth ); - - in.close(); - out.close(); - if(dst.getName().equalsIgnoreCase("index.html") && (filepath.length - defaultLength)==1 ){ - indexFilePath = dst.toString(); - } - - }catch(Exception err){ - Log.e("tag", " Saving "+ err.getMessage()); - } - }catch(Exception err){ - err.printStackTrace(); - } - } catch (Exception Er) { - Er.printStackTrace(); - - } - } - - public void openImage(String docId, final String fileName, String player) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - try{ - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()){ - myDir.mkdirs(); - } - File dst = new File(myDir,fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF "+ dst.toString()); - }catch(Exception err){ - err.printStackTrace(); - } - Intent intent = new Intent(); - intent.setAction(android.content.Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "image/*"); - //Log.e("tag", " URL Path "+ Uri.fromFile(dst).getPath());; - startActivity(intent); - }catch(Exception err){ - - } - } catch (Exception Er) { - Er.printStackTrace(); - - } - - } - - public static void mkDirs(File root, List dirs, int depth) { - if (depth == 0) return; - for (String s : dirs) { - File subdir = new File(root, s); - subdir.mkdir(); - mkDirs(subdir, dirs, depth - 1); - } - } - - public void openPDF(String docId, final String fileName, String player) { - final String myfilename = fileName; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - final Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - - AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create(); - alertDialog.setTitle("Open Document"); - alertDialog.setMessage("Select which application you wish to open document with"); - alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Adobe PDF Reader", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - try{ - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()){ - myDir.mkdirs(); - } - File dst = new File(myDir,fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF "+ dst.toString()); - }catch(Exception err){ - err.printStackTrace(); - } /// - - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setPackage("com.adobe.reader"); - intent.setDataAndType(Uri.fromFile(dst), "application/pdf"); - intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivity(intent); - - - }catch(Exception err){ - File myDir = new File(Environment.getExternalStorageDirectory().toString() + "/ole_temp2"); - File dst = new File(myDir,"adobe_reader.apk"); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setDataAndType(Uri.fromFile(dst), "application/vnd.android.package-archive"); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - - } }); - - alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "In-App PDF Viewer", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - - try{ - File src = new File(fileAttachment.getContentURL().getPath()); - InputStream in = new FileInputStream(src); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - if (!myDir.exists()){ - myDir.mkdirs(); - } - File dst = new File(myDir,fileAttachment.getName().replace(" ", "")); - try { - FileOutputStream out = new FileOutputStream(dst); - byte[] buff = new byte[1024]; - int read = 0; - while ((read = in.read(buff)) > 0) { - out.write(buff, 0, read); - } - in.close(); - out.close(); - Log.e("tag", " Copied PDF "+ dst.toString()); - }catch(Exception err){ - err.printStackTrace(); - } /// - - - Intent intent = new Intent(getActivity(), MyPdfViewerActivity.class); - Log.e("tag", " URL Path "+ Uri.fromFile(dst).getPath()); - intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, Uri.fromFile(dst).getPath()); - startActivity(intent); - - - }catch(Exception err){ - - } - }}); - alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - - - }}); - alertDialog.show(); - - } catch (Exception Er) { - Er.printStackTrace(); - - } - - } - - public void openAudioVideo(String docId,String fileName, String player) { - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database res_Db = manager.getExistingDatabase("resources"); - Document res_doc = res_Db.getExistingDocument(docId); - Attachment fileAttachment = res_doc.getCurrentRevision().getAttachment(fileName); - - File src = new File(fileAttachment.getContentURL().getPath()); - String root = Environment.getExternalStorageDirectory().toString(); - File myDir = new File(root + "/ole_temp"); - deleteDirectory(myDir); - myDir.mkdirs(); - String diskFileName = fileAttachment.getName(); - diskFileName = diskFileName.replace(" ", ""); - File dst = new File(myDir,diskFileName); - - InputStream in = new FileInputStream(src); - OutputStream out = new FileOutputStream(dst); - - // Transfer bytes from in to out - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - in.close(); - out.close(); - dst.setReadable(true); - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(dst).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent = new Intent(); - intent.setAction(Intent.ACTION_VIEW); - Log.e("tag","- "+ mimetype +" - "); - - if(mimetype=="audio/mpeg"){ - intent.setDataAndType(Uri.fromFile(dst),mimetype); - getActivity().startActivity(intent); - }else{ - try { - intent.setDataAndType(Uri.fromFile(dst),mimetype); - getActivity().startActivity(intent); - }catch (Exception Er) { - Log.e("tag", Er.getMessage()); - } - } - } catch (Exception Er) { - Log.e("tag", Er.getMessage()); - } - } - - boolean deleteDirectory(File path) { - if(path.exists()) { - if (path.isDirectory()) { - File[] files = path.listFiles(); - for (int i=0; i resource_properties = null; - for (Iterator it = results; it.hasNext(); ) { - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map properties = doc.getProperties(); - if(memberId.equals((String) properties.get("memberId"))) { - String myresTitile = ""; - String myresId = ""; - String myresType = ""; - String myresDec = ""; - String myresExt = ""; - try { - Document resource_doc = resource_Db.getExistingDocument((String) properties.get("resourceId")); - Log.e("tag", "RES ID "+ (String) properties.get("resourceId")); - try { - resource_properties = resource_doc.getProperties(); - }catch(Exception errs){ - Log.e("tag", "OBJECT ERROR "+ errs.toString()); - } - myresTitile = (String) resource_properties.get("title")+""; - myresId = (String) properties.get("resourceId")+""; - myresDec = (String) resource_properties.get("author")+""; - myresType = (String) resource_properties.get("averageRating")+""; - myresExt = (String) resource_properties.get("openWith")+""; - resourceIdList[rsLstCnt]=myresId; - resourceTitleList[rsLstCnt]=myresTitile; - rsLstCnt++; - }catch(Exception err){ - - - Log.e("tag", "ERROR "+ err.getMessage()); - myresTitile = "Unknown resource .. "; - myresId = ""; - myresDec = "Not yet downloaded.. Please sync"; - myresType = ""; - rsLstCnt++; - - } - - Resource resource = new Resource(); - resource.setTitle(myresTitile); - resource.setThumbnailUrl(getIconType(myresExt)); - resource.setDescription(myresDec); - resource.setRating(myresType); - - resource.setGenre(null); - // adding resource to resources array - resourceList.add(resource); - resourceNo++; - } - } - db.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public int getIconType(String myresExt){ - - int img = R.drawable.web; - switch (myresExt){ - case "Flow Video Player": - img = R.drawable.video; - break; - case "MP3": - img = R.drawable.mp3; - break; - case "PDF.js": - img = R.drawable.pdf; - break; - case "": - img = R.drawable.web; - break; - default: - img = R.drawable.web; - break; - } - return img; - } - - - public void RateResourceDialog(String resourceId, String title){ - // custom dialog - final String resourceID = resourceId; - final Dialog dialog = new Dialog(context); - dialog.setContentView(R.layout.rate_resource_dialog); - dialog.setTitle("Rate this resource"); - - txtComment = (EditText) dialog.findViewById(R.id.editTextComment); - - - ratingBar = (RatingBar) dialog.findViewById(R.id.ratingBar); - ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { - public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) { - ///txtRatingValue.setText(String.valueOf(rating)); - - } - }); - - Button dialogButton = (Button) dialog.findViewById(R.id.btnRateResource); - dialogButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - saveRating(ratingBar.getRating(),String.valueOf(txtComment.getText()),resourceID); - // openDoc(resourceIdList[position]); - dialog.dismiss(); - } - }); - - dialog.show(); - - } - - - public int saveRating(float rate,String comment,String resourceId){ - AndroidContext androidContext = new AndroidContext(getActivity()); - Manager manager = null; - Database resourceRating; - int doc_rating,doc_timesRated; String doc_comments; - - Toast.makeText(getActivity(),String.valueOf(rate),Toast.LENGTH_SHORT).show(); - ArrayList commentList = new ArrayList(); - - try { - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - resourceRating = manager.getDatabase("resourcerating"); - Document retrievedDocument = resourceRating.getExistingDocument(resourceId); - if(retrievedDocument != null) { - Map properties = retrievedDocument.getProperties(); - if(properties.containsKey("sum")){ - doc_rating = (int) properties.get("sum") ; - doc_timesRated = (int) properties.get("timesRated") ; - ///doc_comments = (String) properties.get("comments"); - commentList = (ArrayList) properties.get("comments"); - commentList.add(comment); - Map newProperties = new HashMap(); - newProperties.putAll(retrievedDocument.getProperties()); - newProperties.put("sum", (doc_rating + rate)); - newProperties.put("timesRated", doc_timesRated + 1); - newProperties.put("comments", commentList); - retrievedDocument.putProperties(newProperties); - return doc_rating; - } - } - else{ - Document newdocument = resourceRating.getDocument(resourceId); - Map newProperties = new HashMap(); - newProperties.put("sum", 1); - newProperties.put("timesRated", 1); - commentList.add(comment); - newProperties.put("comments", commentList); - newdocument.putProperties(newProperties); - return 1; - } - - - }catch(Exception err){ - Log.e("VISITS", "ERR : " +err.getMessage()); - - - } - - return 0; - - } - - - - public class EditMovieTask extends AsyncTaskLoader { - - private int mType; - - public EditMovieTask(Context context, int type) { - super(context); - mType = type; - forceLoad(); - } - - @Override - public Boolean loadInBackground() { - switch (mType) { - case 0: - return append(); - case 1: - return crop(); - case 2: - return subTitle(); - } - - return false; - } - private boolean append() { - try { - // 複数の動画を読み込み - String f1 = videoURl.getPath(); - //String f1 = Environment.getExternalStorageDirectory() + "/ole_temp2/bgin.mp4"; - ////String f2 = Environment.getExternalStorageDirectory() + "/sample2.mp4"; - String f2 = videoURl.getPath(); - Log.e("tag","Video URL "+ f2 +" - "); - - Movie[] inMovies = new Movie[]{ - MovieCreator.build(f1), - MovieCreator.build(f2)}; - - // 1つのファイルに結合 - List videoTracks = new LinkedList(); - List audioTracks = new LinkedList(); - for (Movie m : inMovies) { - for (Track t : m.getTracks()) { - if (t.getHandler().equals("soun")) { - audioTracks.add(t); - } - if (t.getHandler().equals("vide")) { - videoTracks.add(t); - } - } - } - Movie result = new Movie(); - if (audioTracks.size() > 0) { - result.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()]))); - } - if (videoTracks.size() > 0) { - result.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()]))); - } - - // 出力 - Container out = new DefaultMp4Builder().build(result); - String outputFilePath = Environment.getExternalStorageDirectory() + "/ole_temp/output_append.mp4"; - FileOutputStream fos = new FileOutputStream(new File(outputFilePath)); - out.writeContainer(fos.getChannel()); - fos.close(); - - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(outputFilePath)).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(new File(outputFilePath)),mimetype); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - getContext().startActivity(intent); - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - - return true; - } - - private boolean crop() { - try { - // オリジナル動画を読み込み - ///String filePath = Environment.getExternalStorageDirectory() + "/sample1.mp4"; - String filePath = videoURl.getPath(); - Movie originalMovie = MovieCreator.build(filePath); - - // 分割 - Track track = originalMovie.getTracks().get(0); - Movie movie = new Movie(); - movie.addTrack(new AppendTrack(new CroppedTrack(track, 200, 400))); - - // 出力 - Container out = new DefaultMp4Builder().build(movie); - String outputFilePath = Environment.getExternalStorageDirectory() + "/output_crop.mp4"; - FileOutputStream fos = new FileOutputStream(new File(outputFilePath)); - out.writeContainer(fos.getChannel()); - fos.close(); - - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(outputFilePath)).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(new File(outputFilePath)),mimetype); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - getContext().startActivity(intent); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - - private boolean subTitle() { - try { - // オリジナル動画を読み込み - ///String filePath = Environment.getExternalStorageDirectory() + "/sample1.mp4"; - String filePath = videoURl.getPath(); - Movie countVideo = MovieCreator.build(filePath); - - // SubTitleを追加 - TextTrackImpl subTitleEng = new TextTrackImpl(); - subTitleEng.getTrackMetaData().setLanguage("eng"); - - subTitleEng.getSubs().add(new TextTrackImpl.Line(0, 1000, "Five")); - subTitleEng.getSubs().add(new TextTrackImpl.Line(1000, 2000, "Four")); - subTitleEng.getSubs().add(new TextTrackImpl.Line(2000, 3000, "Three")); - subTitleEng.getSubs().add(new TextTrackImpl.Line(3000, 4000, "Two")); - subTitleEng.getSubs().add(new TextTrackImpl.Line(4000, 5000, "one")); - countVideo.addTrack(subTitleEng); - - // 出力 - Container container = new DefaultMp4Builder().build(countVideo); - String outputFilePath = Environment.getExternalStorageDirectory() + "/output_subtitle.mp4"; - FileOutputStream fos = new FileOutputStream(outputFilePath); - FileChannel channel = fos.getChannel(); - container.writeContainer(channel); - fos.close(); - - - String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(outputFilePath)).toString()); - String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); - intent.setDataAndType(Uri.fromFile(new File(outputFilePath)),mimetype); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - getContext().startActivity(intent); - - } catch (Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - - - - } - -} - diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment2.java b/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment2.java deleted file mode 100644 index a7054f4..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment2.java +++ /dev/null @@ -1,289 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 17/05/16. - */ -import android.app.Dialog; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.AssetFileDescriptor; -import android.content.res.AssetManager; -import android.net.Uri; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.Button; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.TextView; - -import com.couchbase.lite.Database; -import com.couchbase.lite.Document; -import com.couchbase.lite.Manager; -import com.couchbase.lite.Query; -import com.couchbase.lite.QueryEnumerator; -import com.couchbase.lite.QueryRow; -import com.couchbase.lite.android.AndroidContext; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@SuppressWarnings("ALL") -public class TabFragment2 extends Fragment { - - ListView list; - public TabFragment2 CustomListView = null; - public ArrayList CustomListViewValuesArr = new ArrayList(); - - public static final String PREFS_NAME = "MyPrefsFile"; - SharedPreferences settings; - CouchViews chViews = new CouchViews(); - Context context = null; - - String sys_oldSyncServerURL,sys_username,sys_lastSyncDate, - sys_password,sys_usercouchId,sys_userfirstname,sys_userlastname, - sys_usergender, sys_uservisits= ""; - Object[] sys_membersWithResource; - int courseNo=0; - - String resourceIdList[]; - String courseIdList[]; - int rsLstCnt=0; - int csLstCnt=0; - - ImageView[] imageView; - static Uri videoURl; - static Intent intent; - /////////////////////////// - - // Log tag - private static final String TAG = TabFragment2.class.getSimpleName(); - - private List courses = new ArrayList(); - private ListView listView; - private CourceListCustomAdapter adapter; - - AssetManager assetManager; - AssetFileDescriptor afd; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - context = container.getContext(); - - CustomListView = this; - assetManager = getActivity().getAssets(); - - settings = context.getSharedPreferences(PREFS_NAME, 0); - sys_username = settings.getString("pf_username",""); - sys_oldSyncServerURL = settings.getString("pf_sysncUrl",""); - sys_lastSyncDate = settings.getString("pf_lastSyncDate",""); - sys_password = settings.getString("pf_password",""); - sys_usercouchId = settings.getString("pf_usercouchId",""); - sys_userfirstname = settings.getString("pf_userfirstname",""); - sys_userlastname = settings.getString("pf_userlastname",""); - sys_usergender = settings.getString("pf_usergender",""); - sys_uservisits = settings.getString("pf_uservisits",""); - - - Set mwr = settings.getStringSet("membersWithResource",null); - try{ - sys_membersWithResource = mwr.toArray(); - Log.e("MYAPP", " membersWithResource = "+sys_membersWithResource.length); - - }catch(Exception err){ - Log.e("MYAPP", " Error creating sys_membersWithResource"); - } - - courses.clear(); - LoadCourseList(); - - View rootView = inflater.inflate(R.layout.tab_fragment_2, container, false); - - listView = (ListView) rootView.findViewById(R.id.list); - adapter = new CourceListCustomAdapter(this.getActivity(), courses); - listView.setAdapter(adapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(AdapterView adapter, View v, int position, long id) { - courseDetails(courseIdList[position]); - //openDoc(resourceIdList[position]); - } - }); - - return rootView; - - } - - public String getExtension(final String filename) { - if (filename == null){ - return null; - } - final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1); - final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1; - final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash); - return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1); - } - - public void LoadCourseList() { - - String memberId = sys_usercouchId; - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - try { - - Log.d("tag2", "Loading Course List "); - - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database db = manager.getExistingDatabase("membercourseprogress"); - Database groups_Db = manager.getExistingDatabase("groups"); - Database coursestep_Db = manager.getExistingDatabase("coursestep"); - Query orderedQuery = chViews.ReadCourseList(db).createQuery(); - orderedQuery.setDescending(true); - - //orderedQuery.setStartKey(memberId); - //orderedQuery.setLimit(0); - QueryEnumerator results = orderedQuery.run(); - courseIdList = new String[results.getCount()]; - csLstCnt = 0; - Map course_properties = null; - - for (Iterator it = results; it.hasNext(); ) { - - QueryRow row = it.next(); - String docId = (String) row.getValue(); - Document doc = db.getExistingDocument(docId); - Map membercourseProperties = doc.getProperties(); - if(memberId.equals((String) membercourseProperties.get("memberId"))) { - ArrayList arr_courseStepsIds = new ArrayList(); - ArrayList obj_courseResult = new ArrayList(); - ArrayList obj_courseStatus = new ArrayList(); - arr_courseStepsIds = (ArrayList) membercourseProperties.get("stepsIds"); - obj_courseResult = (ArrayList) membercourseProperties.get("stepsResult"); - obj_courseStatus = (ArrayList) membercourseProperties.get("stepsStatus"); - - try { - for (int i = 0; i < arr_courseStepsIds.size(); i++) { - if(arr_courseStepsIds.size()>0) { - Document groups_doc = groups_Db.getExistingDocument((String) membercourseProperties.get("courseId")); - Map groups_Properties = groups_doc.getProperties(); - - Log.d("tag2", "Inside value is: " + groups_doc.getId()); - - CourseList courselst = new CourseList(); - courselst.setTitle((String) groups_Properties.get("CourseTitle")); - courselst.setThumbnailUrl(getIconType("")); - String desc = (String) groups_Properties.get("description"); - if (desc.length() > 250){ - desc = desc.substring(0, 230)+" ..."; - } - courselst.setDescription(desc); - courselst.setRating((String) groups_Properties.get("endDate") +" "+ (String) groups_Properties.get("endTime")); - courselst.setGenre(null); - ////courseIdList[csLstCnt] = (String) arr_courseStepsIds.get(i); - courseIdList[csLstCnt] = (String) groups_Properties.get("_id"); - // adding resource to resources array - courses.add(courselst); - courseNo++; - } - } - - - }catch(Exception err){ - Log.d("tag", "Error "+ err.getLocalizedMessage()); - } - - Log.d("tag2", "Value is: "+arr_courseStepsIds.size()); - - ///String value = arr_courseStepsIds.toString(); - } - - - } - - db.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - public int getIconType(String myresExt){ - - int img = R.drawable.web; - switch (myresExt){ - case "Flow Video Player": - img = R.drawable.video; - break; - case "MP3": - img = R.drawable.mp3; - break; - case "PDF.js": - img = R.drawable.pdf; - break; - case "": - img = R.drawable.web; - break; - default: - img = R.drawable.web; - break; - } - return img; - } - - - - public void courseDetails(String courseID){ - // custom dialog - final String in_courseID = courseID; - final Dialog dialog = new Dialog(context); - dialog.setContentView(R.layout.course_details); - ////dialog.setTitle("Course Info"); - - try{ - AndroidContext androidContext = new AndroidContext(context); - Manager manager = null; - manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS); - Database groups_Db = manager.getExistingDatabase("groups"); - Document groups_doc = groups_Db.getExistingDocument(courseID); - Map groups_Properties = groups_doc.getProperties(); - - Log.d("tag2", "Inside Course ID: " + in_courseID); - - TextView txttitle = (TextView) dialog.findViewById(R.id.txtTitle); - TextView txtdesc = (TextView) dialog.findViewById(R.id.txtDesc); - - txttitle.setText((String) groups_Properties.get("CourseTitle")); - txtdesc.setText((String) groups_Properties.get("description")); - dialog.setTitle("Progress : "+ readCourseProgress(in_courseID)); - - }catch(Exception err){ - Log.d("tag", "Error "+ err.getMessage()); - } - - Button dialogOpenCourseButton = (Button) dialog.findViewById(R.id.btnLaunchCourse); - dialogOpenCourseButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent intent = new Intent(getActivity(),Course.class); - intent.putExtra("courseID", in_courseID); - startActivity(intent); - dialog.dismiss(); - } - }); - - dialog.show(); - - } - public String readCourseProgress(String courseID){ - String progrs = " 2/4"; - - return progrs; - } - } \ No newline at end of file diff --git a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment3.java b/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment3.java deleted file mode 100644 index d6aed68..0000000 --- a/app/src/main/java/pbell/offline/ole/org/pbell/TabFragment3.java +++ /dev/null @@ -1,18 +0,0 @@ -package pbell.offline.ole.org.pbell; - -/** - * Created by leonardmensah on 17/05/16. - */ -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -public class TabFragment3 extends Fragment { - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return inflater.inflate(R.layout.tab_fragment_3, container, false); - } -} \ No newline at end of file diff --git a/app/src/main/ole_int_logo-web.png b/app/src/main/ole_int_logo-web.png deleted file mode 100755 index 46f6d83..0000000 Binary files a/app/src/main/ole_int_logo-web.png and /dev/null differ diff --git a/app/src/main/ole_logo-web.png b/app/src/main/ole_logo-web.png deleted file mode 100755 index 46f6d83..0000000 Binary files a/app/src/main/ole_logo-web.png and /dev/null differ diff --git a/app/src/main/ole_logo_trans-web.png b/app/src/main/ole_logo_trans-web.png deleted file mode 100755 index 46f6d83..0000000 Binary files a/app/src/main/ole_logo_trans-web.png and /dev/null differ diff --git a/app/src/main/res/app/src/main/res/values-af-rZA/strings.xml b/app/src/main/res/app/src/main/res/values-af-rZA/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-af-rZA/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-ar-rSA/strings.xml b/app/src/main/res/app/src/main/res/values-ar-rSA/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-ar-rSA/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/app/src/main/res/values-de-rDE/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-de-rDE/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-el-rGR/strings.xml b/app/src/main/res/app/src/main/res/values-el-rGR/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-el-rGR/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-en-rUS/strings.xml b/app/src/main/res/app/src/main/res/values-en-rUS/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-en-rUS/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/app/src/main/res/values-es-rES/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-es-rES/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/app/src/main/res/values-fr-rFR/strings.xml deleted file mode 100644 index 8ba6e37..0000000 --- a/app/src/main/res/app/src/main/res/values-fr-rFR/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Réglages - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/app/src/main/res/values-it-rIT/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-it-rIT/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-iw-rIL/strings.xml b/app/src/main/res/app/src/main/res/values-iw-rIL/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-iw-rIL/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-ja-rJP/strings.xml b/app/src/main/res/app/src/main/res/values-ja-rJP/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-ja-rJP/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-ko-rKR/strings.xml b/app/src/main/res/app/src/main/res/values-ko-rKR/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-ko-rKR/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-pl-rPL/strings.xml b/app/src/main/res/app/src/main/res/values-pl-rPL/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-pl-rPL/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/app/src/main/res/values-pt-rPT/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-pt-rPT/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/app/src/main/res/values-ru-rRU/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-ru-rRU/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/app/src/main/res/values-tr-rTR/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-tr-rTR/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-vi-rVN/strings.xml b/app/src/main/res/app/src/main/res/values-vi-rVN/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-vi-rVN/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/app/src/main/res/values-zh-rCN/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-zh-rCN/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/app/src/main/res/values-zh-rTW/strings.xml deleted file mode 100644 index a9c3e6d..0000000 --- a/app/src/main/res/app/src/main/res/values-zh-rTW/strings.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - PLANET - Sync Server Url - Sync Device - Settings - Profile - Help - About - Hello World from section: %1$d - Take-Home - - Take Home - It appears your device hasn\'t yet been linked to the BeLL network. - If you know your BeLL server\'s url, please enter it bellow or contact your coach / group leader for assistance - BeLL Server Url - Save and Proceed - - Achievements - myLibrary - Courses Progress - myMeetups - - Visits - Opened Resources - - Sync server url - Save changes - - Last sync date - Synchronize device with server - Push Changes - Pull Changes - Wipe Clean - Sync Materials - - Username - Password (optional) - Sign in - Sign-in - This password is incorrect - This field is required - \"Contacts permissions are needed for providing email completions.\" - - Sync Device - First Time Configuration - Synchronize With Server - Close - Download Resources - Open Course - Course - My Tutors - My Home - Library - Courses - Meetups - Logout - Settings - Feedback - Member Login - Welcome - Demo Mode - Login - Password - test - Setup - This material is not on this device (offline). Do you want to open it online or download into this device. - Download this - Open Online - Download All - Multiple material download - Single material download - JSON Replication Disabled - FILE STREAMING DISABLED - Update - Become a member - Language - Home - Dummy Button - DUMMY\nCONTENT - User_Dashboard - myCourses - myTeams - - Hello blank fragment - diff --git a/app/src/main/res/drawable-v21/ic_menu_camera.xml b/app/src/main/res/drawable-v21/ic_menu_camera.xml deleted file mode 100644 index 0d9ea10..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_camera.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable-v21/ic_menu_gallery.xml b/app/src/main/res/drawable-v21/ic_menu_gallery.xml deleted file mode 100644 index f6872c4..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_gallery.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable-v21/ic_menu_manage.xml b/app/src/main/res/drawable-v21/ic_menu_manage.xml deleted file mode 100644 index c1be60b..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_manage.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/ic_menu_send.xml b/app/src/main/res/drawable-v21/ic_menu_send.xml deleted file mode 100644 index 00c668c..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_send.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable-v21/ic_menu_share.xml b/app/src/main/res/drawable-v21/ic_menu_share.xml deleted file mode 100644 index a28fb9e..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_share.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable-v21/ic_menu_slideshow.xml b/app/src/main/res/drawable-v21/ic_menu_slideshow.xml deleted file mode 100644 index 209aa64..0000000 --- a/app/src/main/res/drawable-v21/ic_menu_slideshow.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/app/src/main/res/drawable-xxhdpi/test_border_darkblue.xml b/app/src/main/res/drawable/border_darkblue.xml similarity index 100% rename from app/src/main/res/drawable-xxhdpi/test_border_darkblue.xml rename to app/src/main/res/drawable/border_darkblue.xml diff --git a/app/src/main/res/drawable-hdpi/listview_gradient_bg.xml b/app/src/main/res/drawable/listview_gradient_bg.xml similarity index 100% rename from app/src/main/res/drawable-hdpi/listview_gradient_bg.xml rename to app/src/main/res/drawable/listview_gradient_bg.xml diff --git a/app/src/main/res/drawable-hdpi/listview_gradient_bg_hover.xml b/app/src/main/res/drawable/listview_gradient_bg_hover.xml similarity index 100% rename from app/src/main/res/drawable-hdpi/listview_gradient_bg_hover.xml rename to app/src/main/res/drawable/listview_gradient_bg_hover.xml diff --git a/app/src/main/res/drawable-hdpi/listview_image_bg.xml b/app/src/main/res/drawable/listview_image_bg.xml similarity index 100% rename from app/src/main/res/drawable-hdpi/listview_image_bg.xml rename to app/src/main/res/drawable/listview_image_bg.xml diff --git a/app/src/main/res/drawable-hdpi/listview_selector.xml b/app/src/main/res/drawable/listview_selector.xml similarity index 100% rename from app/src/main/res/drawable-hdpi/listview_selector.xml rename to app/src/main/res/drawable/listview_selector.xml diff --git a/app/src/main/res/drawable-xxhdpi/rounded_corners_darkblue_btn.xml b/app/src/main/res/drawable/rounded_corners_darkblue_btn.xml similarity index 100% rename from app/src/main/res/drawable-xxhdpi/rounded_corners_darkblue_btn.xml rename to app/src/main/res/drawable/rounded_corners_darkblue_btn.xml diff --git a/app/src/main/res/drawable-xhdpi/rounderd_corner_blue_white.xml b/app/src/main/res/drawable/rounderd_corner_blue_white.xml similarity index 100% rename from app/src/main/res/drawable-xhdpi/rounderd_corner_blue_white.xml rename to app/src/main/res/drawable/rounderd_corner_blue_white.xml diff --git a/app/src/main/res/layout/activity_course.xml b/app/src/main/res/layout/activity_course.xml deleted file mode 100644 index abff70a..0000000 --- a/app/src/main/res/layout/activity_course.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/layout/activity_dashboard.xml b/app/src/main/res/layout/activity_dashboard.xml deleted file mode 100644 index 10d1838..0000000 --- a/app/src/main/res/layout/activity_dashboard.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/layout/activity_downloading_items.xml b/app/src/main/res/layout/activity_downloading_items.xml new file mode 100644 index 0000000..eb633e6 --- /dev/null +++ b/app/src/main/res/layout/activity_downloading_items.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + - - - - - diff --git a/app/src/main/res/layout/simplerow.xml b/app/src/main/res/layout/simplerow.xml deleted file mode 100644 index 0da151c..0000000 --- a/app/src/main/res/layout/simplerow.xml +++ /dev/null @@ -1,7 +0,0 @@ - - \ No newline at end of file diff --git a/app/src/main/res/layout/syncurl_dialog.xml b/app/src/main/res/layout/syncurl_dialog.xml deleted file mode 100644 index 93739fa..0000000 --- a/app/src/main/res/layout/syncurl_dialog.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - -