363

For those times when you want to isolate the Java and give it a quick test..

Can you run non-Android Java projects in Android studio as in Eclipse?

Zoe
  • 27,060
  • 21
  • 118
  • 148
mgibson
  • 6,103
  • 4
  • 34
  • 49
  • 2
    Android studio is based upon intelliJ. So sure, it surely able to run "standard" java code. But why do you need it ? – Blackbelt May 18 '13 at 17:00
  • 1
    @vmironov I agree with you. – Blackbelt May 18 '13 at 17:18
  • @vmironov That's essentially what they're doing. The Android features are an IntelliJ plugin, they just package it together for Android Studio. I haven't used Android Studio in particular, but I've been using IntelliJ for a while, and you should have no issue running standard Java projects within it. – Kevin Coppock May 18 '13 at 17:20
  • 4
    @kcoppock, yep, but this plugin cann't be added to a "usual" IntelliJ IDEA (I have a purchased Ultimate version and I don't really want to switch back to Community edition). The Good news is that JetBrains has announced that it will be possible to have Android Studio's features in Intellij IDEA 13 – Vladimir Mironov May 18 '13 at 17:35
  • So vmirinov are you saying that you can't run standard Android independent Java in Android Studio currently but that in the future, Android Studio will be made "pluggin-able" to IDEA 13 therefore giving you all the Android capability and Java capability in the same place? – mgibson May 18 '13 at 18:18
  • 1
    Is there a simple way to get this to work with Gradle yet? I keep crashing because it cannot see my gradle libraries at runtime. – Katedral Pillon Oct 24 '15 at 16:26
  • I would need to do this, for example, because I have helper apps such as sprite editors, animation editors, etc, which do not run on Android, but which are bespoke apps part of the development process. –  Jul 28 '17 at 08:14
  • My reason to do it is to work on some Kotlin tutorials that target the IntelliJ platform. Everything is new for me at this point, Android, Android Studio, Kotlin, etc., so reducing number of IDEs just helps. – sb4 Feb 29 '20 at 19:07
  • When I try to run a simple class, I get the error "SourceSet with name 'main' not found" – Harsha Mar 07 '20 at 07:55

13 Answers13

383

Tested on Android Studio 0.8.6 - 3.5

Using this method you can have Java modules and Android modules in the same project and also have the ability to compile and run Java modules as stand alone Java projects.

  1. Open your Android project in Android Studio. If you do not have one, create one.
  2. Click File > New Module. Select Java Library and click Next.
  3. Fill in the package name, etc and click Finish. You should now see a Java module inside your Android project.
  4. Add your code to the Java module you've just created.
  5. Click on the drop down to the left of the run button. Click Edit Configurations...
  6. In the new window, click on the plus sign at the top left of the window and select Application
  7. A new application configuration should appear, enter in the details such as your main class and classpath of your module.
  8. Click OK.

Now if you click run, this should compile and run your Java module.

If you get the error Error: Could not find or load main class..., just enter your main class (as you've done in step 7) again even if the field is already filled in. Click Apply and then click Ok.

My usage case: My Android app relies on some precomputed files to function. These precomputed files are generated by some Java code. Since these two things go hand in hand, it makes the most sense to have both of these modules in the same project.

NEW - How to enable Kotlin in your standalone project

If you want to enable Kotlin inside your standalone project, do the following.

  1. Continuing from the last step above, add the following code to your project level build.gradle (lines to add are denoted by >>>):

    buildscript {
        >>> ext.kotlin_version = '1.2.51'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.1.3'
            >>> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
    ...
    
  2. Add the following code to your module level build.gradle (lines to add are denoted by >>>):

    apply plugin: 'java-library'
    >>> apply plugin: 'kotlin'
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        >>> implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
        >>> runtimeClasspath files(compileKotlin.destinationDir)
    }
    ...
    
  3. Bonus step: Convert your main function to Kotlin! Simply change your main class to:

    object Main {
        ...
        @JvmStatic
        fun main(args: Array<String>) {
            // do something
        }
        ...
    }
    
AskQ
  • 4,215
  • 7
  • 34
  • 61
idunnololz
  • 8,058
  • 5
  • 30
  • 46
  • 2
    I can confirm this works in Android Studio 0.8.14. I used a basic Hello World project, and added a Custom class containing a main method. I deleted the MainActivity.java file. At step 2, I needed to disclose the More Modules pane (bottom left of the Create New Module window) and scroll down to find the Java Library item. At step 6, I named my application, selected Custom as my main class, and app for the classpath of the module. NOTE: If you delete the app module, as per @simonp's solution, your application will run, but with errors. – James Newton Nov 21 '14 at 13:52
  • There should be another step after step 2 : add code to the class, or at least make it a Hello-World code: http://docs.oracle.com/javase/tutorial/getStarted/application/ – android developer Dec 21 '14 at 23:10
  • 3
    But how can I export a desktop project to a .jar file? I can't find that option anywhere :/ – Chris Aug 13 '15 at 16:16
  • Is there a way of importing an existing java library project from say eclipse in AS (except of course of copy pasting the code in step 4 ?) – Mr_and_Mrs_D Dec 18 '15 at 23:23
  • Thanks; your use case is identical to my own: I have a Java utility program that generates some files that are included as part of my app, which the app then uses. So it makes sense to have these things in the same IDE. – Carl May 07 '16 at 02:24
  • 1
    Works in 2.2.2! :) – Pavel Biryukov Oct 27 '16 at 13:50
  • Did you integrate running the Java code into the build process for the Android app? If so, how did you do that? – Ted Hopp Nov 21 '16 at 20:39
  • @idunnololz Nice explanation and it works with Android Studio 3.0. Will the java module class files get added into APK when we generate it? – Pioneer Oct 27 '17 at 14:34
  • @Shail no it will not. As long as you did not modify the gradle build file, gradle will only build/package the Android project when you generate an APK. – idunnololz Nov 05 '17 at 01:48
  • Yes it does, I was able to make it run on 3.0.1 after several hacks, tweaks and gradle syncs. I had to add a `jar { }` configuration otherwise on runtime it won't find any dependencies (`Class not found` errors and the such) – Shujito Mar 19 '18 at 19:58
  • Error: Could not find or load main class Foo – That's Enam Mar 28 '18 at 08:32
  • @Enam: try re-running it after that (works most of the time) and use `implementation` instead of `compile` in the module dependencies. And the only issue I have right now is reading app's resources. – Shujito May 25 '18 at 21:49
  • If I remove the app module from the project structure I am forced to manually sync the project with gradle files to show the Java library folder at every project startup. Is it possible to avoid that? – Evolve_or_Die Oct 24 '18 at 07:07
  • 1
    worked great ! I used Android Studio 3.1.4. Thanks for sharing ! – Birender Singh Nov 27 '18 at 04:02
  • Worked on 3.5! Thanks! – AskQ Oct 22 '19 at 09:15
  • I get this warning, after the code has been executed. It's a little annoying. "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." – Harsha Mar 07 '20 at 08:37
  • But what if my Java module uses Maven as the dependency management system not gradle? – Adam Burley Jul 26 '21 at 21:07
28

EDIT: many moon after this question was asked, yes, now apparently you can.

No, but it's based on Intellij IDEA.

The community version of that is free for download but it doesn't support most things requiring an external database or application server. The line for Java is pretty much that JavaSE code can happily use Community.

If you want that (or are using JavaEE) then you either need the Ultimate version, which isn't free, or the EAP of the next version which is usually good for a month until they release another.

Basically it works like this

Android Studio is just Android the Android Stuff from IDEA 13 Community...

...which will be free, and is anything from IDEA 13 Ultimate...

...that doesn't require a database or app server.

http://www.jetbrains.com/idea/

IDEA 12 Community doesn't have the ability to import the gradilized project and it won't, so while you can do Android development in it now (I do), don't expect it to have the same features as Android Studio. There's a lot of good new Android stuff in it, that's going into 13.

JoeHz
  • 2,136
  • 1
  • 18
  • 29
  • 3
    Happy to help! I personally love IDEA and loathe Eclipse. This is the first time I've gone to playing with the EAP because I'm clearly going to need compatibility with everyone migrating to Android Studio. – JoeHz May 20 '13 at 11:12
  • As of AS 0.5.8, this is no longer correct. You can definitely run standard Java SE code in AS. At least I have success importing a Swing project, developing, and running it. Unfortunately, you cannot create a "regular" Java project as of this writing, at least not that I know of. – Code-Apprentice May 14 '14 at 02:53
  • 3
    As of 0.6.1 you can. See my answer below. – simonp Jun 17 '14 at 23:03
  • 6
    Please delete/edit this answer since it is no longer correct. Android Studio can now build Java modules and run them in the local JRE. – Navin Jun 30 '15 at 10:47
  • So it's better to use Android-Studio for android stuff, and IntelliJ for Java and the rest? What about SWT support on IntelliJ? Do you know of a nice UI designer for it? I need it mostly for preview of the UI . – android developer Mar 20 '16 at 08:29
  • Not deleting an answer as it has historical relevance but I updated it. Are SO users really expected to caretake their old SO questions and answers or is the date warning enough? I always thought it was because of stuff like this happening to my answers: http://stackoverflow.com/questions/526074/android-activity-with-no-gui/6476811#6476811 – JoeHz Nov 13 '16 at 01:26
24

Easy way to run a java program in Android Studio would be,

  1. Create a java Class says "Test.java" in Android Studio.

  2. Write your code eg, a Hello World program to test.

  3. Right-click on the Java class and:

  • select the option Run 'Test.main()'

or

  • press CTRL + SHIFT + F10 (on windows) or control + R (on Mac)

There you have your Java code running below.

Boken
  • 4,825
  • 10
  • 32
  • 42
Shruti Dasgopal
  • 551
  • 4
  • 10
  • 3
    This worked - thanks! In my case I was having issues with the gradle build crashing, when first trying to run this. So I did a `Android Studio > File > Invalidate Caches / Restart` and then the issue was resolved – Gene Bo Feb 20 '17 at 19:29
  • 1
    @Shruti It takes a while to compile the first time after switching from running the app to running the test.java. Do you know if the executable it's creating is added to the APK size at all? – Patrick Aug 25 '17 at 06:54
  • 1
    For Kotlin: Click on the arrow next to `main()`, do NOT right-click the file or method name – xjcl Nov 23 '20 at 23:23
  • On Mac, Run 'Test.main()' is now ⌃⇧R – goodhyun Mar 07 '22 at 09:06
  • 2
    It does not work for me. I get this: `A problem occurred configuring project ':app'. > Could not create task ':app:MyClass.main()'. > SourceSet with name 'main' not found.` – Sambhav Khandelwal May 31 '22 at 09:47
  • I also got the 'main' not found error, but then I chose "Run with Coverage" and it worked fine. – Alexander Pruss Nov 26 '22 at 14:44
17

With Android Studio 0.6.1+ (and possibly earlier) you can easily develop standard Java (non-Android) apps.

This method has been tested on 0.8.2:

Start by creating a vanilla Android Phone app, using File > New Project. Then add a Java Library module to hold your Java Application code. (Choose 'Java Library' even if you're building an application). You'll find you can build and run Java apps with main() methods, Swing apps etc.

You'll want to delete the auto-generated Android "app" module, which you're not using. Go to File -> Project Structure, and delete it (select the "app" module in the box on the left, and click the 'minus' icon above the box). Now when you reopen File -> Project Structure -> Project, you'll see options for selecting the project SDK and language level, plus a bunch of other options that were previously hidden. You can go ahead and delete the "app" module from the disk.

In 0.6.1 you could avoid creating the android module in the first place:

Go to File > New Project. Fill in your application name. On the "form factors" selection page, where you state your minimum Android SDK, deselect the Mobile checkbox, and proceed with creating your project.

Once the project is created, go to File -> Project Structure -> Project, and set your JDK as the "Project SDK". Add a Java Library module to hold your application code as above.

simonp
  • 2,827
  • 1
  • 14
  • 19
  • Where can I find the build then? If I click Build->Make Project or Build->Compile 'PureJava.java' android studio says "Compilation completed successfully". But I can't find any build files. I deleted the app module as well as the app folder. – AndiPower Aug 01 '14 at 23:19
  • 1
    Have you been able to debug those projects? – MLProgrammer-CiM Sep 19 '14 at 12:49
  • @MLProgrammer-CiM yes it is possible. It has happened to me that when debugging, the IDE stalls at some point in the "updating indices" phase, I don't know what's causing it, I've tried cleaning caches and restarting. – Shujito Mar 14 '17 at 19:57
16

Here's exactly what the setup looks like.

enter image description here

Edit Configurations > '+' > Application: enter image description here

AdamHurwitz
  • 9,758
  • 10
  • 72
  • 134
  • HI Adam, can I know if it still works? And why would we need gradle for this application? Could the project be further cleaned up so just the bare minimum files are present? – Harsha Mar 07 '20 at 09:32
  • Hi @Harsha, I implemented this as an experiment in 2016. I have not implemented this recently as I use standalone IntelliJ for backend Kotlin/Java applications. Feel free to update the comments/post with your updated findings. – AdamHurwitz Mar 07 '20 at 17:24
  • I have done it in the same way. It is still working. I would like to start it from the command line but I can not find how to instruct Gradle to use the application configuration. – Todor Balabanov May 01 '21 at 20:42
5

I found a somewhat hacky, annoying and not-completely-sure-it-always-works solution to this. I wanted to share in case someone else finds it useful.

In Android Studio, you can right-click a class with a main method and select "Run .main()". This will create a new Run configuration for YourClass, although it won't quite work: it will be missing some classpath entries.

In order to fix the missing classpath entries, go into the Project Structure and manually add the output folder location for your module and any other module dependencies that you need, like so:

  • File -> Project Structure ...
  • Select "Modules" in the Project Settings panel on the left-column panel
  • Select your module on the list of modules in the middle-column panel
  • Select the "Dependencies" tab on the right-column panel

And then for the module where you have your Java application as well as for each of the module dependencies you need: - Click "+" -> "Jars or directories" on the far right of the right-column panel - Navigate to the output folder of the module (e.g.: my_module/build/classes/main/java) and click "OK" - On the new entry to the Dependencies list, on the far right, change the select box from "Compile" to "Runtime"

After this, you should be able to execute the Run configuration you just created to run the simple Java application.

One thing to note is that, for my particular [quite involved] Android Studio project set-up, I have to manually build the project with gradle, from outside Android Studio in order to get my simple Java Application classes to build, before I run the application - I think this is because the Run configuration of type "Application" is not triggering the corresponding Gradle build.

Finally, this was done on Android Studio 0.4.0.

I hope others find it useful. I also hope Google comes around to supporting this functionality soon.

Julian Cerruti
  • 1,918
  • 2
  • 16
  • 16
3

I installed IntelliJ IDEA community version from http://www.jetbrains.com/idea/download/

I tried opening my project that I started in Android studio but it failed when at gradle build. I instead opened both android studio and intellij at same time and placed one screen next to the other and simply drag and dropped my java files, xml layouts, drawables, and manifest into the project hiearchy of a new project started in IntelliJ. It worked around the gradle build issues and now I can start a new project in IntelliJ and design either an android app or a basic Java app. Thankfully this worked because I hated having so many IDEs on my pc.

cjayem13
  • 903
  • 10
  • 24
3

I have been able to do it using following steps:

  1. Open Android Studio and select 'Import Project'.
    Android Studio import a project

  2. Browse to your project folder in the browse window and select it.

ganchito55
  • 3,559
  • 4
  • 25
  • 46
1

Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:

  • In an open Android Studio project, click File > New Module.
  • Click More Modules > Java Library > Next, then fill in whatever you prefer for the names.
  • A new module will appear as a folder on the same level as your "app" folder in the Project Structure. Open it and open the new Java class file.

    You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!

  • John
    • 640
    • 2
    • 8
    • 18
    0

    It works perfect if you do File>Open... and then select pom.xml file. Be sure to change the dropdown at the top-left of the sidebar that says "Android" to "Project" to see all your files. Also I think it helps if the folder your pom.xml file is in a folder called "app/".

    Disclaimer: My java project was generated by Google App Engine.

    0

    Spent a day on finding the easiest way to do this. The purpose was to find the fastest way to achieve this goal. I couldn't make it as fast as running javac command from terminal or compiling from netbeans or sublime text 3. But still got a good speed with android studio.

    This looks ruff and tuff way but since we don't initiate projects on daily bases that is why I am okay to do this.

    I downloaded IntelliJ IDEA community version and created a simply java project. I added a main class and tested a run. Then simply closed IntelliJ IDEA and opened Android Studio and opened the same project there. Then I had to simply attach JDK where IDE helped me by showing a list of available JDKs and I selected 1.8 and then it compiled well. I can now open any main file and press Control+Shift+R to run that main file.

    Then I copied all my Java files into src folder by Mac OS Finder. And I am able to compile anything I want to.

    There is nothing related to Gradle or Android and compile speed is pretty good.

    Thanks buddies

    Asif Ashraf
    • 665
    • 1
    • 7
    • 15
    0

    To run a java file in Android ensure your class has the main method. In Android Studio 3.5 just right click inside the file and select "Run 'Filename.main()'" or click on "Run" on the menu and select "Run Filename" from the resulting drop-down menu.

    Alabi
    • 11
    • 3
    0

    on Android Studio 4.0 and above, you will get an option readily on the IDE,a green run icon to run the related main() class.

    enter image description here

    Yauraw Gadav
    • 1,706
    • 1
    • 18
    • 39