Although I integrated libraries in build.gradle but when I run it on device the following error occurs.
11-16 12:59:10.097 14630-14630/sadboy.antix E/AndroidRuntime: FATAL EXCEPTION: main
Process: sadboy.antix, PID: 14630
java.lang.NoClassDefFoundError: org.apache.lucene.util.AttributeSource$2
at org.apache.lucene.util.AttributeSource.<clinit>(AttributeSource.java:150)
at sadboy.antix.text_processing.KeywordsExtractor.getKeywordsList(KeywordsExtractor.java:34)
at sadboy.antix.activities.NewsArticle.onCreate(NewsArticle.java:51)
at android.app.Activity.performCreate(Activity.java:6010)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
11-16 13:04:10.197 14630-14630/sadboy.antix I/Process: Sending signal. PID: 14630 SIG: 9
My code looks like this,
buidl.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "sadboy.antix"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.0.0'
//Library for web scraping
compile 'org.jsoup:jsoup:1.10.1'
//Library for HTTP request
compile 'com.squareup.okhttp3:okhttp:3.4.2'
//Savage UX/UI libraries
compile 'com.mikhaellopez:circularfillableloaders:1.2.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.balysv:material-ripple:1.0.2'
compile('com.mikepenz:materialdrawer:5.7.0#aar') {
transitive = true
}
//Lucence libraries for text processing
compile group: 'org.apache.lucene', name: 'lucene-core', version: '5.5.0'
compile group: 'org.apache.lucene', name: 'lucene-analyzers-common', version: '5.5.0'
//Essential google libraries
compile 'com.android.support:cardview-v7:25.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
}
Classes where I am using Lucence
package sadboy.antix.text_processing;
/**
* Created by Varun Kumar on 11/15/2016.
*/
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.en.EnglishAnalyzer;
import org.apache.lucene.analysis.en.PorterStemFilter;
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter;
import org.apache.lucene.analysis.standard.ClassicFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class KeywordsExtractor {
public static List<CardKeyword> getKeywordsList(String fullText) throws IOException {
TokenStream tokenStream = null;
try {
fullText = fullText.replaceAll("-+", "-0");
fullText = fullText.replaceAll("[\\p{Punct}&&[^'-]]+", " ");
fullText = fullText.replaceAll("(?:'(?:[tdsm]|[vr]e|ll))+\\b", "");
StandardTokenizer stdToken = new StandardTokenizer();
stdToken.setReader(new StringReader(fullText));
tokenStream = new StopFilter(new ASCIIFoldingFilter(new ClassicFilter(new LowerCaseFilter(stdToken))), EnglishAnalyzer.getDefaultStopSet());
tokenStream.reset();
List<CardKeyword> cardKeywords = new LinkedList<>();
CharTermAttribute token = tokenStream.getAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
String term = token.toString();
String stem = getStemForm(term);
if (stem != null) {
CardKeyword cardKeyword = find(cardKeywords, new CardKeyword(stem.replaceAll("-0", "-")));
cardKeyword.add(term.replaceAll("-0", "-"));
}
}
Collections.sort(cardKeywords);
return cardKeywords;
} finally {
if (tokenStream != null) {
try {
tokenStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static String getStemForm(String term) throws IOException {
TokenStream tokenStream = null;
try {
StandardTokenizer stdToken = new StandardTokenizer();
stdToken.setReader(new StringReader(term));
tokenStream = new PorterStemFilter(stdToken);
tokenStream.reset();
Set<String> stems = new HashSet<>();
CharTermAttribute token = tokenStream.getAttribute(CharTermAttribute.class);
while (tokenStream.incrementToken()) {
stems.add(token.toString());
}
if (stems.size() != 1) {
return null;
}
String stem = stems.iterator().next();
if (!stem.matches("[a-zA-Z0-9-]+")) {
return null;
}
return stem;
} finally {
if (tokenStream != null) {
try {
tokenStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static <T> T find(Collection<T> collection, T sample) {
for (T element : collection) {
if (element.equals(sample)) {
return element;
}
}
collection.add(sample);
return sample;
}
}
Model Class
package sadboy.antix.text_processing;
/**
* Created by Varun Kumar on 11/15/2016.
*/
import java.util.HashSet;
import java.util.Set;
public class CardKeyword implements Comparable<CardKeyword> {
private final String stem;
private final Set<String> terms = new HashSet<>();
private int frequency;
public CardKeyword(String stem) {
this.stem = stem;
}
public void add(String term) {
this.terms.add(term);
this.frequency++;
}
#Override
public int compareTo(CardKeyword keyword) {
return Integer.valueOf(keyword.frequency).compareTo(this.frequency);
}
#Override
public int hashCode() {
return this.getStem().hashCode();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CardKeyword)) return false;
CardKeyword that = (CardKeyword) o;
return this.getStem().equals(that.getStem());
}
public String getStem() {
return this.stem;
}
public Set<String> getTerms() {
return this.terms;
}
public int getFrequency() {
return this.frequency;
}
}
Activity where all this begins
package sadboy.antix.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import sadboy.antix.R;
import sadboy.antix.text_processing.CardKeyword;
import sadboy.antix.text_processing.KeywordsExtractor;
public class NewsArticle extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_article);
String input = "Pick Flick is your ultimate app to find information about Movies, TV shows and Celebrities fast and easily on the go\n" +
"\n" +
"• Quick access of popular, top rated, now playing, highest grossing and upcoming movies\n" +
"• Quick access of popular, top rated, airing today and on air TV shows\n" +
"• View the cast of movies and TV shows\n" +
"• Similar Movies and TV shows to watch to explore more on the basis of your search\n" +
"• Find the movies or TV shows done by a celebrity\n" +
"• Set reminders and bookmarks so you never forget or miss anything you like\n" +
"• Share everything with your friends and family to plan movies or just watch a TV show maybe\n" +
"• List of trending celebrities\n" +
"• All the information and rating of Movies, TV shows and Celebrities on the go\n" +
"• Fast and easy search with keywords and suggestions\n" +
"• Fluid and easy to use UI enabling for glitch free experience\n" +
"\n" +
"• Like Pick Flick on Facebook\n" +
"• https://www.facebook.com/pickflickapp\n" +
"\n" +
"• Follow Pick Flick on Instagram\n" +
"• https://www.instagram.com/pickflickapp/\n" +
"\n" +
"• Pick Flick uses data and images by TMDb licensed under CC BY-NC 4.0\n" +
"• https://creativecommons.org/licenses/by-nc/4.0/\n" +
"\n" +
"• Pick Flick uses the TMDb API but is not endorsed or certified by TMDb\n" +
"• https://www.themoviedb.org/documentation/api/terms-of-use";
List<CardKeyword> keywordsList = null;
try {
keywordsList = KeywordsExtractor.getKeywordsList(input);
} catch (IOException e) {
e.printStackTrace();
}
int i;
for(i = 0;i<keywordsList.size();i++)
{
Log.d("Keyword",i+" "+keywordsList.get(i).getStem());
}
}
}
Pls check with adding this:
// https://mvnrepository.com/artifact/org.apache.lucene/lucene-backward-codecs
compile group: 'org.apache.lucene', name: 'lucene-backward-codecs', version: '5.5.0'
Related
I have a Spring Boot App with the following classes in the src/main/java/in/javacoder/overlayapp package
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.13'
}
javafx {
version = "17"
modules = [ 'javafx.controls' ]
}
group = 'in.techpro424'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
CoordinateOverlayAppApplication.java
package in.techpro424.coordinateoverlayapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CoordinateOverlayAppApplication {
public static void main(String[] args) {
SpringApplication.run(CoordinateOverlayAppApplication.class, args);
}
}
CoordinateRestController.java
package in.techpro424.coordinateoverlayapp;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CoordinateRestController {
public static double xCoord;
public static double yCoord;
public static double zCoord;
#PostMapping(value = "/coordinateOverlay")
public int receiveCoordinates(#RequestParam(name = "xCoordinate") Double xCoordinate, #RequestParam(name = "yCoordinate") Double yCoordinate, #RequestParam(name = "zCoordinate") Double zCoordinate) {
CoordinateRestController.xCoord = xCoordinate;
System.out.println(CoordinateRestController.xCoord);
CoordinateRestController.yCoord = yCoordinate;
System.out.println(CoordinateRestController.yCoord);
CoordinateRestController.zCoord = zCoordinate;
System.out.println(CoordinateRestController.zCoord);
javafx.application.Application.launch(RenderCoordinateOverlay.class);
return 1;
}
}
RenderCoordinateOverlay.java
package in.techpro424.coordinateoverlayapp;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class RenderCoordinateOverlay extends Application {
double radius = 50;
#Override
public void start(Stage primaryStage) {
Group root = new Group();
Text coordinates = new Text();
coordinates.setText("X:" + CoordinateRestController.xCoord + ", Y:" + CoordinateRestController.yCoord + ", Z:" + CoordinateRestController.zCoord);
root.getChildren().add(coordinates);
Scene scene = new Scene(root, Color.TRANSPARENT);
scene.getRoot().setStyle("-fx-background-color: transparent");
primaryStage.initStyle(StageStyle.TRANSPARENT);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setAlwaysOnTop(true);
}
public static void main(String[] args) {
launch(args);
}
}
I want to render this overlay on the screen whenever I receive the POST request with the specified params
I tried using javafx.application.Application.launch(RenderCoordinateOverlay.class); in the receiveCoordinates() function
I expected the overlay to render the text the moment I sent the POST request
However, when I sent the POST request, only a completely transparent window was rendered with this error in the console:
2023-01-27T15:01:27.384+05:30 WARN 13060 --- [JavaFX-Launcher] javafx: Unsupported JavaFX configuration: classes were loaded from 'unnamed module #1ec4c0e8'
The SpringBoot application is running on my PC with a display and I expect the UI to be displayed on the PC.
I use Postman to send the post.
After recording a simple espresso test on my app the test fails to run and I'm hoping someone can guide me as to why this is happening. The resulting error is:
D/AndroidJUnitRunner: Use the raw file system for managing file I/O.
E/AndroidRuntime: FATAL EXCEPTION: Instr: androidx.test.runner.AndroidJUnitRunner
Process: com.companyname.appname, PID: 2343
**java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/test/platform/io/FileTestStorage;**
at androidx.test.runner.AndroidJUnitRunner.registerTestStorage(AndroidJUnitRunner.java:671)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:447)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2152)
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.test.platform.io.FileTestStorage" on path: DexPathList[[zip file "/system/framework/android.test.runner.jar", zip file "/system/framework/android.test.mock.jar", zip file "/data/app/com.companyname.appname.test-IqFAu-mtwBYt8la6Xi2kdA==/base.apk", zip file "/data/app/com.companyname.appname-mWOZlXK4F0npIJ34j66euw==/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.appname.test-IqFAu-mtwBYt8la6Xi2kdA==/lib/arm, /data/app/com.companyname.appname-mWOZlXK4F0npIJ34j66euw==/lib/arm, /system/lib, /system/product/lib, /system/vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at androidx.test.runner.AndroidJUnitRunner.registerTestStorage(AndroidJUnitRunner.java:671)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:447)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2152)
I/Process: Sending signal. PID: 2343 SIG: 9
Disconnected from the target VM, address: 'localhost:53625', transport: 'socket'
Build.gradle I'm using looks like:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.companyname.appname"
minSdkVersion 16
targetSdkVersion 29
versionCode 4
versionName "1.3.0"
// testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable false
signingConfig getSigningConfig()
applicationVariants.all { variant ->
variant.outputs.each { output ->
variant.outputs.all {
outputFileName = "AppName_${variant.versionName}.apk"
}
}
}
}
debug {
debuggable true
minifyEnabled false
}
}
packagingOptions {
// exclude 'META-INF/services/javax.annotation.processing.Processor'
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
// abortOnError false
}
dexOptions {
preDexLibraries false
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.android.gms:play-services:8.3.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
implementation 'androidx.versionedparcelable:versionedparcelable:1.1.1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test:runner:1.4.1-alpha01'
androidTestImplementation 'androidx.test:rules:1.4.1-alpha01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-alpha01'
}
Espresso java file (with some commented-out things I've tried):
package com.companyname.appname;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.DataInteraction;
import androidx.test.espresso.ViewInteraction;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.filters.LargeTest;
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import static androidx.test.InstrumentationRegistry.getInstrumentation;
import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.pressBack;
import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static androidx.test.espresso.action.ViewActions.*;
import static androidx.test.espresso.assertion.ViewAssertions.*;
import static androidx.test.espresso.matcher.ViewMatchers.*;
import com.companyname.appname.R;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.core.IsInstanceOf;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anything;
import static org.hamcrest.Matchers.is;
#LargeTest
#RunWith(AndroidJUnit4.class) //AndroidJUnit4ClassRunner.class
public class MainActivityTestPortrait2
{
#Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
// public ActivityScenarioRule<MainActivity> activityRule =
// new ActivityScenarioRule<>(MainActivity.class);
#Test
public void mainActivityTestPortrait2()
{
// ActivityScenario scenario = activityRule.getScenario();
ViewInteraction relativeLayout = onView(
allOf(withId(R.id.menuButton),
childAtPosition(
childAtPosition(
withClassName(is("com.android.internal.widget.ActionBarView")),
1),
2),
isDisplayed()));
relativeLayout.perform(click());
ViewInteraction relativeLayout2 = onView(
allOf(withId(R.id.menuButton),
childAtPosition(
childAtPosition(
withClassName(is("com.android.internal.widget.ActionBarView")),
1),
2),
isDisplayed()));
relativeLayout2.perform(click());
ViewInteraction relativeLayout3 = onView(
allOf(withId(R.id.menuButton),
childAtPosition(
childAtPosition(
withClassName(is("com.android.internal.widget.ActionBarView")),
1),
2),
isDisplayed()));
relativeLayout3.perform(click());
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position)
{
return new TypeSafeMatcher<View>()
{
#Override
public void describeTo(Description description)
{
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
#Override
public boolean matchesSafely(View view)
{
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
First of, the dependency on extension functions should not be in base implementation
implementation 'androidx.test.ext:junit:1.1.3'
what should be there is a core library for tests:
// activity does not start without it
debugImplementation "androidx.test:core:1.4.0" // or implementation "androidx.test:core:1.4.0"
Second, with such bugs, try to have all the common library versions aligned.
Also, the usual suspect is your case should be any -alpha library.
So try:
androidTestImplementation "androidx.test:runner:1.4.0"
androidTestImplementation "androidx.test:rules:1.4.0"
androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"
and instead of alpha libraries and then go from there.
Realized I had a dependency (implementation 'androidx.test.ext:junit:1.1.3') that blew up building AndroidJUnitRunner.java. Removal of this line allows the test to run - not successfully, but that's another issue.
I am working on a flutter project which necessarily has to call a java function. So, I defined my MainActivity.java just like this:
package com.manager.nlp;
import android.os.Bundle;
import android.content.Intent;
import android.os.PowerManager;
import android.os.Build.VERSION;
import androidx.annotation.NonNull;
import android.content.IntentFilter;
import android.content.ContextWrapper;
import android.os.Build.VERSION_CODES;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "analisisSintactico";
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler((call, result) -> {
if (call.method.equals("method")) {
result.success("value1");
} else {
result.success("value2");
}
});
}
}
and I call it doing this from the main file in dart:
(I'll skip what's not important, like other Widgets and that stuff)
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/services.dart';
class PaginaHome extends StatefulWidget {
const PaginaHome({Key key}) : super(key: key);
#override
_PaginaHomeState createState() => _PaginaHomeState();
}
class _PaginaHomeState extends State<PaginaHome> {
static const cajaNegra = const MethodChannel('analisisSintactico');
#override
Widget build(BuildContext context) {
return Scaffold(
body: new Column(children: <Widget>[
IconButton(
onPressed: () {
invocarAJava();
}
...
)
...
)
}
Future<void> invocarAJava() async {
String valor = await cajaNegra.invokeMethod('method');
print(valor);
}
}
The, when clicking that IconButton, I get this error:
E/flutter ( 9060): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: MissingPluginException(No implementation found
for method method on channel analisisSintactico) E/flutter ( 9060): #0
MethodChannel._invokeMethod
(package:flutter/src/services/platform_channel.dart:156:7) E/flutter (
9060): E/flutter ( 9060): #1
_PaginaHomeState.invocarAJava (package:holamundo/main.dart:146:20) E/flutter ( 9060):
If I run "flutter doctor -v" it says everything is correct
I also tried to execute flutter clean and then flutter run, having deleted de apk from the debug android emulator. It still shows the same error.
I know the file is being evaluated, because if I write something stupid, it detects the error. But, somehow, it does not recognize the method it is calling. Also tried with other names for the channel and the method.
Lastly, this is my build.gradle:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 30
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
main.java.srcDirs += 'src/main/java'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.holamundo"
minSdkVersion 21
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
minifyEnabled true
useProguard true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
If anyone knows what the issue could be here that forbids me from calling my java code, I would gladly take any suggestions. Thanks.
1- I am writing kotlin side but I think the problem is same. Move your methods to another java file as a Plugin Methods like this:
class AnalisisSintacticoPlugin(
private val registrar: Registrar
) : MethodCallHandler,
PluginRegistry.ActivityResultListener {
private lateinit var _result: MethodChannel.Result
private lateinit var channel: MethodChannel
companion object {
#JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(),"analisisSintactico")
val plugin = FlutterScreenRecordingPlugin(registrar)
channel.setMethodCallHandler(plugin)
registrar.addActivityResultListener(plugin)
}
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "method") {
result.success("value1")
} else {
result.success("value2")
}
}
}
2- Register it in your MainActivity:
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
val shimPluginRegistry = ShimPluginRegistry(flutterEngine)
com.manager.nlp.AnalisisSintacticoPlugin.registerWith(shimPluginRegistry.registrarFor("com.manager.nlp.AnalisisSintacticoPlugin"))
GeneratedPluginRegistrant.registerWith(flutterEngine)
}
}
Edit 1: For java side:
1- Create a file called AnalisisSintacticoPlugin in same folder with MainActivity. Then pass this code:
package com.manager.nlp;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
public class AnalisisSintacticoPlugin implements FlutterPlugin, MethodCallHandler {
private MethodChannel channel;
#Override
public void onAttachedToEngine(#NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "analisisSintactico");
channel.setMethodCallHandler(this);
}
#Override
public void onMethodCall(#NonNull MethodCall call, #NonNull Result result) {
if (call.method.equals("method")) {
result.success("value1");
} else {
result.success("value2");
}
}
#Override
public void onDetachedFromEngine(#NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
2- Add your plugin in MainActivity:
package com.manager.nlp;
import androidx.annotation.NonNull;
import org.jetbrains.annotations.NotNull;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
#Override
public void configureFlutterEngine(#NonNull #NotNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
flutterEngine.getPlugins().add(new com.manager.nlp.AnalisisSintacticoPlugin());
}
}
3- If not, change activity name in AndroidManifest.xml to ".MainActivity"
<activity
android:name=".MainActivity"
4- Make sure that meta-data in AndroidManifest.xml exactly same with this:
<meta-data
android:name="flutterEmbedding"
android:value="2" />
I have gone thru the documentation of Firestore: https://firebase.google.com/docs/firestore/query-data/listen?authuser=0
But while using same code, i am not able to resolve symbols such as DocumentChange, EventListener.
Similarly, I am not able to resolve methods such as getDocumentChanges, getDocument, addSnapshotListener.
I have already imported 'com.google.firebase:firebase-admin:5.8.0'.
build.gradle file
group 'firestore'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
dependencies {
compile 'com.google.firebase:firebase-admin:5.8.0'
}
Here is the code, I am trying:
package firestore;
import com.google.api.core.SettableApiFuture;
import com.google.firestore.v1beta1.DocumentChange;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentChange.Type;
import com.google.cloud.firestore.EventListener;
import com.google.cloud.firestore.ListenerRegistration;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreException;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import static com.google.api.ChangeType.ADDED;
import static com.google.api.ChangeType.MODIFIED;
import static com.google.api.ChangeType.REMOVED;
/**
* Snippets to demonstrate Firestore 'listen' operations.
*/
#SuppressWarnings("Convert2Lambda")
public class FirestoreChange {
private static final long TIMEOUT_SECONDS = 5;
private final Firestore db;
FirestoreChange(Firestore db) {
this.db = db;
}
/**
* Listen to a query, returning the list of DocumentChange events in the first snapshot.
*/
List<DocumentChange> listenForChanges() throws Exception {
SettableApiFuture<List<DocumentChange>> future = SettableApiFuture.create();
// [START listen_for_changes]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
System.out.println("New city: " + dc.getDocument().getData());
break;
case MODIFIED:
System.out.println("Modified city: " + dc.getDocument().getData());
break;
case REMOVED:
System.out.println("Removed city: " + dc.getDocument().getData());
break;
default:
break;
}
}
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(snapshots.getDocumentChanges());
}
// [END_EXCLUDE]
}
});
// [END listen_for_changes]
return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
}
This is happening because you didn't add Cloud Firestore dependencies in build.gradle file at all. Adding firebase-admin is not enought to make Firestore work. So to solve this, just add this line of code:
compile 'com.google.firebase:firebase-firestore:11.8.0'
Right after the firebase-admin dependencies. Sync your project and try again.
I have gradle script which is creating the version in JIRA using the REST API.
But there is jira-rest-java-client also available. I want to use the java library of jira-rest-java-client and wants to do the same stuff in gradle. Can someone provide an example how could I try this.
How to use the jira-rest-java-client library to make connection with JIRA through example?
In Java I am trying to use this JRCJ Library but getting below error through Intellj
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.*;
import com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue;
import com.atlassian.jira.rest.client.api.domain.input.FieldInput;
import com.atlassian.jira.rest.client.api.domain.input.TransitionInput;
import com.atlassian.jira.rest.client.internal.ServerVersionConstants;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.google.common.collect.Lists;
import org.codehaus.jettison.json.JSONException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* A sample code how to use JRJC library
*
* #since v0.1
*/
public class Example1 {
private static URI jiraServerUri = URI.create("http://localhost:2990/jira");
private static boolean quiet = false;
public static void main(String[] args) throws URISyntaxException, JSONException, IOException {
parseArgs(args);
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "admin", "admin");
try {
final int buildNumber = restClient.getMetadataClient().getServerInfo().claim().getBuildNumber();
// first let's get and print all visible projects (only jira4.3+)
if (buildNumber >= ServerVersionConstants.BN_JIRA_4_3) {
final Iterable<BasicProject> allProjects = restClient.getProjectClient().getAllProjects().claim();
for (BasicProject project : allProjects) {
if (project == TEST){
println(project);}else {
System.out.println("Project" + "Not Found");
}
}
}
// let's now print all issues matching a JQL string (here: all assigned issues)
if (buildNumber >= ServerVersionConstants.BN_JIRA_4_3) {
final SearchResult searchResult = restClient.getSearchClient().searchJql("assignee is not EMPTY").claim();
for (BasicIssue issue : searchResult.getIssues()) {
println(issue.getKey());
}
}
final Issue issue = restClient.getIssueClient().getIssue("TST-7").claim();
println(issue);
// now let's vote for it
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
// now let's watch it
final BasicWatchers watchers = issue.getWatchers();
if (watchers != null) {
restClient.getIssueClient().watch(watchers.getSelf()).claim();
}
// now let's start progress on this issue
final Iterable<Transition> transitions = restClient.getIssueClient().getTransitions(issue.getTransitionsUri()).claim();
final Transition startProgressTransition = getTransitionByName(transitions, "Start Progress");
restClient.getIssueClient().transition(issue.getTransitionsUri(), new TransitionInput(startProgressTransition.getId()))
.claim();
// and now let's resolve it as Incomplete
final Transition resolveIssueTransition = getTransitionByName(transitions, "Resolve Issue");
final Collection<FieldInput> fieldInputs;
// Starting from JIRA 5, fields are handled in different way -
if (buildNumber > ServerVersionConstants.BN_JIRA_5) {
fieldInputs = Arrays.asList(new FieldInput("resolution", ComplexIssueInputFieldValue.with("name", "Incomplete")));
} else {
fieldInputs = Arrays.asList(new FieldInput("resolution", "Incomplete"));
}
final TransitionInput transitionInput = new TransitionInput(resolveIssueTransition.getId(), fieldInputs, Comment
.valueOf("My comment"));
restClient.getIssueClient().transition(issue.getTransitionsUri(), transitionInput).claim();
}
finally {
restClient.close();
}
}
private static void println(Object o) {
if (!quiet) {
System.out.println(o);
}
}
private static void parseArgs(String[] argsArray) throws URISyntaxException {
final List<String> args = Lists.newArrayList(argsArray);
if (args.contains("-q")) {
quiet = true;
args.remove(args.indexOf("-q"));
}
if (!args.isEmpty()) {
jiraServerUri = new URI(args.get(0));
}
}
private static Transition getTransitionByName(Iterable<Transition> transitions, String transitionName) {
for (Transition transition : transitions) {
if (transition.getName().equals(transitionName)) {
return transition;
}
}
return null;
}
}
Error:
xception in thread "main" java.lang.NoClassDefFoundError: com/atlassian/sal/api/executor/ThreadLocalContextManager
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
at Example1.main(Example1.java:34)
Caused by: java.lang.ClassNotFoundException: com.atlassian.sal.api.executor.ThreadLocalContextManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more
Moreover I added the JRJC api,core jar in External Libraries but still getting this error?
Could someone tell me what is the issue or where am I missing something?
compile 'com.atlassian.jira:jira-rest-java-client-core:4.0.0'
compile 'com.atlassian.jira:jira-rest-java-client-api:4.0.0'
Simple connection to JIRA:
JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(new URI("https://" + jira_domain),
jira_username, jira_password);