Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio refuses to run main()

Repro steps:

  1. Start a new project in Android Studio (with the latest update);
  2. Make a new class and add main() as usual;
  3. Right-click class to run main() as a test.
package test;

public class Test {
    public static void main(String[] args) {
    }
}

Usually I expect I can just System.out.printLn("Hello World") but this time, no matter if it's a new project, I get the following error:

2:34:23 PM: Executing task 'Test.main()'...

Executing tasks: [Test.main()] in project C:\Users\regan\Desktop\events\MyApplication


FAILURE: Build failed with an exception.

* Where:
Initialization script 'C:\Users\regan\AppData\Local\Temp\Test_main__2.gradle' line: 20

* What went wrong:
A problem occurred configuring project ':app'.
> Could not create task ':app:Test.main()'.
   > SourceSet with name 'test' not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 0s
2:34:24 PM: Task execution finished 'Test.main()'.

I am fairly new to Java after years of C# in Unity and have no idea what all this stuff is trying to tell me. I have googled but the closest I found was a way to HIDE this error (assuming code was still compiling). I need this code to at least compile.

like image 971
Regan Music Avatar asked Aug 31 '19 02:08

Regan Music


3 Answers

Quick Fix : You can run using Run with Coverage.. See Image Below.

J

Permanent Solution: Add <option name="delegatedBuild" value="false" /> and sync project.

inside File gradle.xml under path E:\Project\.idea\gradle.xml. See Image below.

enter image description here

like image 131
Sukhbir Avatar answered Oct 31 '22 15:10

Sukhbir


Open "gradle.xml" File in this path :

.idea/gradle.xml

Add the following line before </GradleProjectSettings/>

<option name="delegatedBuild" value="false" />

That is it , it worked for me.

like image 31
Jian Chen Avatar answered Oct 31 '22 15:10

Jian Chen


The app module is an android library and expects android lifecycle methods such as onCreate() etc for successful execution. If you want to execute plain java code one option is to add a java library to the project using File -> New Module -> Java Library and add the main method there:

package com.example.lib;

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

This would work as you expect it to.

like image 20
Roshan Avatar answered Oct 31 '22 15:10

Roshan