Android studio json from url

Android Studio: получение JSON в ListView с сервера на хостинге. Урок № 3

Всем привет и это уже третья статья и видео, посвященные работе в Android Studio с json файлами.

Из этой статьи вы узнаете как в android studio получать данные из JSON в ListView с сервера на хостинге.

Мы всё ближе и ближе подходим к тому, чтобы наконец-то начать получать данные с сервера на хостинге, а вот сейчас мы займемся как раз разбором данного примера.

Мы загрузим наш тестовый json файл с пользователями на хостинг и будем получать данные уже непосредственно из интернета.

Надеюсь видео вам понравится, можете пока создается новый проект поставить пальцы вверх, подписаться на канал, и мы приступаем.

Смотрите видео: Android Studio: получение JSON в ListView с сервера на хостинге. Урок № 3

Создаем новый проект, выбираем emptyActivity , традиционно жмем Next, назовём новый проект Load json from url -01 , финиш.

Пока подготавливается проект, хочу сказать, что я выложил наш тестовый json файл на хостинг и буду использовать его в качестве примера. Вы можете выложить свой файл, как Вам будет удобно с вашим содержимым. Замечу, что заходить по ftp на сервер, создавать домены, поддомены, создавать директории на хостинге вы обязаны уметь.

Если мы перейдём по ссылке m1.maxfad.ru/api/users.json, то мы можем увидеть структуру файла, перечень пользователей, электронные адреса. Сейчас это всё находится уже на хостинге в интернете.

Давайте поработаем над нашим проектом, кое-что будем использовать из второго урока, код будет немного совпадать, кто не смотрел предыдущие примеры, обязательно посмотрите.

Давайте сразу через New Resource File снова сделаем row.xml , для вывода пунктов нашего списка, чуть позже вернемся к нему.

Откроем AndroidManifest.xml , в нем нужно будет указать разрешение для работы с интернетом.

Также нам понадобится gradle файл, и в него мы вставим имплементацию библиотеки, которую Вы наверное, уже знаете, может кто-то уже слышал, это volley, по крайней мере так я её произношу.

Синхронизируем gradle , произошло добавление, будем работать с этой библиотекой, она как раз используется для сетевых запросов, для получения данных с сайтов и тому подобного.

В AndroidManifest добавим пользовательское разрешение для работы с интернетом.

Хочу сделать маленькое замечание, пока мы не начали всё писать, поскольку у меня, а возможно такое будет и у вас, сертификат не распространяется на поддомены, то для того чтобы не выдавались сообщения об ошибке, Вам нужно будет включить в блок application следующюю запись.

Это вроде как позволяет работать с недостоверными, скажем так с точки зрения Google, сайтами это требование корпорации добра, для вашей безопасности. С манифестом и с gradle закончили.

Теперь перейдем в activity_main , по традиции мы снова будем делать listview , заменим на RelativeLayout , textview меняем на listview , убираем отсюда опять всё ненужное.

Так значит для listview добавим android:id listView , ширина и высота — wrap_content .

Добавим еще один элемент для отображения сетевой активности, ProgressBar ширина wrap_content , высота тоже wrap_content .

Сделаем видимость ProgressBar в

Вот теперь важное: для ProgressBar добавить нужно центрирование по горизонтали и по вертикали, чтобы элемент был по центру экрана.

Так он пока где-то находится, его не видно, можно посмотреть. он находится по центру и будет крутиться.

Перейдём в row.xml для вывода пунктов, сделаем здесь LinearLayout , ширина match_parent , а высота wrap_content , ориентация вертикальная, отступы – 16dp .

Так теперь добавим два textview , вы уже знаете какие, это у нас будут для name и email.

Добавим для видимости текст,

Так значит нам нужно будет создать новый класс для обработки. Наш класс мы назовём ListViewAdapter .

И теперь я буду вставлять куски кода, потому как мы его писали в прошлый раз, но для тех, кто не смотрел, кое-что расскажу, буду уже всё равно блоками вставать, поскольку он практически готов.

Снова напишем конструктор, в котором будем вызываться контекст, слой, которые у нас row , будем вызывать поля, в принципе можно там первое вызвать name и уже будет работать и список который будет передавать данные.

Метод super это всё вызывает, здесь присвоение переменных.

Ну и опять без изменений практически из второго видео, с некоторыми оговорками получается вот такая функция.

В getView определяем слой для вывода данных, обращаемся к элементам пункта name , email . В блоке обработки исключений try/catch циклично присваиваем текст, получая его из списка userlist .

Кто смотрел мое второе видео по json , тот знает, что это такое, в принципе больше на этом останавливаться не будем.

Теперь переходим в mainactivity и поработаем в ней. Итак, нам нужно будет объявить несколько переменных, переменная JSON_URL в которой мы будем хранить наш адрес, по которому будет лежать наш файл на сайте.

и ListView listView для списка.

Я надеюсь вы знаете как заливать файлы на хостинг, поэтому я не буду рассказывать, как мне удалось создать папку api в поддомене и положить туда файл, думаю это вам уже известно, если вы занимаетесь и обучайтесь разработке Android приложений для себя, либо по учёбе, по работе.

Читайте также:  Android передача gps координат

Сразу же мы получаем наш listView , наш список через findViewById

А вот теперь мы напишем вот такую строчку,

это по сути в onCreate больше ничего не будет. Дальше будет несколько функций, которые мы напишем в рукопашную.

И эта функция loadJSONFromURL будет вызывать наш адрес, и будем получать данные.

Далее напишем ручками Private void loadJSONFromURL , в качестве параметра Stirling передаём url .

Нужно будет обратиться к нашему элементу ProgressBar , который у нас указан в activity_main progressBar

ProgressBar надо будет сделать видимым

Теперь пишем StringRequest , обратите внимание это мы работаем с библиотекой volley ,

передаём наш url , пишем new Response.Listener

Открываем скобки пишем @Override ,

Нам нужно добавить метод onResponse , подключить сюда onResponse .

Далее делаем ProgressBar не видимым.

Всё мы его скрыли, теперь у нас идёт обработчик исключений try , пишем

и указываем нашу таблицу users , которая у нас внутри файла users.json .

Объявляем ArrayList JSONObject

и вот здесь мы напишем ту функцию, которую мы писали в прошлый раз.

В прошлый раз, я хочу напомнить, мы её вставим вне функций, мы её Встаём целиком и полностью, можете скопировать её из второго примера. Поскольку будем выполнять то же самое действие здесь.

Не буду останавливаться, но тут происходит наполнение данными из массива. Передаём jsonArray , далее пишем ListAdapter adapter

И теперь для списка установим адаптер

Блок исключений catch

Далее идет Response.ErrorListener

В нем Toast выводит ошибки. Что такое тосты уже знаете, последние две строчки данной функции

Вот теперь только вызываться наша библиотека, которая в конце концов вызовет наконец-то запрос и сформирует нужный результат.

Так, здесь я пропустил запятую после переменной url , и в принципе больше у нас ни каких нюансов быть не должно… А они будут…)

Сохраняем, запускаем… Эмулятор запустился, и мы получили данные…

Поскольку наш файл вряд ли был в кодировке UTF-8 , но здесь должен быть четко UTF-8 . Напишу для себя UTF-8 , должна быть такая кодировка, тогда у нас будут русские буквы, русский текст нормально выглядить.

Сложно догадаться, что это Коля, Вася, Федя, и тому подобное, хотя email отобразился нормально.

Значит нам нужно будет написать ещё одну небольшую функция, которая превратит наш ответ – response , превратит эту кашу в кодировку UTF-8 .

Итак давайте исправим это недоразумение, написав еще одну функцию EncodingToUTF8

В качестве параметра передаём string response , сразу try обработчик, пишем массив байт, code

Ответ в строку, получим байты в кодировке ISO-8859-1 , западноевропейская кодировка, и конвертируем в UTF-8 , перегоним нашу абракадабру в понятный вид.

После обработки ошибок Catch вернем строковое значение response.

Вот такая получилась небольшая функция в принципе когда мы перейдём наконец-то в четвёртый урок, в четвёртом занятие, мы будем получать данные уже непосредственно из PHP с базы данных на хостинге, и этот костыль не понадобится, поскольку мы обойдемся без неё, там уже будем конвертировать текст, можно в базе указать.

И давайте её вызовем EncodingToUTF8 наш response , сохраним и перезапустим.

Вот так, всего лишь одна небольшая функция и мы превратили абракадабру во вполне понятной вид.

Источник

Android JSON Parsing From Url With Volley, Retrofit And httpurlconnection

Learn today about android json parsing from URL using Retrofit,Volley and HTTP.

We will create three examples as per the below.

1. Android JSON Parsing From URL Using Retrofit

We will learn how to parse JSON from URL or Server Using Retrofit Library in android.

You will learn how to fetch/retrieve data from MySQL database in android using JSON, retrofit, and PHP.

When you want to interact with a remote server such as to get data from a server or to send data to a remote servers, you need to make HTTP calls.

Retro fit is the library which make this task easier and faster.

Check Final Texts

Below video demonstrate how the outcome of this project will look a like

Basics about Retrofit

Square have developed the retrofit library.

Retrofit is the REST client for Java and Android development.

This library makes development tasks easier to get or send the data in the JSON format.

Retrofit uses the OkHttp library for HTTP requests. It also handles the cache operations itself with any coding from app developer.

Generally, developers make custom classes to parse JsonArray or JsonObject separately.

In this tutorial, we will get the JSON response in the string format. Then we can use android’s built in classes like JSONArray and JSONObject to parse the JSON in string format.

So now follow all the below steps of this example.

Step 1. Write Retrofit Dependency

First of all, make a new project in android studio.

Write down the following two lines in the build.gradle(Module:app) file.

First line will integrate the required classes for retrofit.

Second one will get the files for scalar library.

Retrofit will help us to make http calls to the remote web server. While scalar will convert the JSON response in the string format for us.

Give Internet Permission

Add the below line in the AndroidManifest.xml file.

This line will allow our project to use the internet of the android device.

Step 2. Making Interface

For making the http call, we need to create one interface.

Make a new JAVA class and give it a name ApiInterface.java

Below is the source code for ApiInterface.java

First string variable holds the path of the URL. This variable do not include the name of the file.

I have set the file name in the @GET annotation.

Then we need to define the call function. Name of the function is getString().

Step 3. Making the Model class

Model class will help us to maintain the proper data structure.

Make a new class named RetroModel.java and copy the below source code in it

Our JSON response holds the information like name, country, city, id.

So the above class includes the getter and setter methods for all these parameters.

We will use these methods to send and receive data in the MainActivity.java file.

Step 4. Final Modifications

When you created the new project in android studio, you should have two file in the project. activity_main.xml and MainActivity.java

Читайте также:  Yandex сервисы для android

Write the below code structure in activity_main.xml file

I have written two textviews in the above file.

First textview is static and it is just saying that below information is fetched using retrofit.

Second textview will hold the JSON data. We will insert the data in this textview in Main Activity.

Code snippet for MainActivity.java file looks like the below

Reading above source code

In the onCreate() method, compiler will first get the id of the text view.

Then it will call the method getResponse().

getResponse() method looks like the following

First of all, compiler will make the object of the Retrofit class.

Here, it will bind the URL using .baseUrl() method.

Then it will create the object of the interface ApiInterface. Using this object, it will create new Callback and will run the .enqueue() method.

After this much, retrofit have make the http call to the URL and it has get the response.

Compiler will read the JSON response in the onResponse() method.

Below line will give us the JSON response in the String format.

Then compiler will call the writeTv(jsonresponse) method. Compiler will pass the string variable which holds the JSON response in the parameter of this method.

Code structure for writeTv(jsonresponse) method is as the below

For understanding above method, let us first check the JSON data which we have got.

First of all, compiler will parse the parent object from the JSON response.

Then from this parent object, it will check the value of the “status” field.

If it is true, then it will create one arraylist with objects of the RetroModel class, which we have written in the Step 3.

Now compiler will create one JSONArray which is represented by the field “data“.

After this, it will make one for loop. During every iteration of this for loop, compiler will create the object of the RetroModel class and it will set the data with this object.

Then it will add this object into the arraylist.

Now another for loop is there. In this for loop, compiler will set the data in to the text view.

2. Android JSON Parsing Using Volley

Welcome to Android JSON Parsing Using Volley From URL Example Tutorial.

We will learn how to parse JSON from URL or Server Using Volley Library.

You will learn how to fetch/retrieve data from MySQL database in android using json, volley and PHP.

When we want to interact with the remote server, we need to send and fetch data over internet.

For example, when making registration and login module, we need to send username and password to remote server when user completes sign up task.

When user wants to login again, we need to fetch those username and password from the remote server.

In this process of sending and fetching data, we have to make some bridge between android device and remote server.

This tutorial uses Volley as a bridge.

Volley will return our json text in the string format.

Final Looks of JSON Volley

Information About Volley

Volley is a networking library developed by google.

It is an HTTP library that makes networking for android apps easier and faster.

We can also use AsyncTask class for networking purpose which is in-built class for android system.

Main drawback of using AsynTask is it’s inaccuracy. Also little time consuming problem is there for this class.

Steps To Make Example

Follow all the below steps to make a sample project in android studio.

We will fetch JSON data using volley and parse this data using JSONArray and JSONObject class.

Step 1. Dependency part

All the classes of the Volley library are not included in the core android structure.

They are available on GitHub but not in local android library.

So we need to fetch the volley classes in our project using dependency concept.

Add the below line in build.gradle(Module:app) file

Above line will enable us to use volley library in our project.

Step 2. Model For Players

Now let us create a model class. This class mainly includes getter and setter methods for the various data types.

For example, we have id, name, county and city of the players.

So we will have separate getter and setter methods for all four data types.

Make a new JAVA class named PlayerModel.java

Copy the below code in PlayerModel.java

As you can see that we have required methods for all four data types in above class.

We will use getter methods to fetch the data from the JSON response.

Setter methods will help us to set the data in appropriate UI widget.

Step 3. Main Files

Ok, now last thing is to change activity_main.xml and MainActivity.java files.

Write down below code structure in activity_main.xml

I have defined two textviews in this file.

First one is just saying that compiler have fetched the below data from URL.

Second one will hold all the data from json response.

Now add the following coding lines into MainActivity.java file

Understandings Of Main Logic

Main logic and code is written in the Main Activity.

First of all, read the below lines

First line is declaring one string variable named “URLstring” . This string includes the URL from which we will fetch JSON response.

Second one is making an object of the textview where we will set the data.

requestJSON() method

in onCreate() method, I have written a requestJSON() method, which will parse the json.

Following is the coding layout for requestJSON() method

Consider the below code

Compiler will create an object of the StringRequest class.

First parameter will decide whether volley will execute GET request or POST request. Our URL do not need any URL parameter so we will execute GET request.

Second parameter includes the string variable. This string variable represents the URL which will give us JSON response.

Читайте также:  Арена героев андроид как получить персонажа

When the volley get any response from the URL, compiler will run onResponse() method.

We will receive our response via the parameter of onResponse() method.

Look at the below few starting lines of onResponse() method.

Compiler will implement try statement so that if any execution is there, we can avoid force close (app crashing) of our app.

JSON response is looking like below

Under try statement, compiler will first get the JSON Object.

then it will check the status.

If the status is true, then it will create an Arraylist with the objects of the PlayerModel class.

Then it will create a JSONArray named “data”. You can see the JSON array named “data” in above JSON response.

Now consider following code snippet

Compiler will execute one for loop.

Here, it will create an object of PlayerModel class and an object of JSONObject class.

The it will get the id, name, country and city of the players and will set them using setter methods.

After this, compiler will add the object to the arraylist.

After populating the arraylist with the data of the JSON response, compiler will execute below loop

We will write text in the textview using the above loop. It will write all the information about each player during every iteration of the loop.

3. Android httpurlconnection post JSON example

Hello, developers. Welcome to JSON Parsing Android Studio Example.

In JSON Parsing Android Studio simple example you will learn how to parse simple JSON data from URL step by step.

We will programmatically parse JSON with JSONObject and JSONArray classes in JSON Parsing In Android.

You will get the professional format to call remote Web Services in proper and easiest way at the end of JSON Parsing Android example.

You may find this JSON Parsing Android tutorial little lengthy but once you give it 10 minutes, you will be able to call all web services easily in all your future apps.

First, check the output of JSON Parsing Android tutorial and then we will create it.

JSON Data Which We Will Parse In JSON Parsing Android Tutorial

How to Parse JSON Data

JSON Parsing Android is not a very big thing.

Mainly there are only two main things in JSON data. First is JSON Object which is indicated by curly brackets .

Second is JSON Array which is indicated by square brackets [ ].

JSONObject class (Inbuilt Java Class) is used to parse JSONObject and JSONArray (Inbuilt Java Class) class is used to parse JSONArray.

We will see how to parse these two with special method later in the JSON Parsing Android tutorial. Now go to Android Studio.

Step 2: Updating AndroidManifest.xml file

add required permissions between …. tag.

Final code for AndroidManifest.xml file

Step 3: Adding common classes

We will add some common classes which contain constant variables and public methods.

We can use these variables and methods anywhere in the whole project so that it will reduce data redundancy.

Means that we will write them only once and then we can use them anytime and anywhere when needed.

Names of the classes are:

  1. AndyConstants
  2. AndyUtils
  3. HttpRequest
  4. ParseContent

Step 4: Creating AndyConstants

Create a new Java class and copy following source code

Above class contain URL constants and Parameter constants.

Step 5: Creating AndyUtils

Create a Java class named AndyUtils and add below source code

This class contains a methods to show(showSimplrProgressDialog()) and remove(removeSimpleProgressDialog()) progress dialog when app is fetching JSON data from server.

AndyUtils also includes a method (isNetworkAvailable()) to check whether the Internet of Android device is on or off.

Step 6: Preparing HttpRequest Class

Make new Java class named HttpRequest and paste following source code

We will use methods of this class to establish a connection between an Android device and web server.

Step 7: Creating ParseContent

Open new Java class and give it a name ParseContent, then Add below source code

In above source code, isSuccess(String response) method is used to check whether a status of response is true or false (see in JSON data above).

getErrorCode(String response) method is used to get the message of JSON data (see in JSON data above).

getInfo(String response) method will parse JSON data. I will describe this method later.

Step 8: Creating Model Class

We will display JSON Data in ListView, so create a new class named “PlayersModel” and add following

Step 9: Creating lv_item.xml layout file

Create a new layout resource file named lv_item.xml file and add following

Step 10: Create one class and name it: CustomeAdapter.java

Copy and paste following code in this class:

Step 11: Copy and Paste following code in activity_main.xml

Step 12: Copy following code in MainActivity.java

Step 13: Description of MainActivity.java

Look at below source code

First, we will check the internet of the device. If it is off, then give message that “Internet is required!”

If internet is on then we will call a web service to get JSON.

Following will call web service.

We will get JSON Data in String Format into variable named “response.”

These JSON Data is sent to onPostExecute(String result) method. Below is code of onPostExecute(String result).

From above method, JSON Data is sent to the onTaskCompleted() method.

JSON Parsing in android is done by getInfo() method of ParseContent class. Following is getInfo() method.

After that, we have key named “data” and its value is starting from ‘[‘ bracket which is JSONArray. It is parse by following line.

Now data array contains 8 objects so they are parsed by for loop and it is stored in instance of PlayersModel Class.

After getting playersModelArrayList from getInfo() method, listview is populated using custom adapter.

So that’s all for JSON Parsing Android Studio example, Feel free to comment on your queries and reviews. Thank you 🙂

Источник

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