├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap
│ │ │ └── ic_launcher.png
│ │ ├── drawable
│ │ │ └── ic_add_white_24dp.png
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── menu
│ │ │ └── menu_main.xml
│ │ └── layout
│ │ │ ├── fragment_definition.xml
│ │ │ ├── fragment_image.xml
│ │ │ ├── simple_list_item_multiple_choice_left.xml
│ │ │ ├── activity_card.xml
│ │ │ └── activity_main.xml
│ │ ├── java
│ │ └── in
│ │ │ └── rab
│ │ │ └── bildkort
│ │ │ ├── Utils.java
│ │ │ ├── Model.java
│ │ │ ├── DefinitionFragment.java
│ │ │ ├── MainActivity.java
│ │ │ ├── ImageFragment.java
│ │ │ ├── CardActivity.java
│ │ │ └── SentenceFragment.java
│ │ ├── assets
│ │ ├── model.question.html
│ │ └── imagepicker.js
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── screenshots
├── images.png
└── sentences.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/screenshots/images.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vitkyrka/bildkortsappen/HEAD/screenshots/images.png
--------------------------------------------------------------------------------
/screenshots/sentences.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vitkyrka/bildkortsappen/HEAD/screenshots/sentences.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vitkyrka/bildkortsappen/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vitkyrka/bildkortsappen/HEAD/app/src/main/res/mipmap/ic_launcher.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_add_white_24dp.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vitkyrka/bildkortsappen/HEAD/app/src/main/res/drawable/ic_add_white_24dp.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 180dp
3 | 16dp
4 |
5 | 16dp
6 | 16dp
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/Utils.java:
--------------------------------------------------------------------------------
1 | package in.rab.bildkort;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.util.Scanner;
6 |
7 | public class Utils {
8 | static String inputStreamToString(InputStream input) throws IOException {
9 | Scanner scanner = new Scanner(input).useDelimiter("\\A");
10 | String str = scanner.hasNext() ? scanner.next() : "";
11 |
12 | input.close();
13 |
14 | return str;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/rabin/dev/android-sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_definition.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
14 |
15 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_image.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
15 |
16 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/app/src/main/assets/model.question.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "in.rab.bildkort"
9 | minSdkVersion 22
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.3.0'
26 | compile 'com.android.support:design:23.3.0'
27 | compile 'com.squareup.retrofit2:retrofit:2.0.1'
28 | compile 'com.squareup.retrofit2:converter-gson:2.0.1'
29 | compile 'com.android.support:support-v4:23.3.0'
30 | compile 'com.android.support:recyclerview-v7:23.3.0'
31 | compile 'com.ichi2.anki:api:1.1.0alpha5'
32 | }
33 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Bildkortsappen
3 | Skapa
4 | Bildkort
5 | Substantiv
6 | Adjektiv
7 | Verb
8 | Preposition
9 | Okänd
10 | Bokstavlig matchning
11 | Föredragen ordklass
12 | Skapa kort
13 | Ord
14 | Exempel
15 | Bilder
16 | Definition
17 | Det gick inte att skapa kortet
18 | Kortet har skapats
19 | AnkiDroid behövs
20 | Bildkortsappen behöver AnkiDroid. Installera appen \"AnkiDroid flashcards\" från Play-butiken och ge Bildkortsappen de efterfrågade rättigheterna.
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/simple_list_item_multiple_choice_left.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
17 |
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bildkortsappen
2 |
3 |  
4 |
5 | Bildkortsappen is an Android app to create flashcards for language learning.
6 | Given a word, it presents an interface where the user can pick images which
7 | correspond to that word (currently from Google Image Search) or real-world
8 | example sentences which use that word (from a concordance).
9 |
10 | The flashcards are created directly in
11 | [AnkiDroid](https://play.google.com/store/apps/details?id=com.ichi2.anki) and
12 | use Javascript to display a random subset of the chosen images and example
13 | sentences on the front side, and a user-specified reverse side.
14 |
15 | While the image search should work for any language, only Swedish is supported
16 | for the interface and the example sentences. The examples are retrieved from
17 | [Språkbanken](https://spraakbanken.gu.se/swe)'s
18 | [Korp](https://spraakbanken.gu.se/korp/) service using [their
19 | API](https://spraakbanken.gu.se/swe/forskning/infrastruktur/korp/ws).
20 |
21 | Words can be added manually or via sharing from any Android app. Words shared
22 | to Bildkortsappen from the [Ordboken Swedish
23 | dictionary](https://play.google.com/store/apps/details?id=in.rab.ordboken) will
24 | automatically have their HTML-formatted definition used for the reverse side of
25 | the created flashcards.
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/Model.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import android.content.Context;
20 | import android.content.res.AssetManager;
21 |
22 | import java.io.InputStream;
23 |
24 | class Model {
25 | public static final String NAME = "in.rab.bildkort";
26 | public static final String[] FIELDS = {"Images", "Sentences", "Back"};
27 | public static final String[] CARD_NAMES = {"Card 1"};
28 | static final String[] AFMT = {"{{FrontSide}}\n\n
\n\n{{Back}}"};
29 |
30 | public static String[] getQuestionFormats(Context context) {
31 | try {
32 | AssetManager am = context.getAssets();
33 | InputStream is = am.open("model.question.html");
34 | return new String[]{Utils.inputStreamToString(is)};
35 | } catch (java.io.IOException e) {
36 | return new String[]{"Error"};
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_card.xml:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
23 |
24 |
28 |
29 |
32 |
33 |
36 |
37 |
38 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/assets/imagepicker.js:
--------------------------------------------------------------------------------
1 | /* This file is injected with a javascript: URL. Single-line comments will not work. */
2 |
3 | var toDataURL = function (img) {
4 | var canvas = document.getElementById('canvas');
5 |
6 | canvas.width = img.width;
7 | canvas.height = img.height;
8 |
9 | canvas.getContext('2d').drawImage(img, 0, 0);
10 |
11 | return canvas.toDataURL();
12 | };
13 |
14 | var updateSelected = function () {
15 | var selected = [];
16 | var els = document.getElementsByTagName('img');
17 |
18 | for (i = 0; i < els.length; i++) {
19 | if (els[i].className == 'selected') {
20 | var src = els[i].src;
21 |
22 | if (src.substr(0, 5) != 'data:') {
23 | src = toDataURL(els[i]);
24 | }
25 |
26 | selected.push(src);
27 | }
28 | }
29 |
30 | wcm.pushSelected(JSON.stringify(selected));
31 | };
32 |
33 | var toggleSelected = function (img) {
34 | img.className = img.className == 'selected' ? '' : 'selected';
35 | updateSelected();
36 | };
37 |
38 | var getPickerHtml = function() {
39 | var html = '' +
44 | '';
45 | var els = document.getElementsByTagName('img');
46 | var onclick = "toggleSelected(this);";
47 |
48 | for (i = 0; i < els.length; i++) {
49 | var src = '';
50 |
51 | if (i == 0) {
52 | continue;
53 | }
54 |
55 | src = els[i].src;
56 | if (src == '') {
57 | src = els[i].dataset.src;
58 | }
59 |
60 | if (!src) {
61 | continue;
62 | }
63 |
64 | /*
65 | * Change images pointing to the various encrypted-tbn[0-9].gstatic.com
66 | * servers to point to the local one encrypted-tbn0.gstatic.com, to get
67 | * around the canvas cross-origin restrictions in toDataURL.
68 | */
69 | src = src.replace(/^http.*\.com/, '');
70 |
71 | if (src && (src.substr(0, 5) == 'data:' || src.indexOf('tbn:') != -1)) {
72 | html += '
';
73 | }
74 | }
75 |
76 | wcm.pushPickerHtml(html);
77 | };
78 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/DefinitionFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import android.os.Bundle;
20 | import android.support.annotation.Nullable;
21 | import android.support.v4.app.Fragment;
22 | import android.view.LayoutInflater;
23 | import android.view.View;
24 | import android.view.ViewGroup;
25 | import android.webkit.WebView;
26 | import android.widget.EditText;
27 |
28 |
29 | public class DefinitionFragment extends Fragment {
30 | private EditText mEditText;
31 |
32 | public DefinitionFragment() {
33 | }
34 |
35 | public static DefinitionFragment newInstance(String definition, Boolean isHtml) {
36 | DefinitionFragment fragment = new DefinitionFragment();
37 | Bundle args = new Bundle();
38 | args.putString("definition", definition);
39 | args.putBoolean("isHtml", isHtml);
40 | fragment.setArguments(args);
41 | return fragment;
42 | }
43 |
44 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
45 | super.onActivityCreated(savedInstanceState);
46 |
47 | String definition = getArguments().getString("definition");
48 | Boolean isHtml = getArguments().getBoolean("isHtml");
49 |
50 | mEditText = (EditText) getView().findViewById(R.id.editText);
51 | WebView webView = (WebView) getView().findViewById(R.id.webView);
52 |
53 | if (isHtml) {
54 | // Anki centers text by default, which is not optimal for large HTML
55 | // chunks such as those we get from NE.
56 | definition = "" + definition + "
";
57 |
58 | mEditText.setVisibility(View.GONE);
59 | webView.setVisibility(View.VISIBLE);
60 | } else {
61 | mEditText.setVisibility(View.VISIBLE);
62 | webView.setVisibility(View.GONE);
63 | }
64 |
65 | mEditText.setText(definition);
66 | webView.loadDataWithBaseURL("http://fake", definition, "text/html", "UTF-8", null);
67 | }
68 |
69 | @Override
70 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
71 | Bundle savedInstanceState) {
72 | return inflater.inflate(R.layout.fragment_definition, container, false);
73 | }
74 |
75 | public String getText() {
76 | return mEditText.getText().toString();
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import android.content.Intent;
20 | import android.os.Bundle;
21 | import android.support.v7.app.AppCompatActivity;
22 | import android.support.v7.widget.Toolbar;
23 | import android.view.View;
24 | import android.widget.ArrayAdapter;
25 | import android.widget.Button;
26 | import android.widget.EditText;
27 | import android.widget.Spinner;
28 |
29 | public class MainActivity extends AppCompatActivity {
30 | private class PosItem {
31 | private String mName;
32 | private String mId;
33 |
34 | public PosItem(int resource, String id) {
35 | mName = getString(resource);
36 | mId = id;
37 | }
38 |
39 | public String getId() {
40 | return mId;
41 | }
42 |
43 | public String toString() {
44 | return mName;
45 | }
46 | }
47 |
48 | @Override
49 | protected void onCreate(Bundle savedInstanceState) {
50 | super.onCreate(savedInstanceState);
51 | setContentView(R.layout.activity_main);
52 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
53 | setSupportActionBar(toolbar);
54 |
55 | final EditText wordEdit = (EditText) findViewById(R.id.wordEdit);
56 | final Spinner posSpinner = (Spinner) findViewById(R.id.posSpinner);
57 |
58 | PosItem[] array = {
59 | new PosItem(R.string.pos_unknown, SentenceFragment.POS_UNKNOWN),
60 | new PosItem(R.string.pos_noun, SentenceFragment.POS_NOUN),
61 | new PosItem(R.string.pos_adjective, SentenceFragment.POS_ADJECTIVE),
62 | new PosItem(R.string.pos_verb, SentenceFragment.POS_VERB),
63 | new PosItem(R.string.pos_preposition, SentenceFragment.POS_PREPOSITION),
64 | new PosItem(R.string.pos_none, SentenceFragment.POS_NONE),
65 | };
66 |
67 | ArrayAdapter adapter = new ArrayAdapter(this,
68 | android.R.layout.simple_spinner_item, array);
69 |
70 | adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
71 | posSpinner.setAdapter(adapter);
72 |
73 | Button button = (Button) findViewById(R.id.button);
74 | button.setOnClickListener(new View.OnClickListener() {
75 | @Override
76 | public void onClick(View v) {
77 | Intent intent = new Intent(MainActivity.this, CardActivity.class);
78 | PosItem posItem = (PosItem) posSpinner.getSelectedItem();
79 |
80 | intent.putExtra(Intent.EXTRA_SUBJECT, wordEdit.getText().toString());
81 | intent.putExtra("in.rab.extra.pos", posItem.getId());
82 | startActivity(intent);
83 | }
84 | });
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
22 |
23 |
24 |
25 |
37 |
38 |
44 |
45 |
51 |
52 |
57 |
58 |
64 |
65 |
70 |
71 |
77 |
78 |
79 |
80 |
81 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/ImageFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import org.json.JSONArray;
20 | import org.json.JSONException;
21 |
22 | import android.annotation.SuppressLint;
23 | import android.content.res.AssetManager;
24 | import android.os.Bundle;
25 | import android.support.annotation.Nullable;
26 | import android.support.v4.app.Fragment;
27 | import android.view.LayoutInflater;
28 | import android.view.View;
29 | import android.view.ViewGroup;
30 | import android.webkit.JavascriptInterface;
31 | import android.webkit.WebChromeClient;
32 | import android.webkit.WebSettings;
33 | import android.webkit.WebView;
34 | import android.webkit.WebViewClient;
35 | import android.widget.ProgressBar;
36 |
37 | import java.io.InputStream;
38 | import java.util.ArrayList;
39 | import java.util.Objects;
40 |
41 | public class ImageFragment extends Fragment {
42 | static final String GSTATIC_SERVER = "https://encrypted-tbn0.gstatic.com/";
43 |
44 | private WebView mWebView;
45 | private ArrayList mSelected = new ArrayList<>();
46 | private String mImagePickerJs;
47 |
48 | public static ImageFragment newInstance(String word) {
49 | ImageFragment fragment = new ImageFragment();
50 |
51 | Bundle args = new Bundle();
52 | args.putString("word", word);
53 | fragment.setArguments(args);
54 |
55 | return fragment;
56 | }
57 |
58 | private String getWord() {
59 | return getArguments().getString("word");
60 | }
61 |
62 | private class WcmJsObject {
63 | @SuppressWarnings("unused")
64 | @JavascriptInterface
65 | public void pushSelected(final String json) {
66 | getActivity().runOnUiThread(new Runnable() {
67 | @Override
68 | public void run() {
69 | JSONArray array;
70 | try {
71 | array = new JSONArray(json);
72 |
73 | mSelected.clear();
74 |
75 | for (int i = 0; i < array.length(); i++) {
76 | mSelected.add(array.getString(i));
77 | }
78 | } catch (JSONException e) {
79 | e.printStackTrace();
80 | }
81 | }
82 | });
83 | }
84 |
85 | @SuppressWarnings("unused")
86 | @JavascriptInterface
87 | public void pushPickerHtml(final String html) {
88 | getActivity().runOnUiThread(new Runnable() {
89 | @Override
90 | public void run() {
91 | mWebView.loadDataWithBaseURL(GSTATIC_SERVER,
92 | html + "",
93 | "text/html", "UTF-8", null);
94 | }
95 | });
96 | }
97 | }
98 |
99 | @SuppressLint("SetJavaScriptEnabled")
100 | @Override
101 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
102 | super.onActivityCreated(savedInstanceState);
103 |
104 | mWebView = (WebView) getView().findViewById(R.id.webView);
105 | final ProgressBar progress = (ProgressBar) getView().findViewById(R.id.image_progress);
106 | mWebView.setWebChromeClient(new WebChromeClient());
107 | final WebSettings settings = mWebView.getSettings();
108 |
109 | settings.setBuiltInZoomControls(true);
110 | settings.setDisplayZoomControls(false);
111 | settings.setJavaScriptEnabled(true);
112 |
113 | // We replace the src urls in imagepicker.js::init(), so don't load
114 | // images twice.
115 | settings.setBlockNetworkImage(true);
116 |
117 | mWebView.setInitialScale(100);
118 |
119 | mWebView.setWebViewClient(new WebViewClient() {
120 | @Override
121 | public void onPageFinished(WebView view, String url) {
122 | if (Objects.equals(url, GSTATIC_SERVER)) {
123 | settings.setBlockNetworkImage(false);
124 |
125 | progress.setVisibility(View.GONE);
126 | mWebView.setVisibility(View.VISIBLE);
127 | } else {
128 | view.loadUrl("javascript:" + getImagePickerJs() + "getPickerHtml();");
129 | }
130 | }
131 | });
132 |
133 | mWebView.addJavascriptInterface(new WcmJsObject(), "wcm");
134 | mWebView.loadUrl("https://www.google.se/search?tbm=isch&q=" + getWord());
135 | }
136 |
137 | private String getImagePickerJs() {
138 | if (mImagePickerJs != null) {
139 | return mImagePickerJs;
140 | }
141 |
142 | try {
143 | AssetManager am = getActivity().getAssets();
144 | InputStream is = am.open("imagepicker.js");
145 | mImagePickerJs = Utils.inputStreamToString(is);
146 | } catch (java.io.IOException e) {
147 | mImagePickerJs = "document.body.innerHtml='Error';";
148 | }
149 |
150 | return mImagePickerJs;
151 | }
152 |
153 | @Override
154 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
155 | Bundle savedInstanceState) {
156 | return inflater.inflate(R.layout.fragment_image, container, false);
157 | }
158 |
159 | public ArrayList getSelected() {
160 | return mSelected;
161 | }
162 | }
163 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/CardActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import com.ichi2.anki.FlashCardsContract;
20 | import com.ichi2.anki.api.AddContentApi;
21 |
22 | import org.json.JSONArray;
23 |
24 | import android.content.DialogInterface;
25 | import android.content.Intent;
26 | import android.content.pm.PackageManager;
27 | import android.os.Bundle;
28 | import android.support.annotation.NonNull;
29 | import android.support.design.widget.TabLayout;
30 | import android.support.v4.app.ActivityCompat;
31 | import android.support.v4.app.Fragment;
32 | import android.support.v4.app.FragmentManager;
33 | import android.support.v4.app.FragmentPagerAdapter;
34 | import android.support.v4.content.ContextCompat;
35 | import android.support.v4.view.ViewPager;
36 | import android.support.v7.app.AlertDialog;
37 | import android.support.v7.app.AppCompatActivity;
38 | import android.support.v7.widget.Toolbar;
39 | import android.view.Menu;
40 | import android.view.MenuInflater;
41 | import android.view.MenuItem;
42 | import android.widget.Toast;
43 |
44 | import java.util.ArrayList;
45 | import java.util.Map;
46 |
47 | public class CardActivity extends AppCompatActivity
48 | implements ActivityCompat.OnRequestPermissionsResultCallback {
49 | private static final String ANKI_DECK_NAME = "Bildkort";
50 | private SentenceFragment mSentenceFragment;
51 | private ImageFragment mImageFragment;
52 | private DefinitionFragment mDefinitonFragment;
53 | private AddContentApi mApi;
54 |
55 | @Override
56 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
57 | @NonNull int[] grantResults) {
58 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
59 | finishCreate();
60 | } else {
61 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
62 | AlertDialog dialog = builder.setTitle(R.string.anki_needed)
63 | .setMessage(R.string.anki_needed_long)
64 | .setPositiveButton("OK", new DialogInterface.OnClickListener() {
65 | @Override
66 | public void onClick(DialogInterface dialog, int which) {
67 | finish();
68 | }
69 | })
70 | .create();
71 |
72 | dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
73 | @Override
74 | public void onDismiss(DialogInterface dialog) {
75 | finish();
76 | }
77 | });
78 |
79 | dialog.show();
80 | }
81 | }
82 |
83 | @Override
84 | protected void onCreate(Bundle savedInstanceState) {
85 | super.onCreate(savedInstanceState);
86 |
87 | mApi = new AddContentApi(this);
88 |
89 | Intent intent = getIntent();
90 |
91 | String word = intent.getStringExtra(Intent.EXTRA_SUBJECT);
92 | if (word == null) {
93 | word = intent.getStringExtra(Intent.EXTRA_TEXT);
94 | }
95 |
96 | if (word == null) {
97 | finish();
98 | return;
99 | }
100 |
101 | setTitle(word);
102 |
103 | String definition = intent.getStringExtra(Intent.EXTRA_HTML_TEXT);
104 | Boolean isHtml = false;
105 | if (definition == null) {
106 | definition = intent.getStringExtra(Intent.EXTRA_TEXT);
107 | if (definition == null) {
108 | definition = word;
109 | }
110 | } else {
111 | isHtml = true;
112 | }
113 |
114 | String pos = intent.getStringExtra("in.rab.extra.pos");
115 | if (pos == null) {
116 | pos = SentenceFragment.POS_UNKNOWN;
117 | }
118 |
119 | mSentenceFragment = SentenceFragment.newInstance(word, pos);
120 | mImageFragment = ImageFragment.newInstance(word);
121 | mDefinitonFragment = DefinitionFragment.newInstance(definition, isHtml);
122 |
123 | if (ContextCompat.checkSelfPermission(this, FlashCardsContract.READ_WRITE_PERMISSION) !=
124 | PackageManager.PERMISSION_GRANTED) {
125 | ActivityCompat.requestPermissions(this,
126 | new String[]{FlashCardsContract.READ_WRITE_PERMISSION},
127 | 0);
128 | } else {
129 | finishCreate();
130 | }
131 | }
132 |
133 | private class CardFragmentPagerAdapter extends FragmentPagerAdapter {
134 | public CardFragmentPagerAdapter(FragmentManager fm) {
135 | super(fm);
136 | }
137 |
138 | @Override
139 | public Fragment getItem(int position) {
140 | switch (position) {
141 | case 0:
142 | return mImageFragment;
143 | case 1:
144 | return mSentenceFragment;
145 | case 2:
146 | return mDefinitonFragment;
147 | default:
148 | return null;
149 | }
150 | }
151 |
152 | @Override
153 | public int getCount() {
154 | return 3;
155 | }
156 |
157 | @Override
158 | public CharSequence getPageTitle(int position) {
159 | switch (position) {
160 | case 0:
161 | return getString(R.string.images);
162 | case 1:
163 | return getString(R.string.sentences);
164 | case 2:
165 | return getString(R.string.definition);
166 | default:
167 | return null;
168 | }
169 | }
170 | }
171 |
172 | private void finishCreate() {
173 | setContentView(R.layout.activity_card);
174 |
175 | Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
176 | setSupportActionBar(myToolbar);
177 |
178 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
179 |
180 | ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
181 | assert viewPager != null;
182 | viewPager.setOffscreenPageLimit(10);
183 | viewPager.setAdapter(new CardFragmentPagerAdapter(getSupportFragmentManager()));
184 |
185 | TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
186 | assert tabLayout != null;
187 | tabLayout.setupWithViewPager(viewPager);
188 | }
189 |
190 | public boolean onCreateOptionsMenu(Menu menu) {
191 | MenuInflater inflater = getMenuInflater();
192 | inflater.inflate(R.menu.menu_main, menu);
193 | return true;
194 | }
195 |
196 | private Long getDeckId() {
197 | Map deckList = mApi.getDeckList();
198 | if (deckList != null) {
199 | for (Map.Entry entry : deckList.entrySet()) {
200 | if (entry.getValue().equals(ANKI_DECK_NAME)) {
201 | return entry.getKey();
202 | }
203 | }
204 | }
205 |
206 | return mApi.addNewDeck(ANKI_DECK_NAME);
207 | }
208 |
209 | private Long getModelId() {
210 | Map modelList = mApi.getModelList();
211 | if (modelList != null) {
212 | for (Map.Entry entry : modelList.entrySet()) {
213 | if (entry.getValue().equals(Model.NAME)) {
214 | return entry.getKey();
215 | }
216 | }
217 | }
218 |
219 | return mApi.addNewCustomModel(Model.NAME, Model.FIELDS, Model.CARD_NAMES,
220 | Model.getQuestionFormats(this),
221 | Model.AFMT, null, null, null);
222 | }
223 |
224 | private void createCard() {
225 | ArrayList images = mImageFragment.getSelected();
226 | ArrayList sentences = mSentenceFragment.getSelected();
227 |
228 | String[] fields = {
229 | new JSONArray(images).toString(),
230 | new JSONArray(sentences).toString(),
231 | mDefinitonFragment.getText()
232 | };
233 |
234 | Long id = mApi.addNote(getModelId(), getDeckId(), fields, null);
235 | Toast.makeText(this, id == null ? getString(R.string.failed_add_card) : getString(R.string.card_added),
236 | Toast.LENGTH_LONG).show();
237 | finish();
238 | }
239 |
240 | @Override
241 | public boolean onOptionsItemSelected(MenuItem item) {
242 | switch (item.getItemId()) {
243 | case R.id.action_create:
244 | createCard();
245 | return true;
246 | default:
247 | return super.onOptionsItemSelected(item);
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------
/app/src/main/java/in/rab/bildkort/SentenceFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2016 Rabin Vincent
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package in.rab.bildkort;
18 |
19 | import com.google.gson.annotations.SerializedName;
20 |
21 | import android.os.Bundle;
22 | import android.support.annotation.Nullable;
23 | import android.support.v4.app.ListFragment;
24 | import android.text.Html;
25 | import android.text.Spanned;
26 | import android.util.Log;
27 | import android.util.SparseBooleanArray;
28 | import android.widget.ArrayAdapter;
29 | import android.widget.ListView;
30 |
31 | import java.util.ArrayList;
32 |
33 | import okhttp3.Cache;
34 | import okhttp3.OkHttpClient;
35 | import retrofit2.Call;
36 | import retrofit2.Callback;
37 | import retrofit2.Response;
38 | import retrofit2.Retrofit;
39 | import retrofit2.converter.gson.GsonConverterFactory;
40 | import retrofit2.http.GET;
41 | import retrofit2.http.Query;
42 |
43 |
44 | public class SentenceFragment extends ListFragment {
45 | // This is almost all the corpora classified under Akademiska texter, Skönlitteratur,
46 | // Tidningstexter, Tidskrifter and Myndighetstexter in the Korp web interface. Shortening
47 | // the list greatly improves the response time from Korp, but we of course don't
48 | // want to miss out on sentences for rare words.
49 | private static final String CORPORA = "sweachum,sweacsam,aspacsv,romi,romii,rom99,storsuc," +
50 | "romg,gp1994,gp2001,gp2002,gp2003,gp2004,gp2005,gp2006," +
51 | "gp2007,gp2008,gp2009,gp2010,gp2011,gp2012,gp2013,gp2d," +
52 | "press95,press96,press97,press98,webbnyheter2001,webbnyheter2002," +
53 | "webbnyheter2003,webbnyheter2004,webbnyheter2005,webbnyheter2006," +
54 | "webbnyheter2007,webbnyheter2008,webbnyheter2009,webbnyheter2010," +
55 | "webbnyheter2011,webbnyheter2012,webbnyheter2013,attasidor," +
56 | "dn1987,fof,klarsprak,sou,sfs";
57 |
58 | // https://spraakbanken.gu.se/swe/forskning/saldo/taggm%C3%A4ngd
59 | public static final String POS_ADJECTIVE = "av.*";
60 | public static final String POS_ADVERB = "ab.*";
61 | public static final String POS_INTERJECTION = "in.*";
62 | public static final String POS_NOUN = "n.*";
63 | public static final String POS_PREPOSITION = "pp.*";
64 | public static final String POS_VERB = "vb.*";
65 | public static final String POS_UNKNOWN = ".*";
66 | public static final String POS_NONE = "";
67 | private KorpService mKorp;
68 | private String mWord;
69 | private String mPos;
70 | public static final String API_URL = "https://ws.spraakbanken.gu.se/";
71 | private ArrayList mSentences;
72 |
73 | public static SentenceFragment newInstance(String word, String pos) {
74 | SentenceFragment fragment = new SentenceFragment();
75 |
76 | Bundle args = new Bundle();
77 | args.putString("word", word);
78 | args.putString("pos", pos);
79 | fragment.setArguments(args);
80 |
81 | return fragment;
82 | }
83 |
84 | public static SentenceFragment newInstance(String word) {
85 | return newInstance(word, POS_UNKNOWN);
86 | }
87 |
88 | private String getWord() {
89 | return getArguments().getString("word");
90 | }
91 |
92 | private static String tokenJoin(QueryResponse.Kwic kwic) {
93 | StringBuilder sentence = new StringBuilder();
94 | String delimiter = "";
95 | String previous = "";
96 | int quotes = 0;
97 |
98 | for (int i = 0; i < kwic.tokens.size(); i++) {
99 | String word = kwic.tokens.get(i).toString();
100 |
101 | if (word.equals("\"")) {
102 | quotes++;
103 | }
104 |
105 | if (!word.equals(",")
106 | && !word.equals(".")
107 | && !word.equals(":")
108 | && !previous.equals("(")
109 | && !word.equals(")")
110 | && (!previous.equals("\"") || quotes % 2 == 0)
111 | && (!word.equals("\"") || quotes % 2 != 0)) {
112 | sentence.append(delimiter);
113 | }
114 |
115 | if (i >= kwic.match.start && i < kwic.match.end) {
116 | sentence.append("");
117 | sentence.append(word);
118 | sentence.append("");
119 | } else {
120 | sentence.append(word);
121 | }
122 |
123 | previous = word;
124 | delimiter = " ";
125 | }
126 |
127 | return sentence.toString();
128 | }
129 |
130 | private static ArrayList parseJson(QueryResponse p) {
131 | ArrayList sentences = new ArrayList<>();
132 |
133 | if (p.kwic == null) {
134 | return sentences;
135 | }
136 |
137 | for (QueryResponse.Kwic kwic : p.kwic) {
138 | sentences.add(tokenJoin(kwic));
139 | }
140 |
141 | return sentences;
142 | }
143 |
144 | private class QueryResponse {
145 | private ArrayList kwic;
146 | private int hits;
147 |
148 | private class Kwic {
149 | private ArrayList tokens;
150 | private Match match;
151 |
152 | private class Token {
153 | private String word;
154 |
155 | public String toString() {
156 | return word;
157 | }
158 | }
159 |
160 | private class Match {
161 | private int start;
162 | private int end;
163 | }
164 | }
165 | }
166 |
167 | private class AutoCompleteResponse {
168 | private Hits hits;
169 |
170 | private class Hits {
171 | private ArrayList hits;
172 | private int total;
173 |
174 | private class Hit {
175 | @SerializedName("_source")
176 | private Source source;
177 |
178 | private class Source {
179 | @SerializedName("FormRepresentations")
180 | private ArrayList formRepresentations;
181 |
182 | private class FormRepresentations {
183 | String lemgram;
184 | }
185 | }
186 | }
187 | }
188 | }
189 |
190 | public interface KorpService {
191 | @GET("/ws/korp/?command=query&defaultcontext=1+sentence")
192 | Call query(
193 | @Query("corpus") String corpus,
194 | @Query("cqp") String cqp,
195 | @Query("sort") String sort,
196 | @Query("start") Integer start,
197 | @Query("end") Integer end
198 | );
199 |
200 | @GET("/ws/karp/v1/autocomplete?resource=saldom")
201 | Call autoComplete(
202 | @Query("q") String query
203 | );
204 | }
205 |
206 | private class KorpCallback implements Callback {
207 | @Override
208 | public void onResponse(Call call,
209 | Response response) {
210 | if (!response.isSuccessful()) {
211 | return;
212 | }
213 |
214 | QueryResponse queryResponse = response.body();
215 | if (queryResponse.hits == 0 && !mPos.equals(POS_NONE)) {
216 | mPos = POS_NONE;
217 | getSentences();
218 | return;
219 | }
220 |
221 | initList(parseJson(queryResponse));
222 | }
223 |
224 | @Override
225 | public void onFailure(Call call, Throwable t) {
226 | Log.e("Blah", t.getMessage());
227 | }
228 | }
229 |
230 | private void getSentences() {
231 | String cqp;
232 |
233 | if (mPos.equals(POS_NONE)) {
234 | cqp = String.format("\"%s\"", mWord.replace(" ", "\" \""));
235 | } else {
236 | cqp = String.format("[lex contains \"%s\\.\\.%s\\.1\"]", mWord.replace(' ', '_'), mPos);
237 | }
238 |
239 | Call call = mKorp.query(CORPORA, cqp, "random", 0, 30);
240 | call.enqueue(new KorpCallback());
241 | }
242 |
243 | @Override
244 | public void onActivityCreated(@Nullable Bundle savedInstanceState) {
245 | super.onActivityCreated(savedInstanceState);
246 |
247 | Cache cache = new Cache(getContext().getCacheDir(), 1024 * 1024);
248 |
249 | OkHttpClient client = new OkHttpClient.Builder()
250 | .cache(cache)
251 | .build();
252 |
253 | Retrofit retrofit = new Retrofit.Builder()
254 | .client(client)
255 | .baseUrl(API_URL)
256 | .addConverterFactory(GsonConverterFactory.create())
257 | .build();
258 |
259 | mKorp = retrofit.create(KorpService.class);
260 |
261 | mWord = getArguments().getString("word");
262 | mPos = getArguments().getString("pos");
263 | if (!mPos.isEmpty() && !mPos.endsWith("*")) {
264 | mPos += ".*";
265 | }
266 |
267 | getSentences();
268 | }
269 |
270 | private void initList(ArrayList sentences) {
271 | ArrayList spanneds = new ArrayList<>();
272 |
273 | for (String sentence : sentences) {
274 | spanneds.add(Html.fromHtml(sentence));
275 | }
276 |
277 | ArrayAdapter adapter = new ArrayAdapter<>(getActivity(),
278 | R.layout.simple_list_item_multiple_choice_left,
279 | spanneds);
280 |
281 | mSentences = sentences;
282 |
283 | ListView listView = getListView();
284 | setListAdapter(adapter);
285 | listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
286 | }
287 |
288 | public ArrayList getSelected() {
289 | ArrayList selected = new ArrayList<>();
290 | ListView listView = getListView();
291 | SparseBooleanArray items = listView.getCheckedItemPositions();
292 |
293 | if (items == null) {
294 | return selected;
295 | }
296 |
297 | for (int i = 0; i < mSentences.size(); i++) {
298 | if (!items.get(i)) {
299 | continue;
300 | }
301 |
302 | selected.add(mSentences.get(i).replace("strong>", "em>"));
303 | }
304 |
305 | return selected;
306 | }
307 | }
308 |
--------------------------------------------------------------------------------