Run a single .kt file in Android Studio - android-studio

I created a Scratch Kotlin file in Android Studio. I simply want to run this scratch.kt file and get output.
I fiddled with Run Cofigurations but cannot understand what will go into Main Class.

If you create a top-level function called main in any kotlin file, a green run button will appear next to it that allows you to run it as a program:
Note that this works in Android Studio as well as in IntelliJ IDEA.

You can create a scratch kotlin file with File -> New -> Scratch File -> Kotlin.
With this you should be able to create and run kotlin script files to try features, code and so on.
If your intention is to create a full standlone kotlin project. My recomendation is to use IntelliJ IDEA. Doing so with Android Studio may be possible but you won't stop facing issues and having to search for workarounds all the time.

Android Studio allow to run Kotlin code, but the green triangle (to Run) appears just if you don't use a class file or if you add a fun main(args: Array<String>){} out of the class's brackets. So, the way I am doing this (in AS 4.0) is:
Creating a Kotlin FILE (not choose a CLASS) and putting inside just:
fun main(args: Array) {}
Then, inside this method you are allowed to use Kotlin classes. You can do for example:
fun main(args: Array){
var oneMan: Man = Man()
oneMan.method()
}
being Man a regular Kotlin class.

Use this code, You will see a run icon near function.
class Test {
companion object {
#JvmStatic
fun main(args: Array<String>) {
println("Hello test!")
}
}
}

Related

Kotlin Compose Preview reference unresolved

I am working on a Kotlin Multiplatform project for Android and Desktop using Compose and have the Compose Multiplatform IDE Support plugin installed.
What I am trying to do is add the #Preview annotation so I can get a preview of the composables that I'm working on. I tried following this guide to implement that:
https://developer.android.com/jetpack/compose/tooling/studio
I want to have my shared Compose classes in the module shared-ui, so I added the following dependencies to the build.gradle.kts in that module:
dependencies {
debugImplementation("androidx.compose.ui:ui-tooling:1.3.2")
implementation("androidx.compose.ui:ui-tooling-preview:1.3.2")
}
However, even after a synchronization, when I try to use or import the #Preview annotation in my class (shared-ui/src/commonMain/kotlin/.../MyScreen.kt), I get this error:
Unresolved reference: preview
That happens twice: Once in the import statement, where the final word Preview is in red, and once in the annotation, where it is also the word Preview that is in red:
[...]
import androidx.compose.ui.tooling.preview.Preview
[...]
#Preview
#Composable
[...]
Incidentally, I also tried the quick fix option that Android Studio offered me there: "Add dependency on androidx.compose.ui.ui-tooling-preview and import". What that does is add the dependencies exactly where I added them (provided I remove them first, otherwise it does nothing), which apparently means that Android Studio agrees with me that this is where the dependencies should go.
Which brings me to my ultimate question: Why does this not work? What am I doing wrong? Based on my understanding, this should work. But it doesn't. Am I missing something?

What are the new 'p' variables in Android Studio debugger variables pane?

Recently I've installed the Bumblebee version of Android Studio and I've remarked strange new fields marked with p icon and ...get() in my debugger variables pane.
I haven't found any info about these fields, so maybe you can answer? They are so annoying, just duplicating info about val fields in the class.
See the screenshots and the sample class:
data class MyOwnClass2(
val fieldOne: String,
val fieldTwo: Int,
)
I'm using coroutines in the app, and have some Java code mixed with Kotlin one.
I can only imagine that these fields are 'properties' of the class, but I didn't explicitly override custom get/set.
TL;TR: #JvmField or migrate from Java!
So after all, these are consequences of using both Kotlin and Java code in the same module. When I put #JvmField, it doesn't generate these get/set in Kotlin, so no 'p' fields in the debugger are seen any longer.

Flutter coverage reporting in Android Studio [duplicate]

I'm developing an open source Android app in Flutter, using Android Studio 3.3.1 (on Window and Ubuntu). The source is available on Github.
The project has a test file that generates coverage data, which can be viewed with tools such as Coveralls. This indicates to me that the LCOV data contains meaningful data.
I want to use inline Code Coverage viewing, similar to the other Jetbrains tools. The run configuration under the 'Flutter Test' category correctly recoginezes my tests, and is able to run them properly.
However, the 'Run with Coverage' option is disabled. I tried different run configurations such as Android JUnit to no avail.
I am aware that I can manually create the coverage data, but my goal is to automate the generation of the coverage data, and showing the coverage inline (just like Coveralls does).
Does anyone know what run configuration, if any, accomplishes this goal?
As a side note, I recently switched to Codemagic as my CI tool so the coverage data on Coveralls is outdated, but the point that the LCOV data is meaningful still holds. I also tried similar setups in Intellij, but the result is the same as Android Studio.
I don't think is supported for Flutter projects yet.
I have all non-UI code in another pure Dart package that I add as dependency to the Flutter project.
For my project this also has the advantage that code that I can share with the browser GUI (Angular Dart) is separated and can't accidentally be polluted with Flutter dependencies that would break the web project.
In this project I can get coverage information in IntellJ when I follow these steps:
You need a "Dart Command Line App" IntelliJ run configuration instead of a "Dart Test", "Flutter" or "Flutter Test" run configuration.
To be able to run tests with a "Dart Command Line App" run configuration you probably need the standalone Dart SDK installed and select it in Preferences > Languages & Frameworks > Dart > Dart SDK path.
To run all tests with coverage instead of individual files you need a file like
test/all.dart
// ignore_for_file: await_only_futures
import 'dart:async';
import 'client/controller/app_controller_test.dart' as i0;
import 'client/controller/authentication_controller_test.dart' as i1;
import 'client/controller/backoffice/backoffice_controller_test.dart' as i2;
import 'client/controller/backoffice/image_reference_controller_test.dart'
as i3;
...
Future<void> main() async {
i0.main();
i1.main();
i2.main();
...
}
with an entry for each test file.
I use a Grinder task like below to generate that file automatically
import 'package:path/path.dart' as path;
...
/// Generate a single Dart file that executes all tests.
/// Dart code coverage reporting still requires that.
#Task('generate test/all.dart')
Future<void> prepareCoverage() async {
final testDir = Directory('test');
final context = path.Context(style: path.Style.posix);
final testFiles = testDir
.listSync(recursive: true, followLinks: false)
.where((e) =>
FileSystemEntity.isFileSync(e.path) && e.path.endsWith('_test.dart'))
.map(
(tf) => context.normalize(path.relative(tf.path, from: testDir.path)))
.toList()
..sort();
final content = StringBuffer('''
// ignore_for_file: await_only_futures
import 'dart:async';
''');
final executions = StringBuffer();
for (var i = 0; i < testFiles.length; i++) {
final testFile = testFiles[i];
content.writeln("import '$testFile' as i$i;");
executions.writeln(' i$i.main();');
}
content
..writeln('Future<void> main() async {')
..writeln()
..writeln(executions)
..writeln('}');
File('test/all.dart').writeAsStringSync(content.toString());
PubApp.global('dart_style')
.run(['-w', '--fix']..add('test/all.dart'), script: 'format');
}
The 'Run with Coverage' option in Android Studio is enabled only for Flutter integration tests for some reason (at least for me).
I wrote an article that describes how to generate code coverage reports locally and on CodeCov and CoverAlls that should get you close to what you want to do. Includes all source code and shows live examples.
It works for both flutter and dart packages.
You can find it here:
https://medium.com/#nocnoc/combined-code-coverage-for-flutter-and-dart-237b9563ecf8

FlashDevelop/OpenFL: How to set default target to neko

I am trying to write some cross-language code with Haxe/OpenFL and compile it using FalshDevelop. But I get an error as soon as I use the basic Sys.print function. A minimal example is as follows:
package;
import flash.display.Sprite;
class Graphic extends Sprite {
public function new () {
super ();
}
static function main() { //used in standalone swf project
Sys.print("Hi");
}
}
It turns out that the default compile command of FlashDevelop is something like:
haxelib run openfl build project.xml flash
,which gives an error on Sys.print:
Graphic.hx:xx: characters 2-11 : Accessing this field requires a system platform
(php,neko,cpp,etc.)
My guess is that Sys.print isn't available in the flash target or flash isn't a system platform (strange). I was wondering if there is way to work around this, and configure FlashDevelop so that the compile command is:
haxelib run openfl build project.xml neko
Thanks
There are actually 2 questions.
For the first one, Sys.print is available only on some platforms because it wouldn't make sense in others(what would it do in flash?), what you probably want is trace, which is used to print things for debug purposes.
For the second question there is a drop down menu at the top of flashdevelop if you created a openfl project that looks like this and does exactly that:

Groovy and IntelliJ - getting code compiled

I have IntelliJ 12 and some groovy code (along with a pile of java code) in a project.
In intelliJ, i can see class A's import of some groovy code, and i have also included the library that has that code.
However, while the package itself is in one colour (for the import), the actual class being imported is in red, which implies an issue of some sort. Hovering the mouse over it reveals no issue though.
When i run a "make" or a "rebuild project" is where the problems start - i get
Groovyc: unable to resolve class com.blah.blah.blah.A
How can i resolve this?
Currently, my project setup is like so:
Under "Libraries" in (Project Structure -> Project Settings -> Libraries) I have:
the jar file with all the groovy code
the src jar file with all the groovy code
In the "Modules" section i have the - well, i don't know what to call it, the column isn't labelled - the library name from the libraries section associated with the src and class files, and the little "export" button beside it is ticked.
Incidentally, opening the class in intelliJ never shows the source code, which given the source is included struck me as weird.
Is there anything else I should need to do?
I've worked this one out, but if anybody knows why groovy cannot be in the "Resource Patterns" list and wants an upvote, do chime in
Oh, right.
I removed the !?*.groovy entry from the list of, um, entries in the File : Settings -> Compiler -> Resource Patterns thingy.
It doesn't seem to matter if "use external build" is on or off for this, but the !?*.groovy; entry cannot be there.
I wonder if anybody knows why?
I had the same problem and had to Add Framework Support and add Groovy to the project to get round this problem.
I created the project using gradle.
I just got your question in my Google results as I had a similar issue. My problem was that I was able to get the groovy code in my IntelliJ 12 project to compile ok, but it wasn't getting wired in properly when I tried to run unit tests within the IDE.
After some investigation, I uncovered that groovy and logback libraries were all set up in the project to be available in the runtime stage of the Maven build of the project, but that resulted in them not being available in the test stage. To fix this, I ended up manually updating the groovy-all and the logback libraries scope from runtime to provided under File->Project Structure->Modules->Dependencies. This allowed me to both compile and test within the IDE while including the Groovy modules as well as the Java modules.
Perhaps you had something similar going on in your project?
Six years later, I also just got this question near the top of my search results.
In my project my Unable to load class 'groovy.text.SimpleTemplateEngine' problem was actually due to a codenarc issue. I was able to resolve the issue by adding the following to build.gradle:
// codenarc version issue work-around
configurations.codenarc {
resolutionStrategy.eachDependency { DependencyResolveDetails d ->
if (d.requested.group == 'org.codehaus.groovy') {
d.useVersion '2.4.7'
}
}
}

Resources