Creating test folders in legacy Android Studio project - java

I've been having issues getting test folders adding to my existing legacy project. I've been looking through Stack and whilst these users are all having similar issues, the solutions haven't yet worked. I'm new at working with gradle, so this has been a bit confusing.
How to add test folders to an older Android Studio Project
Android studio doesn't recognise source folders
Cannot Create Testing Folders In Android Studio
The problem can be seen below:
When looking at android view, I get this.
You can see that there's a visible alpha and main folder.
Looking at project view, you can see the addition of the src/test/java and src/androidTest/java to the folder structure, but I can't get them to register in Android view.
I've tried setting the sourceSets in the gradle file:
sourceSets {
beta {
java.srcDirs = [ 'src/general/java']
res.srcDirs=['src/general/res']
}
general {
java.srcDirs = [ 'src/general/java', 'src/androidTest/java/', 'src/test/java']
res.srcDirs=['src/general/res']
}
demo {
java.srcDirs = [ 'src/alpha/java']
res.srcDirs=['src/alpha/res']
}
alpha {
java.srcDirs = [ 'src/alpha/java', 'src/androidTest/java/', 'src/test/java']
res.srcDirs=['src/alpha/res']
}
test {
java.srcDirs = ['src/test/java']
}
androidTest {
java.srcDirs = ['src/androidTest/java']
}
}
where test and androidTest are new. (Note: the others all have buildflavors associated with them, and I haven't created any for the tests. Could this be the issue?)
Some of the previous suggestions have said it's to do with build version and that there should be a testing related dropdown - here. I've tested all of the builds with no success.
Another user suggested using the build task assembleAndroidTest to generate the folders, which gives the following error:
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':library:processDebugAndroidTestResources'.
Android resource linking failed
I've been having other issues with trying to get testing working whilst following through google's recommended documentation. Dependencies and manifest declarations have worked fine but trying to add
useLibrary 'android.test.runner'
useLibrary 'android.test.base'
useLibrary 'android.test.mock'
I get
Error:Unable to find optional library: android.test.runner
Which I've seen referenced for apache legacy but little for this situation. I think this is probably a different problem but included it in case it was relevant.
Android studio is at version 3.2.1.
So in summary:
How do I add test folders to the project and get them to display in Android view?
Thanks.

I found the problem. A simple fix.
Inside the main, the folder structure was
main/java/com/windowmaker/measure
and the folder structure for my test folders was
test/java
By changing the path to
test/java/com/windowmaker/measure
it now displays correctly.
Hooray!

Related

Converting existing Flutter Java Android project to Kotlin

I have an existing Flutter project that was created with Android Java set.
I tried removing my android directory and running flutter create -a kotlin .. App fails to run and error says it is still expecting main/java/com/myApp/MainActivity.java even though the main/kotlin/com/myApp/MainActivity.kt was generated. Any ideas?
In your android app level, check your build.gradle and make sure you have this
android {
...
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
...
}
you can change the dir path to your MainActivity.kt placed

Android Studio refuses to run main()

Repro steps:
Start a new project in Android Studio (with the latest update);
Make a new class and add main() as usual;
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.
Quick Fix : You can run using Run with Coverage.. See Image Below.
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.
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.
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.
Try to run it with "coverage". I don't have any explanation, but it works!
I'm currently using Android Studio Version 4.0.1
after creating the project, you should go to tab
File ==> New ==> New Module...
on "Create New Module/ Selecte Module Type":
Select Java or Kotlin Library
After it finish, go to javalib folder/ module that you have created.
Create Java file on there.
try to run it
I had this problem momentarily as well
I found when I changed Gradle to offline and then back online again then updated Gradle and made sure the connection and proxy settings were correct, things started working normally
Avoid naming the class name as Test, Android studio somehow will get screwed when you name class as Test.
If the module is from an android application or library it is not allowed to run the main; because what is expected is navigate transitions between stages of the activity lifecycle.
In the following cases of modules with these plugins applied, the main can NOT be run.
build.gradle.kts (:appAndroid)
plugins {
id("com.android.application")
id("kotlin-android")
}
build.gradle.kts (:libraryAndroid)
plugins {
id("com.android.library")
id("kotlin-android")
}
build.gradle.kts (:kmmShared)
plugins {
kotlin("multiplatform")
id("com.android.library")
}
If the purpose of running the main was to test things, what you really have to do is use the sourceSets of test.
If the module is from a Java or Kotlin library, running the main is allowed so the error would not exist.
The following applied plugins describe a JVM library:
build.gradle.kts (:jvmLibrary)
plugins {
id("java-library")
id("kotlin")
}
Finally, if using the test sourceSets or creating a JVM module was not enough for you, there is a 'hack' which is weak because it depends on the IDE (It does not work in KMM modules).
.idea/gradle.xml
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="delegatedBuild" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
GL
I have not much idea about it as I am very new in Android development and Android Studio. But after reading some solution over the internet and watchin some Youtube Videos, I have fixed it.
In app/build.gradle under dependencies for me
implementation 'androidx.appcompat:appcompat:1.4.1' - this was there
I changed it to
implementation 'androidx.appcompat:appcompat:1.2.0'
rebuilt the project and run, it worked for me..
I guess there must be some android studio update (in the latest version) was causing the problem.
I also got stuck in this problem. I am using Android Studio Arctic Fox in Macbook Pro M1. I have also tried to add New Module and Select Java and Kotlin Library and edited the configuration but it did not work for me. But it did work on my Windows System.
In macbook, I simply downgraded the dependancy in my App level build.gradle file
from
implementation 'androidx.appcompat:appcompat:1.5.0'
to
implementation 'androidx.appcompat:appcompat:1.2.0'
and run my Java Class as Run as Coverage and it worked.

How to change the package name of an Android flavor app with Gradle?

I am currently migrating a very old Android app from Eclipse to Android Studio.
In the old version of my app, I was able to create some "flavors" with an Ant script. The aim of this script was to do a copy of the Eclipse project with a different package name and with different resources (drawable, etc.)
I have migrated the project to Android Studio, deleted the Ant script and created some flavors.
But now, I have some issues to deserialize - in the new version of the app - an object serialized in the old version of the app.
Here a part of the stackstrace : Caused by: java.lang.ClassNotFoundException: com.company.app.flavor.bo.Player
In the old version, each flavors had it own package name :
com.company.app
com.company.app.flavor
In this new version, the code structure is com.company.app.flavor and I play with Gradle in order to generate the good applicationId for the flavor.
So, the applicationId for the flavor is correct, but the package name of the class seems to respect the project structure so, I cannot deserialize the original object with the package com.company.app.flavor.bo.Player into the object com.company.app.bo.Player.
If I change the structure of the project with com.company.app.flavor it will work for the flavor but not for the original one with the applicationId com.company.app.
So, is there a way, with Gradle or maybe another tool (proguard ?) to change the applicationId AND the package name for a flavor ?
Thank you in advance for your help.
Yes you can have ProductFlavor in gradle and this supposed to change the package name of the app. If you didn't hardcoded the classpath then serialization also should work without any issues.
android {
.
.
.
defaultConfig {
applicationId "lib4.com.stackoverflow"
}
productFlavors {
staging {
applicationIdSuffix ".staging"
}
preProduction {
applicationIdSuffix ".preProduction"
}
}
}
Once the apk got created, you can verify whether the package name has been changed or not by dragging and dropping apk on android studio and open Android Manifest. You will see the updated package name in the manifest in apk. But in source code, you will still see the package you provided earlier.

Android Project Structure Changed After Gradle Sync

I am working with android studio attempting to implement the following github within my own application
https://github.com/jhansireddy/AndroidScannerDemo
When following the instructions I add the following line to the gradle
compile project(':scanlibrary')
After adding the above i then sync the gradle and the whole project structure changes, to the point where i no longer recognise it
Original Project Structure
New Project Structure
If you havnt gathered i am fairly new to the whole android programming thing
One thought i had was that the git project uses OpenCV and it was related to this, however i have not manually installed OpenCV
You have to import scan library to bring project structure to normal. Follow these steps:
1 - Download zip from this link.
2 - Extract it and copy location of scanlibrary project present inside ScanDemoExample. In my case it is like (D:\Amrit\AndroidScannerDemo-master\AndroidScannerDemo-master\ScanDemoExample\scanlibrary).
3 - Now come back to Android Studio, select
File -> New -> Import Module
and paste copied location path from previous step in source directory which will result in module name :scanlibrary. Click on Finish to close the dialog.
4 - Now your project structure will look like image below. (You can view it by selecting File -> Project Structure).
5 - Don't forget to add dependency
compile project(':scanlibrary')
inside build.gradle file.
6 - Now your library is ready to use with your project. In case you are facing any errors try cleaning & rebuilding your project. And more often errors are import problem so try including these imports :
import com.scanlibrary.ScanActivity;
import com.scanlibrary.ScanConstants;
where ScanActivity & ScanConstants are classes present inside scanlibrary.
Let me know if you have any doubts. Happy coding!
add this depenedency in build.gradle
implementation 'com.github.neutrinosplatform:scanlibrary:3.3'
and add maven in repositories
maven { url 'https://jitpack.io' }

ndk.dir error in Android Studio

I was trying to use opencv library, so I imported one of its projects in Android Studio and when I tried to run it I got this error:
Error:Execution failed for task ':openCVSamplefacedetection:compileDebugNdk'.
NDK not configured.
Download the NDK from http://developer.android.com/tools/sdk/ndk/.Then add ndk.dir=path/to/ndk in local.properties.
(On Windows, make sure you escape backslashes, e.g. C:\ndk rather than C:\ndk)
So I downloaded the ndk and I addes this line to the local.properties file where it became:
sdk.dir=C\:\\Users\\skoon\\AppData\\Local\\Android\\sdk
ndk.dir=C\:\\Users\\skoon\\AppData\\Roaming\\IDM\\android-ndk-r10d
but I still got this error which I didn't understand:
Error:Execution failed for task ':openCVSamplefacedetection:compileDebugNdk'.
com.android.ide.common.internal.LoggedErrorException: Failed to run command:
C:\Users\skoon\AppData\Roaming\IDM\android-ndk-r10d\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=C:\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\build\intermediates\ndk\debug\Android.mk APP_PLATFORM=android-14 NDK_OUT=C:\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\build\intermediates\ndk\debug\obj NDK_LIBS_OUT=C:\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\build\intermediates\ndk\debug\lib APP_ABI=all
Error Code:
2
Output:
make.exe: *** No rule to make target 'C:\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\build\intermediates\ndk\debug\obj/local/arm64-v8a/objs/detection_based_tracker/C_\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\src\main\jni', needed by `C:\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\build\intermediates\ndk\debug\obj/local/arm64-v8a/objs/detection_based_tracker/C_\Users\skoon\Downloads\Compressed\OpenCV-2.4.10-android-sdk\OpenCV-2.4.10-android-sdk\samples\face-detection\openCVSamplefacedetection\src\main\jni\DetectionBasedTracker_jni.o'. Stop.
I didn't change anything in the code, so what should I do? do I need to change or add any variables to point to the ndk?
P.S. This is my first time trying to build Android application so I don't have any experience.
Thank you in advance.
UPDATE:
To import the project I just used import project from file, then I synced the gardle, and run the project.
the package that I downloaded from opencv was the Android one, and I tried to use the face detection sample.
when I run it I got the error above.
You need to setup OpenCV librairies for your project. You can follow the instruction here.
OpenCV sample projects haven't support gradle officially. I think it will be easier if you start a new project and configure it to work as in examples.
I have implemented a tutorial project using Android Studio + NDK + OpenCV. You may have a look. https://github.com/quanhua92/NDK_OpenCV_AndroidStudio
Install NDK in your SDK manager, if you already installed open app's "build.gradle" replace these lines
sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jniLibs/', 'src/main/jni/'] } }
to
sourceSets.main {
jniLibs.srcDir 'src/main/jniLibs' // mention your JNI lib path(where ".so" files contains)
jni.srcDirs = [] //disable automatic ndk-build call
}
I'm tried to configure OpenCV and its fixed

Categories