- Подключаем Git к Android Studio
- Дополнительные статьи
- Работа с Github
- How to link Android Studio with Github
- How to use GitHub with Android Studio
- Requirements
- Selecting project
- What to contribute
- Cloning the repository
- Making the change
- Forking the repository
- Committing and pushing the change
- Creating the pull request
- Wrapping up
Подключаем Git к Android Studio
Android Studio умеет работать с системами контроля версий (version control system, сокр.VCS). Самой популярной системой является Git, которая стала практически стандартом во многих языках программирования.
Сама по себе Git управляется через командную строку. Для изучения её возможностей есть множество документации. Мы сфокусируемся на подключении Git к проекту в Android Studio.
Чтобы лучше понять объяснения, откройте старый проект Hello Kitty или создайте его заново, если успели его удалить.
Для начала нужно установить Git. Перейдите на страницу загрузки http://git-scm.com/downloads и скачайте последнюю версию под вашу операционную систему.
Запускаем процесс инсталяции. Не рекомендую устанавливать в папку по умолчанию в системной папке Windows C:\Program Files, так как из-за пробела между словами часто возникают проблемы у многих пользователей при работе с командной строкой. Я установил в папке D:\Git. Желательно также прописать путь к папке D:\Git\bin\ в переменной окружения PATH.
Запускаем файл git-bash.exe для запуска консоли. Следует сконфигурировать Git, указав своё имя и электронный адрес, чтобы можно было установить авторство изменений в коде. Вводим по очереди две команды:
Возвращаемся в студию. Выбираем в меню File | Settings и в диалоговом окне в левой части выбираем секцию Version Control | Git. Нажимаем кнопку с многоточием и находим нужный файл на диске.
Для проверки можно щёлкнуть по кнопке Test, вы должны увидеть радостное сообщение в успешном случае. Закрываем окно настроек, применив изменения.
Данная настройка запоминается и в новых проектах этот шаг можно пропустить.
Далее идём в меню VCS | Import into Version Control | Create Git Repository и в диалоговом окне выбираем корневую папку проекта. Для удобства можно сразу нажать на значок студии (третий слева), чтобы сразу переместиться в корневую папку, если окно откроется с другой папкой.
Нажимаем кнопку OK и создаём локальный Git-репозиторий. Под капотом выполняется команда git init.
Как только вы это сделаете, в студии произойдут удивительные изменения. Многие имена файлов в левой панели окрасятся в коричневый цвет.
Коричневый цвет шрифта означает, что файл распознан системой контроля версий на локальном компьютере, но ещё не добавлен в репозиторий. Нам следует подсказать системе об этом.
Но не будем торопиться. При создании локального репозитория студия также создала несколько специальных файлов .gitignore, которые помогают системе контроля версий игнорировать некоторые файлы проекта при изменениях. Один такой файл вы можете найти в корневой папке проекта, а второй в папке app. Можете открыть их любым текстовым редактором. Начнём с файла из корневой папки.
Как видим, Git будет игнорировать файл .idea/workspace.xml, который относится к конфигурации самой студии на вашем компьютере и к самому проекту не имеет отношения. Аналогично будет проигнорирован файл local.properties, который является уникальным для каждого компьютера. Можно указывать не только отдельные файлы, но и папки. Например, в списке присутствует папка /build. В эту папку попадают файлы при компиляции. Их нет смысла отслеживать, так как они постоянно меняются, когда вы запускаете приложение для проверки. Все файлы, которые должны быть проигнорированы, выводятся обычным чёрным цветом. Обратите внимание на имя файла local.properties на скриншоте выше.
Кроме чёрного и коричневого цвета, имена файлов могут также выводиться синим цветом (файл изменён), зелёным (новый файл).
При подключении Git в нижней части студии появится новая вкладка Version Control. Откройте её. Сейчас вы видите две секции: Default и Unversioned Files. Секция Default сейчас пуста. При изменении или создании новых файлов они попадут в эту секцию. Секция Unversioned Files содержит файлы, которые ещё не были учтены системой контроля версий.
При создании нового проекта файлы автоматически не учитываются и находятся в секции Unversioned Files. Мы хотим их перенести в репозиторий. В левой части панели находятся две колонки со значками. Найдите значок с изображением папки в скобках (при подведении курсора появится подсказка Group by Directory) и нажмите на неё. Файлы будут сгруппированы, как в проекте. Так проще вам будет понять структуру.
Щёлкаем правой кнопкой мыши на Unversioned Files и выбираем в контекстном меню Add to VCS. Либо можно перетащить мышкой эту секцию на секцию Default. В результате все файлы переместятся и будут учтены системой контроля версий.
После добавления файлов нажмите на значок с зелёной стрелкой вверх и надписью VCS (Commit Changes). Откроется диалоговое окно. В текстовом поле Commit Message введите текст, поясняющий изменения в проекте и нажмите кнопку Commit.
Файлы исчезнут из секции Default и теперь находятся под контролем Git. При изменении файл снова попадёт в данную секцию и вам снова нужно выполнить предыдущую операцию Commit.
Например, откроем файл манифеста и добавим разрешение на работу с интернетом. Файл окрасится в синий цвет. Комментируем изменения в проекте, добавив сообщение Добавлено разрешение на интернет.
Просматривать изменения можно на вкладке Log. Вы можете просматривать коммиты и ветки.
Таким образом мы познакомились с базовыми приёмами работы с Git.
Также вы можете создавать новые ветки, сливать их в одну и выполнять прочие операции.
Естественно, вы можете также выкладывать проект на GitHub или наоборот вносить изменения в локальный проект из удалённого репозитория.
Источник
Дополнительные статьи
Работа с Github
Github представляет популярный репозиторий проектов, который упрощает ведение командной работы над одним проектом, а также позволяет отслеживать все сделанные в нем изменения.
Для работы прежде всего необходимо создать учетную запись на сайте https://github.com. Также для работы необходимо установить инструментарий git, установщики которого для различных ОС можно найти на сайте https://git-scm.com/
Возьмем какой-нибудь проект. В Android Studio перейдем к пункту меню VCS -> Import into Version Control -> Share Project on Github .
Далее надо будет ввести логин и пароль от учетной записи на github.com:
Затем будет предложено ввести дополнительный пароль (Master password):
Если подобного пароля не указывалось ранее, оставим это полу пустым и нажмем OK.
Далее будет предложено указать имя репозитория, удаленное имя и описание:
Описание лучше писать на английском. После ввода всех данных нажмем на кнопку Share.
После этого будет предложено указать те файлы проекта, которые мы хотим закинуть на github:
После удачного экспорта файлов в Android Studio отобразится соответствующее сообщение.
Итак, наш проект уже расположен на github, однако впоследствии мы можем произвести в нем изменения, например, добавить файлы кода, изменить какой-то код. И в этом случае нам надо будет обновить проект в репозитории. Для этого перейдем к пункту меню VCS -> Commit Changes. :
После этого отобразится окошко со сделанными изменениями со времени последнего коммита. В поле Commit Message укажем хаактер сделанных изменений. Для завершения обновления нажмем внизу окошка на кнопку Commit and Push. :
Затем отобразиться дополнительное окошко, где надо подтвердить коммит. Для этого нажмем на кнопку Push :
Источник
How to link Android Studio with Github
This article is for github beginners or for those who find it difficult to upload android projects on github.
Visit this official site to download git on your computer. Once you do that, you can start using it with android studio.
2. Enable Version Control Integration on android studio
> On doing this,you will notice that all your files will turn red.
Now ,go to VCS>Import into Version Control>Share project on Github
Now give a name to your repository and write a description if you want.
4. Push your project files on Github
Now select the files you want to share and press Ok . You can also write a specific commit message and after you do so,all your files will turn white.
Your project is now under version control and shared on Github ,you can start making changes to commit and push. You can see I added a new ImageView reference to the MainActivity.java . Notice that after I made the change, the MainActivity.java file turned blue. That means the file now has uncommitted changes (and it doesn’t match the file in the Github repository).
Its upto you now when you want to do commit and push. You can do it after every new change or after a lot of changes.
To commit and push,go to Menu>VCS(with green up arrow)
After that,you will see a commit changes window and you have to write a commit message (mandatory) and then press on commit and push.
After that,you will see another push window. Just press on push button and all your changes will be reflected in you repository.
Congratulations on setting up your first project with version control . Yayyyyy.
I am a recipitentof Udacity’s Google India challenge scholarship and I wrote this article to help my peers. Do clap if you find this useful.
Источник
How to use GitHub with Android Studio
Table of Contents
What to contribute
Cloning the repository
Making the change
Forking the repository
Committing and pushing the change
Creating the pull request
• over 1 year ago
Android Studio makes it easy to push changes to your favorite Open Source, professional, or personal projects on GitHub. In this tutorial, we’ll learn how to use GitHub with Android Studio. We’ll use an Open Source contribution for context.
Android developers use Open Source projects to speed up development or enable functionality that is otherwise impractical to build. Therefore it’s essential to understand how to give back and improve the Open Source projects that we use.
Requirements
Selecting project
First of all, to which Open Source project should you contribute? You can contribute to any project, but, ideally, it’s one that you know and use.
What to contribute
Sometimes, during the usage of an Open Source library, we encounter bugs that we wish were fixed and missing features that we want added. When that happens, it’s tempting to request it to the maintainer(s) and hope for the best, or even search for another library. However, it’s essential first to consider contributing with that bug fix or feature we want. It’s often not as complicated as we may think.
Alternatively, we may want to contribute to the project in general and select a request that’s made by the community. In this case, the best way to find an idea is to look through the issues list and select an issue that seems simple enough for a first contribution.
For this tutorial, I’ll fix a bug that I encountered while testing the sample app. In this case, the sample app crashed when pressing an image inside the chat, instead of showing it in full screen.
Cloning the repository
With Android Studio, you don’t need to use the terminal to contribute to an Android project on GitHub. It has native integration with git and GitHub to allow most actions via the Android Studio UI.
When you open Android Studio, it offers the option to open a project from version control. That’s the option we’ll use.
After selecting that option, you can type the URL of the repository, press «Clone», and select a folder. After that, Android Studio will do all the work and open the project ready to go.
Making the change
Initially, the default branch will be selected, but often projects have a development branch that receives the changes before merging them to master. Let’s create a branch for our change based on that development branch. That is a better practice than using the development branch directly, to not risk polluting it.
To do that, click where it says «Git: [default branch]», select the development branch, click «New Branch from Selected», and choose a name for your branch.
After that, we can proceed with making the change we want. After debugging the project, I’ve identified that initializing Facebook’s Fresco library in the MessageListView class solves the issue.
Now that we fixed the issue, we’re ready to commit it and send a Pull Request to the main GitHub repository. The next step will show how to fork the repository, in case you don’t have permission to push a branch to the main repository, which is often the case if you’re not a maintainer of that project.
Forking the repository
If you’re not a maintainer of that repository, you can’t push your branch to it. You’ll need to fork it first and push the branch to your fork. To do this, go to the GitHub repository and press fork.
You’ll need the URL of your repository in the next step, as we’ll push the branch to it.
Committing and pushing the change
Now, we can commit our change. To do this, either press CMD+K (or CTRL+K on Windows), or navigate to Commit via the menu.
Review your changes in the screen provided, write a descriptive commit message, press the arrow on the «Commit» button, and select «Commit and push». That will take you to the screen where you’ll choose which repository the branch will be uploaded. If you’re a maintainer of the origin remote, you can press «Push» and skip to «Creating the pull request».
If you’re not a maintainer, you should press the «origin» label, which will allow you to define a new remote repository. After that, you still need to select the proper remote and press the «Push» button.
If you’re not yet authenticated, Android Studio will ask for your GitHub credentials.
After you authenticate, Android Studio will send the changes to your remote repository.
Creating the pull request
Now, go to your repository page on GitHub, and you’ll see a prompt to open a Pull Request with your newly pushed branch.
When you press that, it will take you to a Pull Request composer. Generally, it will already contain a template that you can follow to describe your PR and some instructions that you need to follow. Also, don’t forget to check out the contribution guidelines of the project if it has one.
Usually, GitHub will pick the master branch as a base, so don’t forget to switch it to the development branch, if it exists, as the image shows.
Wrapping up
Congratulations! You just learned how to contribute to an Open Source project using GitHub and Android Studio, without having to touch the command-line interface. After you’ve sent your Pull Request, the project’s maintainers will review it and ask for changes if needed, in which case you can follow the «Committing and pushing the change» step again.
At Stream, we have many Open Source Android projects in Kotlin and Java, and we’re happy to receive and help you with your contributions.
Источник