Java build path android studio

How to Set Java SDK Path in Android Studio?

The Java SDK for Android is a sophisticated suite of tools for managing, monitoring, profiling, and debugging Java code written in Android Studio. But sometimes as software is unpredictable you might be caught in an error that Android Studio stopped compiling projects and says that it can’t locate the 1.7.0_21 folder. Well, this is exactly what is referred to as a missing Java SDK Path.

How to Fix the Java SDK Path?

There are several methods that can help you resolve this issue, the ones which have the highest score in fixing this problem are mentioned below:

Method #1: For Android Studio Version 4.2 and Above

Navigate to File > Project Structure > SDK Location. Upon navigating there you will find that a tab named “JDK Location”, select that and then you can set the JDK path for the current project on which you’re working.

Image I. Setting Project SDK location in 4.2 & +

Method #2: For Android Studio Version Below 4.2

Chances are that you might be rocking an older version of Android Studio, if yes then

Navigate to File > Project Structure > [Platform Settings] > SDKs

You’ll then need to either update your current SDK setup to make use of the new directory or create a new directory and then adjust the settings in your project to make use of the new directory. This will make it applicable to the present project.

Method #3: Adding a new SDK to Your Android Studio

Sometimes only updating your SDKs won’t allow you to compile projects just because the SDK has lived its life and requires an update to itself. In that scenario, you’ll need to recreate the configurations from 0.

  1. Navigate to Project Structure > Platform Settings > SDKs and click the “+” button.
  2. Go to your Android SDK folder and select “Choose” on the pop-up.
  3. A new pop-up window will open, asking which SDK and JDK you’d want to use. Select any Android SDK and the JDK 1.7.

Note: Change your Project SDK to the one you just established under Project Structure > Project Settings > Project. The name of the SDK should now include the new Java version that you installed.

Method #4: For the Command Line Enthusiasts

If you want to be a Geek and the above methods are just too much GUI for you, you might want to handle the SDK path using the terminal. In order to achieve that using the command line, follow the below commands in the Android Studio’s Terminal

Читайте также:  Android os parcel что такое

and just like that, you’ve achieved the desired result

Note: the ‘oldjre‘ here refers to your old JRE path

Method #5: Using the Embedded SDK

If you are on Android Version 3.2 or older then you’ll be having the option of using the embedded JDK & SDK for your project and that is one of the optimal ways you can fix this issue as Android Studio will handle the management of the services in the Backend!

Navigate to File > Project Structure > JDK Location and Checkmark the box saying “Use embedded JDK (recommended)”.

Image II. Checking the Recommended JDK Location

Method #6: Setting and Viewing SDK using the Studio Project Structure

If all the above-mentioned ways didn’t work out for you, the best you can do is to get the SDK path of another Android Studio Project and then providing that path to your particular project (as in Method #1)

Press Ctrl (Command on Mac) + Alt + Shift + S

Then in the SDK Location tab, you will find your SDK Location, just copy it and paste it in the SDK Location as mentioned in Method #1.

Источник

Куда Android studio закачивает JDK?

Подскажите пожалуйста, куда она его скачивает, если вообще скачивает.

Т.е. нужен для работы ASstydio JDK?

  • Вопрос задан более года назад
  • 103 просмотра

Оставил самое главное

Кроме этого в пути нужно добавить
C:\Program Files\Android\Android Studio\jre\bin

ANDROID_SDK_ROOT=C:\Users\kvn\AppData\Local\Android\Sdk
ChocolateyInstall=C:\ProgramData\chocolatey
ChocolateyLastPathUpdate=132455740198058264
GRADLE_HOME=C:\bin\gradle-6.6.1
Path=C:\Python38\Scripts\;C:\Python38\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\bin\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files\Git\cmd;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Users\kvn\AppData\Local\Microsoft\WindowsApps;C:\Users\kvn\.dotnet\tools;C:\Users\kvn\AppData\Roaming\npm;C:\bin\gradle-6.6.1\bin;C:\Program Files\Android\Android Studio\jre\bin;;C:\Users\kvn\AppData\Local\Programs\Microsoft VS Code\bin

Источник

Android Studio для NDK под Windows

На днях я обнаружил, что версия Android Studio неуклонно стремится к единице, в связи с чем задумался об изучении этого инструмента. Чтобы не было скучно, я решил поделиться своим опытом и собранными граблями в виде статьи-туториала.

Сразу хочу оговориться, что я не являюсь гуру Android-разработки, поэтому каких-либо откровений в тексте вы не найдете. Зато тут есть пошаговая инструкция по установке и настройке Android Studio под Windows и созданию простейшего проекта с использованием Android NDK.

Также заранее предупреждаю: статья получилась большой и очень подробной (честно, сам не ожидал), даже несмотря на то, что я почти все скриншоты и некоторые листинги кода спрятал под спойлеры.

На момент написания последней версией Android Studio была 0.8.1, для последующих версий необходимые действия могут отличаться от нижеописанных (очень надеюсь, что в лучшую сторону).

Установка и настройка Android Studio

1. Необходимо установить JDK (Java Development Kit) и JRE (Java Runtime Environment).

Раньше Android SDK поддерживал только JDK версии 6, но теперь это в прошлом. Поддерживается 7 и даже 8 (по крайней мере, именно 8-ю версию я указал в качестве JAVA_HOME и в настройках Android Studio, и никаких проблем не испытал).
JRE же нужен для запуска самой студии. У меня она использует версию 7.
Скачать JDK и JRE версий больше 6 можно с сайта Oracle.

Переменную JAVA_HOME теперь, вроде бы, можно не устанавливать, так как в Android Studio мы будем в настройках прописывать путь к JDK. Но я ее установил. Для этого нужно:

  • Зайти в Панель управления\Система и безопасность\Система, выбрать слева Дополнительные параметры системы, в открывшемся диалоге найти кнопку Переменные среды.
  • Создать системную или пользовательскую переменную JAVA_HOME и указать для нее путь к JDK. У меня указан вот такой путь: C:\Program Files\Java\jdk1.8.0_05.
Читайте также:  Обзор клавиатур для android приставок

2. Если у вас установлен Android SDK.

В комплекте с Android Studio идет свой Android SDK. И, если вы хотите использовать именно его, то в некоторых случаях может случиться странное. Например, у меня при обновлении SDK через SDK Manager часть файлов записывалась в старую папку, и возникли проблемы, когда я эту папку удалил. Скорее всего это произошло из-за того, что в реестре хранился ключ с путем к старой папке. Поэтому имеет смысл почистить реестр. Для этого нужно запустить regedit.exe и найти HKEY_LOCAL_MACHINE\Software\Android SDK Tools для 32-битных машин либо HKEY_LOCAL_MACHINE\Software\Wow6432Node\Android SDK Tools для 64-битных машин и удалить Android SDK Tools. Если в реестре вашей системы таких ключей нет, то все в порядке.

Если у вас установлена переменная среды ANDROID_SDK_HOME и вы хотите, чтобы она указывала на старую установку, то, по идее, это не должно стать проблемой, так как при настройке Android Studio мы укажем ей путь к SDK. Проблемы могут возникнуть, если эту переменную использует какое-либо из приложений, входящих в состав Android SDK.

3. Теперь переходим к установке Android Studio.

Нужно скачать Android Studio для вашей системы с официальной страницы и установить ее. По умолчанию, если выбрать «Установить только для меня» ставится в \Users\ \AppData\Local\Android\android-studio\, иначе ставится в \Program FIles (x86)\Android\android-studio\. Можно выбрать и другую папку.

После установки запускаем Android Studio.

Источник

How to make Android apps without IDE from command line

Nov 26, 2017 · 5 min read

A HelloWorld without Android Studio

Update: I’ve made a new course that explain how you can avoid Android Studio and Gradle, but still use IntelliJ iDE:

How to do Android development faster without Gradle

IntelliJ IDE, but not Gradle

In this tutorial, I will show you how you can build/compile an APK (an A n droid app) from your java code using terminal (on Linux) without IDE or in other words without Android Studio. At the end, I will also show you a script to automate the process. In this example, I will use Android API 19 (4.4 Kitkat) to make a simple HelloWorld. I want to say that I will do this tutorial without android command which is deprecated.

1. Install Java

First, you need to install java, in my case, I install the headless version because I don’t use graphics (only command line):

2. Install all SDK tools

Then download the last SDK tools of Android which you can find here:

Download Android Studio and SDK Tools | Android Studio

Download the official Android IDE and developer tools to build apps for Android phones, tablets, wearables, TVs, and…

I recommend to unzip it in the /opt directory inside another directory that we will call “android-sdk”:

Now, we have to install platform tools (which contain ADB), an Android API and build tools.

In fact, if you are on Debian, you can avoid installing platform-tools package and only install ADB like that:

3. Code the application

In this example, I want to compile a simple HelloWorld. So, first, we need to make a project directory:

Then we have to make the files tree:

If you use exernal libraries (.jar files), also make a folder for them:

You have an example here:

How to use JavaMail on Android (without Gradle)

Hello guys!

Make the file src/com/example/helloandroid/MainActivity.java and put that inside:

Make the strings.xml file in the res/values folder. It contains all the text that your application uses:

Читайте также:  Планшет не включается пишет только андроид

The activity_main.xml is a layout file which have to be in res/layout:

You also have to add the file AndroidManifest.xml at the root:

4. Build the code

Now, I recommend to store the project path in a variable:

First, we need generate the R.java file which is necessary for our code:

  • -m instructs aapt to create directories under the location specified by -J
  • -J specifies where the output goes. Saying -J src will create a file like src/com/example/helloandroid/R.java
  • -S specifies where is the res directory with the drawables, layouts, etc.
  • -I tells aapt where the android.jar is. You can find yours in a location like android-sdk/platforms/android-/android.jar

Now, we have to compile the .java files:

If you have use an external, add it the classpath:

The compiled .class files are in obj folder, but Android can’t read them. We have to translate them in a file called “classes.dex” which will be read by the dalvik Android runtime:

But if you use external libraries, do rather:

If you have the error UNEXPECTED TOP-LEVEL EXCEPTION , it can be because you use old build tools and DX try to translate java 1.7 rather than 1.8. To solve the problem, you have to specify 1.7 java version in the previous javac command:

The -source option specify the java version of your source files. Note that we can use previous versions of Java even we use OpenJDK 8 (or 1.8).

We can now put everything in an APK:

Be aware: until now, we used three AAPT commands, the first and the second one are similar but they don’t do the same. You have to copy the classes.dex file at the root of project like above! Otherwise, AAPT won’t put this file at right place in the APK archive (because an APK is like a .zip file).

The generated package can’t be installed by Android because it’s unaligned and unsigned.

If you want, you can check the content of the package like this:

5. Sign the package

To do so, we firstly create a new keystore with the command keytool given by Java:

Just answer the questions and put a password.

You can sign an APK like this:

Note that apksigner only exist since Build Tools 24.0.3.

6. Align the package

It’s as simple as that:

Alignment increase the performance of the application and may reduce memory use.

7. Test the application

To test the application, connect your smartphone with a USB cable and use ADB:

But before run this command, I recommend to run this one:

If there is an error during installation or running, you see it with that command.

Voila! Here’s the result:

8. Make a script

If you don’t want to run all these steps every time you would like to compile your app, make a script! Here’s mine:

Notes

  • You can remove “test” if you just want to compile without testing.
  • This script only compile and run the app on the phone. But I can also make a script to automatically generate a new project like this one. I think I have a good idea to do so, but I need to know if you are interested. If it’s the case, please leave a comment or send me an e-mail.
  • I can also complete the script for external libraries. Likewise, let me know if you want this.

If you have any questions, don’t hesitate to ask them below or by e-mail ;-)! EDIT: Well I’m very busy actually…

Источник

Оцените статью