├── settings.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── app ├── src │ └── main │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── drawable-hdpi │ │ │ └── ic_share_white_24dp.png │ │ ├── drawable-mdpi │ │ │ └── ic_share_white_24dp.png │ │ ├── drawable-xhdpi │ │ │ └── ic_share_white_24dp.png │ │ ├── drawable-xxhdpi │ │ │ └── ic_share_white_24dp.png │ │ ├── drawable-xxxhdpi │ │ │ └── ic_share_white_24dp.png │ │ ├── values │ │ │ ├── dimens.xml │ │ │ └── strings.xml │ │ ├── menu │ │ │ ├── main_menu.xml │ │ │ └── action_mode_menu.xml │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── layout │ │ │ ├── activity_main.xml │ │ │ └── word_layout.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── ichi2 │ │ └── apisample │ │ ├── AnkiDroidConfig.java │ │ ├── AnkiDroidHelper.java │ │ └── MainActivity.java └── build.gradle ├── README.md ├── .gitignore ├── AnkiDroid_Sync.prf.xml ├── gradlew.bat ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.enableJetifier=true 2 | android.useAndroidX=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_share_white_24dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/drawable-hdpi/ic_share_white_24dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_share_white_24dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/drawable-mdpi/ic_share_white_24dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_share_white_24dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/drawable-xhdpi/ic_share_white_24dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_share_white_24dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/drawable-xxhdpi/ic_share_white_24dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxxhdpi/ic_share_white_24dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ankidroid/apisample/HEAD/app/src/main/res/drawable-xxxhdpi/ic_share_white_24dp.png -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # apisample 2 | Sample project for the AnkiDroid API. 3 | 4 | Developers should see [the Wiki](https://github.com/ankidroid/Anki-Android/wiki/AnkiDroid-API) for info on how to use the API. 5 | 6 | Users can install the app by getting an APK from [the release section](https://github.com/ankidroid/apisample/releases) to see the API in action. 7 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main_menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/menu/action_mode_menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | API sample 3 | Share 4 | Instant-Add 5 | Other apps 6 | Settings 7 | %d items selected 8 | %d items added to AnkiDroid 9 | Error adding cards to AnkiDroid 10 | Couldn\'t get permission to access the AnkiDroid database 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 10 | 15 | 16 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # files for the dex VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # built native files 12 | *.o 13 | *.so 14 | 15 | # generated files 16 | bin/ 17 | gen/ 18 | 19 | # Ignore gradle files 20 | .gradle/ 21 | build/ 22 | 23 | # Local configuration file (sdk path, etc) 24 | local.properties 25 | 26 | # Proguard folder generated by Eclipse 27 | proguard/ 28 | 29 | # Eclipse Metadata 30 | .metadata/ 31 | 32 | # Mac OS X clutter 33 | *.DS_Store 34 | 35 | # Windows clutter 36 | Thumbs.db 37 | 38 | # Ubunut gedit cluter 39 | *~ 40 | 41 | # Intellij IDEA (see https://intellij-support.jetbrains.com/entries/23393067) 42 | .idea/* 43 | 44 | # Additionally ignore project files themselves so developers can choose their root directory name freely 45 | .idea/modules.xml 46 | *.iml 47 | 48 | # Crowdin files 49 | ankidroid.zip 50 | tools/crowdin_key.txt 51 | 52 | .idea/misc.xml 53 | 54 | .idea/vcs.xml 55 | -------------------------------------------------------------------------------- /app/src/main/res/layout/word_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 11 | 17 | 23 | -------------------------------------------------------------------------------- /AnkiDroid_Sync.prf.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1446713011681 4 | 1446713143626 5 | 9 6 | 4 7 | AnkiDroid Sync 8 | 9 | 599 10 | android.intent.action.ACTION_POWER_CONNECTED 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 1445006914290 19 | 1445022789689 20 | 4 21 | AnkiDroid Sync 22 | 100 23 | 24 | 877 25 | com.ichi2.anki.DO_SYNC 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | def homePath = System.properties['user.home'] 3 | 4 | android { 5 | namespace = 'com.ichi2.apisample' 6 | compileSdkVersion 35 7 | buildToolsVersion "35.0.0" 8 | 9 | defaultConfig { 10 | applicationId "com.ichi2.apisample" 11 | minSdkVersion 21 12 | targetSdkVersion 33 13 | versionCode 2 14 | versionName "1.0.1" 15 | } 16 | compileOptions { 17 | sourceCompatibility JavaVersion.VERSION_11 18 | targetCompatibility JavaVersion.VERSION_11 19 | } 20 | signingConfigs { 21 | release { 22 | storeFile file("${homePath}/src/android-keystore") 23 | keyAlias "nrkeystorealias" 24 | storePassword "ENTER_PASSWORD" 25 | keyPassword "ENTER_PASSWORD" 26 | } 27 | } 28 | buildTypes { 29 | release { 30 | minifyEnabled false 31 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 32 | signingConfig = signingConfigs.release 33 | } 34 | } 35 | } 36 | 37 | dependencies { 38 | implementation fileTree(dir: 'libs', include: ['*.jar']) 39 | implementation 'androidx.appcompat:appcompat:1.7.1' 40 | implementation 'com.github.ankidroid:Anki-Android:api-v1.1.0' 41 | } 42 | 43 | configurations.all { 44 | resolutionStrategy { 45 | force 'org.jetbrains.kotlin:kotlin-stdlib:1.8.22' 46 | force 'org.jetbrains.kotlin:kotlin-stdlib-common:1.8.22' 47 | // Exclude the old jdk7/jdk8 variants 48 | exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib-jdk7' 49 | exclude group: 'org.jetbrains.kotlin', module: 'kotlin-stdlib-jdk8' 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /app/src/main/java/com/ichi2/apisample/AnkiDroidConfig.java: -------------------------------------------------------------------------------- 1 | package com.ichi2.apisample; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Set; 10 | 11 | /** Some fields to store configuration details for AnkiDroid **/ 12 | final class AnkiDroidConfig { 13 | // Name of deck which will be created in AnkiDroid 14 | public static final String DECK_NAME = "API Sample"; 15 | // Name of model which will be created in AnkiDroid 16 | public static final String MODEL_NAME = "com.ichi2.apisample"; 17 | // Optional space separated list of tags to add to every note 18 | public static final Set TAGS = new HashSet<>(Collections.singletonList("API_Sample_App")); 19 | // List of field names that will be used in AnkiDroid model 20 | public static final String[] FIELDS = {"Expression","Reading","Meaning","Furigana","Grammar","Sentence", 21 | "SentenceFurigana","SentenceMeaning"}; 22 | // List of card names that will be used in AnkiDroid (one for each direction of learning) 23 | public static final String[] CARD_NAMES = {"Japanese>English", "English>Japanese"}; 24 | // CSS to share between all the cards (optional). User will need to install the NotoSans font by themselves 25 | public static final String CSS = ".card {\n" + 26 | " font-family: NotoSansJP;\n" + 27 | " font-size: 24px;\n" + 28 | " text-align: center;\n" + 29 | " color: black;\n" + 30 | " background-color: white;\n" + 31 | " word-wrap: break-word;\n" + 32 | "}\n" + 33 | "@font-face { font-family: \"NotoSansJP\"; src: url('_NotoSansJP-Regular.otf'); }\n" + 34 | "@font-face { font-family: \"NotoSansJP\"; src: url('_NotoSansJP-Bold.otf'); font-weight: bold; }\n" + 35 | "\n" + 36 | ".big { font-size: 48px; }\n" + 37 | ".small { font-size: 18px;}\n"; 38 | // Template for the question of each card 39 | static final String QFMT1 = "
{{Expression}}

{{Grammar}}"; 40 | static final String QFMT2 = "{{Meaning}}

{{Grammar}}

({{SentenceMeaning}})
"; 41 | public static final String[] QFMT = {QFMT1, QFMT2}; 42 | // Template for the answer (use identical for both sides) 43 | static final String AFMT1 = "
{{furigana:Furigana}}

{{Meaning}}\n" + 44 | "

\n" + 45 | "{{furigana:SentenceFurigana}}
\n" + 46 | "Sentence Translation\n" + 47 | "
{{SentenceMeaning}}
\n" + 48 | "

\n" + 49 | "{{Grammar}}
{{Tags}}
"; 50 | public static final String[] AFMT = {AFMT1, AFMT1}; 51 | // Define two keys which will be used when using legacy ACTION_SEND intent 52 | public static final String FRONT_SIDE_KEY = FIELDS[0]; 53 | public static final String BACK_SIDE_KEY = FIELDS[2]; 54 | 55 | /** 56 | * Generate the ArrayList example data which will be sent to AnkiDroid 57 | */ 58 | public static List> getExampleData() { 59 | final String[] EXAMPLE_WORDS = {"例", "データ", "送る"}; 60 | final String[] EXAMPLE_READINGS = {"れい", "データ", "おくる"}; 61 | final String[] EXAMPLE_TRANSLATIONS = {"Example", "Data", "To send"}; 62 | final String[] EXAMPLE_FURIGANA = {"例[れい]", "データ", "送[おく]る"}; 63 | final String[] EXAMPLE_GRAMMAR = {"P, adj-no, n, n-pref", "P, n", "P, v5r, vt"}; 64 | final String[] EXAMPLE_SENTENCE = {"そんな先例はない。", "きゃ~データが消えた!", "放蕩生活を送る。"}; 65 | final String[] EXAMPLE_SENTENCE_FURIGANA = {"そんな 先例[せんれい]はない。", "きゃ~データが 消[き]えた!", 66 | "放蕩[ほうとう] 生活[せいかつ]を 送[おく]る。"}; 67 | final String[] EXAMPLE_SENTENCE_MEANING = {"We have no such example", "Oh, I lost the data!", 68 | "I lead a fast way of living."}; 69 | 70 | List> data = new ArrayList<>(); 71 | for (int idx = 0; idx < EXAMPLE_WORDS.length; idx++) { 72 | Map hm = new HashMap<>(); 73 | hm.put(FIELDS[0], EXAMPLE_WORDS[idx]); 74 | hm.put(FIELDS[1], EXAMPLE_READINGS[idx]); 75 | hm.put(FIELDS[2], EXAMPLE_TRANSLATIONS[idx]); 76 | hm.put(FIELDS[3], EXAMPLE_FURIGANA[idx]); 77 | hm.put(FIELDS[4], EXAMPLE_GRAMMAR[idx]); 78 | hm.put(FIELDS[5], EXAMPLE_SENTENCE[idx]); 79 | hm.put(FIELDS[6], EXAMPLE_SENTENCE_FURIGANA[idx]); 80 | hm.put(FIELDS[7], EXAMPLE_SENTENCE_MEANING[idx]); 81 | data.add(hm); 82 | } 83 | return data; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /app/src/main/java/com/ichi2/apisample/AnkiDroidHelper.java: -------------------------------------------------------------------------------- 1 | package com.ichi2.apisample; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.content.SharedPreferences; 6 | import android.content.pm.PackageManager; 7 | import android.os.Build; 8 | import androidx.core.app.ActivityCompat; 9 | import androidx.core.content.ContextCompat; 10 | import android.util.SparseArray; 11 | 12 | import com.ichi2.anki.api.AddContentApi; 13 | import com.ichi2.anki.api.NoteInfo; 14 | 15 | import java.util.ArrayList; 16 | import java.util.LinkedList; 17 | import java.util.List; 18 | import java.util.ListIterator; 19 | import java.util.Map; 20 | import java.util.Set; 21 | 22 | import static com.ichi2.anki.api.AddContentApi.READ_WRITE_PERMISSION; 23 | 24 | public class AnkiDroidHelper { 25 | private static final String DECK_REF_DB = "com.ichi2.anki.api.decks"; 26 | private static final String MODEL_REF_DB = "com.ichi2.anki.api.models"; 27 | 28 | private final AddContentApi mApi; 29 | private final Context mContext; 30 | 31 | public AnkiDroidHelper(Context context) { 32 | mContext = context.getApplicationContext(); 33 | mApi = new AddContentApi(mContext); 34 | } 35 | 36 | public AddContentApi getApi() { 37 | return mApi; 38 | } 39 | 40 | /** 41 | * Whether or not the API is available to use. 42 | * The API could be unavailable if AnkiDroid is not installed or the user explicitly disabled the API 43 | * @return true if the API is available to use 44 | */ 45 | public static boolean isApiAvailable(Context context) { 46 | return AddContentApi.getAnkiDroidPackageName(context) != null; 47 | } 48 | 49 | /** 50 | * Whether or not we should request full access to the AnkiDroid API 51 | */ 52 | public boolean shouldRequestPermission() { 53 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { 54 | return false; 55 | } 56 | return ContextCompat.checkSelfPermission(mContext, READ_WRITE_PERMISSION) != PackageManager.PERMISSION_GRANTED; 57 | } 58 | 59 | /** 60 | * Request permission from the user to access the AnkiDroid API (for SDK 23+) 61 | * @param callbackActivity An Activity which implements onRequestPermissionsResult() 62 | * @param callbackCode The callback code to be used in onRequestPermissionsResult() 63 | */ 64 | public void requestPermission(Activity callbackActivity, int callbackCode) { 65 | ActivityCompat.requestPermissions(callbackActivity, new String[]{READ_WRITE_PERMISSION}, callbackCode); 66 | } 67 | 68 | 69 | /** 70 | * Save a mapping from deckName to getDeckId in the SharedPreferences 71 | */ 72 | public void storeDeckReference(String deckName, long deckId) { 73 | final SharedPreferences decksDb = mContext.getSharedPreferences(DECK_REF_DB, Context.MODE_PRIVATE); 74 | decksDb.edit().putLong(deckName, deckId).apply(); 75 | } 76 | 77 | /** 78 | * Save a mapping from modelName to modelId in the SharedPreferences 79 | */ 80 | public void storeModelReference(String modelName, long modelId) { 81 | final SharedPreferences modelsDb = mContext.getSharedPreferences(MODEL_REF_DB, Context.MODE_PRIVATE); 82 | modelsDb.edit().putLong(modelName, modelId).apply(); 83 | } 84 | 85 | /** 86 | * Remove the duplicates from a list of note fields and tags 87 | * @param fields List of fields to remove duplicates from 88 | * @param tags List of tags to remove duplicates from 89 | * @param modelId ID of model to search for duplicates on 90 | */ 91 | public void removeDuplicates(LinkedList fields, LinkedList> tags, long modelId) { 92 | // Build a list of the duplicate keys (first fields) and find all notes that have a match with each key 93 | List keys = new ArrayList<>(fields.size()); 94 | for (String[] f: fields) { 95 | keys.add(f[0]); 96 | } 97 | SparseArray> duplicateNotes = getApi().findDuplicateNotes(modelId, keys); 98 | // Do some sanity checks 99 | if (tags.size() != fields.size()) { 100 | throw new IllegalStateException("List of tags must be the same length as the list of fields"); 101 | } 102 | if (duplicateNotes == null || duplicateNotes.size() == 0 || fields.isEmpty() || tags.isEmpty()) { 103 | return; 104 | } 105 | if (duplicateNotes.keyAt(duplicateNotes.size() - 1) >= fields.size()) { 106 | throw new IllegalStateException("The array of duplicates goes outside the bounds of the original lists"); 107 | } 108 | // Iterate through the fields and tags LinkedLists, removing those that had a duplicate 109 | ListIterator fieldIterator = fields.listIterator(); 110 | ListIterator> tagIterator = tags.listIterator(); 111 | int listIndex = -1; 112 | for (int i = 0; i < duplicateNotes.size(); i++) { 113 | int duplicateIndex = duplicateNotes.keyAt(i); 114 | while (listIndex < duplicateIndex) { 115 | fieldIterator.next(); 116 | tagIterator.next(); 117 | listIndex++; 118 | } 119 | fieldIterator.remove(); 120 | tagIterator.remove(); 121 | } 122 | } 123 | 124 | 125 | /** 126 | * Try to find the given model by name, accounting for renaming of the model: 127 | * If there's a model with this modelName that is known to have previously been created (by this app) 128 | * and the corresponding model ID exists and has the required number of fields 129 | * then return that ID (even though it may have since been renamed) 130 | * If there's a model from #getModelList with modelName and required number of fields then return its ID 131 | * Otherwise return null 132 | * @param modelName the name of the model to find 133 | * @param numFields the minimum number of fields the model is required to have 134 | * @return the model ID or null if something went wrong 135 | */ 136 | public Long findModelIdByName(String modelName, int numFields) { 137 | SharedPreferences modelsDb = mContext.getSharedPreferences(MODEL_REF_DB, Context.MODE_PRIVATE); 138 | long prefsModelId = modelsDb.getLong(modelName, -1L); 139 | // if we have a reference saved to modelName and it exists and has at least numFields then return it 140 | if ((prefsModelId != -1L) 141 | && (mApi.getModelName(prefsModelId) != null) 142 | && (mApi.getFieldList(prefsModelId) != null) 143 | && (mApi.getFieldList(prefsModelId).length >= numFields)) { // could potentially have been renamed 144 | return prefsModelId; 145 | } 146 | Map modelList = mApi.getModelList(numFields); 147 | if (modelList != null) { 148 | for (Map.Entry entry : modelList.entrySet()) { 149 | if (entry.getValue().equals(modelName)) { 150 | return entry.getKey(); // first model wins 151 | } 152 | } 153 | } 154 | // model no longer exists (by name nor old id), the number of fields was reduced, or API error 155 | return null; 156 | } 157 | 158 | 159 | /** 160 | * Try to find the given deck by name, accounting for potential renaming of the deck by the user as follows: 161 | * If there's a deck with deckName then return it's ID 162 | * If there's no deck with deckName, but a ref to deckName is stored in SharedPreferences, and that deck exist in 163 | * AnkiDroid (i.e. it was renamed), then use that deck.Note: this deck will not be found if your app is re-installed 164 | * If there's no reference to deckName anywhere then return null 165 | * @param deckName the name of the deck to find 166 | * @return the did of the deck in Anki 167 | */ 168 | public Long findDeckIdByName(String deckName) { 169 | SharedPreferences decksDb = mContext.getSharedPreferences(DECK_REF_DB, Context.MODE_PRIVATE); 170 | // Look for deckName in the deck list 171 | Long did = getDeckId(deckName); 172 | if (did != null) { 173 | // If the deck was found then return it's id 174 | return did; 175 | } else { 176 | // Otherwise try to check if we have a reference to a deck that was renamed and return that 177 | did = decksDb.getLong(deckName, -1); 178 | if (did != -1 && mApi.getDeckName(did) != null) { 179 | return did; 180 | } else { 181 | // If the deck really doesn't exist then return null 182 | return null; 183 | } 184 | } 185 | } 186 | 187 | /** 188 | * Get the ID of the deck which matches the name 189 | * @param deckName Exact name of deck (note: deck names are unique in Anki) 190 | * @return the ID of the deck that has given name, or null if no deck was found or API error 191 | */ 192 | private Long getDeckId(String deckName) { 193 | Map deckList = mApi.getDeckList(); 194 | if (deckList != null) { 195 | for (Map.Entry entry : deckList.entrySet()) { 196 | if (entry.getValue().equalsIgnoreCase(deckName)) { 197 | return entry.getKey(); 198 | } 199 | } 200 | } 201 | return null; 202 | } 203 | } 204 | 205 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | org.gradle.wrapper.GradleWrapperMain \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Timothy Rae 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /app/src/main/java/com/ichi2/apisample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.ichi2.apisample; 2 | 3 | import android.app.Activity; 4 | import android.content.Intent; 5 | import android.content.pm.ApplicationInfo; 6 | import android.content.pm.PackageManager; 7 | import android.content.res.Resources; 8 | import android.os.Bundle; 9 | 10 | import androidx.annotation.NonNull; 11 | import androidx.core.app.ActivityCompat; 12 | import androidx.core.app.ShareCompat; 13 | import androidx.appcompat.app.AppCompatActivity; 14 | 15 | import android.util.Log; 16 | import android.util.SparseBooleanArray; 17 | import android.view.ActionProvider; 18 | import android.view.Menu; 19 | import android.view.MenuInflater; 20 | import android.view.MenuItem; 21 | import android.view.SubMenu; 22 | import android.view.View; 23 | import android.widget.AbsListView; 24 | import android.widget.ListView; 25 | import android.widget.SimpleAdapter; 26 | import android.widget.Toast; 27 | 28 | import com.ichi2.anki.api.AddContentApi; 29 | 30 | import java.util.ArrayList; 31 | import java.util.Arrays; 32 | import java.util.LinkedList; 33 | import java.util.List; 34 | import java.util.Map; 35 | import java.util.Set; 36 | 37 | 38 | public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { 39 | public static final String LOG_TAG = "AnkiDroidApiSample"; 40 | private static final int AD_PERM_REQUEST = 0; 41 | 42 | private ListView mListView; 43 | private List> mListData; 44 | private AnkiDroidHelper mAnkiDroid; 45 | 46 | @Override 47 | protected void onCreate(Bundle savedInstanceState) { 48 | super.onCreate(savedInstanceState); 49 | setContentView(R.layout.activity_main); 50 | // Create the example data 51 | mListData = AnkiDroidConfig.getExampleData(); 52 | // Setup the ListView containing the example data 53 | mListView = findViewById(R.id.main_list); 54 | mListView.setAdapter(new SimpleAdapter(this, mListData, R.layout.word_layout, 55 | Arrays.copyOfRange(AnkiDroidConfig.FIELDS, 0, 3), 56 | new int[]{R.id.word_item, R.id.word_item_reading, R.id.word_item_translation})); 57 | mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); 58 | // When an item is long-pressed the ListSelectListener will make a Contextual Action Bar with Share icon 59 | mListView.setMultiChoiceModeListener(new ListSelectListener()); 60 | // Create instance of helper class 61 | mAnkiDroid = new AnkiDroidHelper(this); 62 | } 63 | 64 | 65 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 66 | @NonNull int[] grantResults) { 67 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 68 | if (requestCode == AD_PERM_REQUEST && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 69 | addCardsToAnkiDroid(getSelectedData()); 70 | } else { 71 | Toast.makeText(MainActivity.this, R.string.permission_denied, Toast.LENGTH_LONG).show(); 72 | } 73 | } 74 | 75 | 76 | @Override 77 | public boolean onCreateOptionsMenu(Menu menu) { 78 | // Inflate the menu; this adds items to the action bar if it is present. 79 | getMenuInflater().inflate(R.menu.main_menu, menu); 80 | return true; 81 | } 82 | 83 | @Override 84 | public boolean onOptionsItemSelected(MenuItem item) { 85 | switch (item.getItemId()) { 86 | default: 87 | return super.onOptionsItemSelected(item); 88 | } 89 | } 90 | 91 | /** 92 | * Inner class that handles the contextual action bar that appears when an item is long-pressed in the ListView 93 | */ 94 | class ListSelectListener implements AbsListView.MultiChoiceModeListener { 95 | 96 | @Override 97 | public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) { 98 | // Set the subtitle on the action bar to show how many items are selected 99 | int numItemsChecked = mListView.getCheckedItemCount(); 100 | String subtitle = getResources().getString(R.string.n_items_selected, numItemsChecked); 101 | mode.setSubtitle(subtitle); 102 | } 103 | 104 | @Override 105 | public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) { 106 | // Inflate the menu resource while holds the contextual action bar actions 107 | MenuInflater inflater = mode.getMenuInflater(); 108 | inflater.inflate(R.menu.action_mode_menu, menu); 109 | return true; 110 | } 111 | 112 | @Override 113 | public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) { 114 | // Don't need to do anything here 115 | return false; 116 | } 117 | 118 | @Override 119 | public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) { 120 | // This is called when the contextual action bar buttons are pressed 121 | if (item.getItemId() == R.id.share_data_button) { 122 | /* Use AnkiDroid provider if installed, otherwise use ACTION_SEND intent 123 | * If you don't need to share with any apps other than AnkiDroid, you can completely replace 124 | * this code block with the code in AnkiDroidActionProvider.onMenuItemClick() 125 | */ 126 | if (AnkiDroidHelper.isApiAvailable(MainActivity.this)) { 127 | // Use AnkiDroidActionProvider to handle the click event if the provider is installed 128 | item.setActionProvider(new AnkiDroidActionProvider(MainActivity.this, getSelectedData())); 129 | } else { 130 | // Only 1 piece of text is supported by the ACTION_SEND intent, so take first entry 131 | shareViaSendIntent(getSelectedData().get(0)); 132 | } 133 | return true; 134 | } else { 135 | return false; 136 | } 137 | } 138 | 139 | @Override 140 | public void onDestroyActionMode(android.view.ActionMode mode) { 141 | // Don't need to do anything here 142 | } 143 | } 144 | 145 | List> getSelectedData() { 146 | // Extract the selected data 147 | SparseBooleanArray checked = mListView.getCheckedItemPositions(); 148 | List> selectedData = new ArrayList<>(); 149 | for (int i = 0; i < checked.size(); i++) { 150 | if (checked.valueAt(i)) { 151 | selectedData.add(mListData.get(checked.keyAt(i))); 152 | } 153 | } 154 | return selectedData; 155 | } 156 | 157 | /** 158 | * Inner class which implements the dropdown menu on the Share button of the Contextual Action Bar 159 | */ 160 | class AnkiDroidActionProvider extends ActionProvider implements 161 | MenuItem.OnMenuItemClickListener { 162 | 163 | static final int ANKIDROID_INSTANT_ADD = 0; 164 | static final int ALL_APPS = 1; 165 | List> mSelectedData; 166 | 167 | 168 | /** 169 | * Creates a new instance. 170 | * 171 | * @param context Context for accessing resources. 172 | */ 173 | public AnkiDroidActionProvider(Activity context, List> selectedData) { 174 | super(context); 175 | mSelectedData = selectedData; 176 | } 177 | 178 | @Override 179 | @Deprecated 180 | public View onCreateActionView() { 181 | // Just return null for a simple dropdown menu 182 | return null; 183 | } 184 | 185 | @Override 186 | public boolean hasSubMenu() { 187 | // If the AnkiDroid ContentProvider is installed then show it in a submenu, otherwise no need for submenu 188 | return AddContentApi.getAnkiDroidPackageName(MainActivity.this) != null; 189 | } 190 | 191 | @Override 192 | public void onPrepareSubMenu(SubMenu subMenu) { 193 | // Generate the submenu when the system asks for it 194 | subMenu.clear(); 195 | PackageManager manager = getApplicationContext().getPackageManager(); 196 | Resources res = getApplicationContext().getResources(); 197 | // Add AnkiDroid "instant add" to the menu 198 | try { 199 | ApplicationInfo appInfo = manager.getApplicationInfo(AddContentApi.getAnkiDroidPackageName(MainActivity.this), 0); 200 | String label = manager.getApplicationLabel(appInfo) + " " + res.getString(R.string.instant_add); 201 | subMenu.add(0, ANKIDROID_INSTANT_ADD, ANKIDROID_INSTANT_ADD, label) 202 | .setIcon(appInfo.loadIcon(manager)) 203 | .setOnMenuItemClickListener(this); 204 | } catch (PackageManager.NameNotFoundException e) { 205 | Log.e(MainActivity.LOG_TAG, "AnkiDroid app could not be found"); 206 | } 207 | // Add other apps here if it's advantageous for the user to be able to access them with one click 208 | // You could also get rid of the "more" item and just add the apps that support SEND directly to submenu 209 | 210 | // Add a "more" item to show more items if there are too many 211 | subMenu.add(0, ALL_APPS, ALL_APPS, res.getString(R.string.more_items)) 212 | .setIcon(R.mipmap.ic_launcher) 213 | .setOnMenuItemClickListener(this); 214 | } 215 | 216 | @Override 217 | public boolean onMenuItemClick(MenuItem item) { 218 | // Handle when the submenu items are clicked 219 | if (item.getItemId() == ANKIDROID_INSTANT_ADD) { 220 | // Request permission to access API if required 221 | if (mAnkiDroid.shouldRequestPermission()) { 222 | mAnkiDroid.requestPermission(MainActivity.this, AD_PERM_REQUEST); 223 | return true; 224 | } 225 | // Add all data using AnkiDroid provider 226 | addCardsToAnkiDroid(mSelectedData); 227 | } else if (item.getItemId() == ALL_APPS) { 228 | // If the user presses "more" then switch to the stock Android intent selector (can only send 1 card) 229 | shareViaSendIntent(mSelectedData.get(0)); 230 | } 231 | return true; 232 | } 233 | } 234 | 235 | /** 236 | * Send a simple front / back flashcard via the ACTION_SEND intent 237 | */ 238 | private void shareViaSendIntent(Map data) { 239 | // Use ShareCompat so that the sending app info is correctly included in the share intent 240 | Activity context = MainActivity.this; 241 | Intent shareIntent = new ShareCompat.IntentBuilder(context) 242 | .setType("text/plain") 243 | .setText(data.get(AnkiDroidConfig.BACK_SIDE_KEY)) 244 | .setSubject(data.get(AnkiDroidConfig.FRONT_SIDE_KEY)) 245 | .getIntent(); 246 | if (shareIntent.resolveActivity(context.getPackageManager()) != null) { 247 | context.startActivity(shareIntent); 248 | } 249 | } 250 | 251 | /** 252 | * get the deck id 253 | * 254 | * @return might be null if there was a problem 255 | */ 256 | private Long getDeckId() { 257 | Long did = mAnkiDroid.findDeckIdByName(AnkiDroidConfig.DECK_NAME); 258 | if (did == null) { 259 | did = mAnkiDroid.getApi().addNewDeck(AnkiDroidConfig.DECK_NAME); 260 | mAnkiDroid.storeDeckReference(AnkiDroidConfig.DECK_NAME, did); 261 | } 262 | return did; 263 | } 264 | 265 | /** 266 | * get model id 267 | * 268 | * @return might be null if there was an error 269 | */ 270 | private Long getModelId() { 271 | Long mid = mAnkiDroid.findModelIdByName(AnkiDroidConfig.MODEL_NAME, AnkiDroidConfig.FIELDS.length); 272 | if (mid == null) { 273 | mid = mAnkiDroid.getApi().addNewCustomModel(AnkiDroidConfig.MODEL_NAME, AnkiDroidConfig.FIELDS, 274 | AnkiDroidConfig.CARD_NAMES, AnkiDroidConfig.QFMT, AnkiDroidConfig.AFMT, AnkiDroidConfig.CSS, getDeckId(), null); 275 | mAnkiDroid.storeModelReference(AnkiDroidConfig.MODEL_NAME, mid); 276 | } 277 | return mid; 278 | } 279 | 280 | /** 281 | * Use the instant-add API to add flashcards directly to AnkiDroid. 282 | * 283 | * @param data List of cards to be added. Each card has a HashMap of field name / field value pairs. 284 | */ 285 | private void addCardsToAnkiDroid(final List> data) { 286 | Long deckId = getDeckId(); 287 | Long modelId = getModelId(); 288 | if ((deckId == null) || (modelId == null)) { 289 | // we had an API error, report failure and return 290 | Toast.makeText(MainActivity.this, getResources().getString(R.string.card_add_fail), Toast.LENGTH_LONG).show(); 291 | return; 292 | } 293 | String[] fieldNames = mAnkiDroid.getApi().getFieldList(modelId); 294 | if (fieldNames == null) { 295 | // we had an API error, report failure and return 296 | Toast.makeText(MainActivity.this, getResources().getString(R.string.card_add_fail), Toast.LENGTH_LONG).show(); 297 | return; 298 | } 299 | // Build list of fields and tags 300 | LinkedList fields = new LinkedList<>(); 301 | LinkedList> tags = new LinkedList<>(); 302 | for (Map fieldMap : data) { 303 | // Build a field map accounting for the fact that the user could have changed the fields in the model 304 | String[] flds = new String[fieldNames.length]; 305 | for (int i = 0; i < flds.length; i++) { 306 | // Fill up the fields one-by-one until either all fields are filled or we run out of fields to send 307 | if (i < AnkiDroidConfig.FIELDS.length) { 308 | flds[i] = fieldMap.get(AnkiDroidConfig.FIELDS[i]); 309 | } 310 | } 311 | tags.add(AnkiDroidConfig.TAGS); 312 | fields.add(flds); 313 | } 314 | // Remove any duplicates from the LinkedLists and then add over the API 315 | mAnkiDroid.removeDuplicates(fields, tags, modelId); 316 | int added = mAnkiDroid.getApi().addNotes(modelId, deckId, fields, tags); 317 | if (added != 0) { 318 | Toast.makeText(MainActivity.this, getResources().getString(R.string.n_items_added, added), Toast.LENGTH_LONG).show(); 319 | } else { 320 | // API indicates that a 0 return value is an error 321 | Toast.makeText(MainActivity.this, getResources().getString(R.string.card_add_fail), Toast.LENGTH_LONG).show(); 322 | } 323 | } 324 | } --------------------------------------------------------------------------------