한국어

Coding

온누리070 플레이스토어 다운로드
    acrobits softphone
     온누리 070 카카오 프러스 친구추가온누리 070 카카오 프러스 친구추가친추
     카카오톡 채팅 상담 카카오톡 채팅 상담카톡
    
     라인상담
     라인으로 공유

     페북공유

   ◎위챗 : speedseoul


  
     PAYPAL
     
     PRICE
     

pixel.gif

    before pay call 0088 from app


https://www.londonappdeveloper.com/consuming-a-json-rest-api-in-android/


Consuming a JSON REST API in Android

JSON REST API

This week’s blog post was requested by one of our readers, Jasmine.

Jasmine asked if I could write a guide on “processing JSON data for android applications using NodeJS and Express and Android Studio”.

I haven’t done anything using Android Studio in a while – and I love writing guides that you all want and need – so I thought I would give it a shot.

There are two parts to processing JSON data in Android using NodeJS and Express:

  1. Writing an app capable of processing the JSON data.
  2. Writing a backend capable of producing the JSON data to be processed.

Because there are two parts to this, naturally I’ve broken the steps down into two blog posts.

In the first guide – i.e. this one – l’ll walk you through step #1 and teach you how to create an Android app using Android Studio, which allows you to process JSON data from a REST API.

The next post will show you how to make a REST API using NodeJS and Express. (Check back next week, or better yet, sign up to my newsletter).

Alright, so let’s get started.

In this guide I’ll teach you how to make an Android app which uses the latest Volley HTTP library and allows you to efficiently make network requests and handle the response.

The app will have a text field where you can enter a GitHub username and a button that will retrieve a list of all public GitHub repositories for the provided username.

The repos will be listed in a text box with the name and last updated date.

Create Our App

Open up Android Studio and create a new project.

Next, fill out the new project form by entering the following:

Application Name: AndroidJsonParser

Company Domain: (Your company domain, or if you don’t have one, use example.com).

Then, click Next.

In the Target Android Devices screen, leave everything as default and click Next.

On the Add an Activity to Mobile screen, choose Empty Activity and then click Next.

On the Customize the Activity screen, leave everything as default and click Finish.

Wait a minute or two for the project to load…

Enable Volley and Internet Access

Let’s add the Volley library to our project.

In the Project Explorer, navigate to Gradle Scripts > build.gradle and add the following to the dependencies:

compile 'com.mcxiaoke.volley:library:1.0.19'

Save the file.

Then, in the Project Explorer navigate to and open app > manifests AndroidManifest.xml.

Just above the application tag, add the following line to add the INTERNET permission:

<uses-permission android:name="android.permission.INTERNET" />

Modify the Layout

Next we are going to want to add the following elements to our activity layout:

  • EditText for a GitHub username
  • Button for getting the data once the username is entered
  • TextView for showing our results

That’s the minimum required for an effective demo.

In the project explorer, navigate to app > res > layout > activity_main.xml. Once the file opens, select the Text tab at the bottom of the screen.

Now, let’s remove the existing Hello World! text view, and add the following code:

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="GitHub Username"
android:text="LondonAppDev"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/et_github_user"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:text="Get Repos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/et_github_user"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/btn_get_repos"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="getReposClicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_get_repos"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/tv_repo_list"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:scrollbars="vertical"
android:layout_alignParentEnd="true" />

Write our Java Code

Now, let’s write the logic for our app.

The first thing we’ll do is import the packages we need to make our app work.

You can actually do this as you go along, using the Alt Enter shortcut to auto-import. However, I found this didn’t work for all of the imports (some of the Volley and JSON packages I needed to import manually).

For simplicity, lets delete any existing import statements, and replace with the following (note: make sure you leave the packagedeclaration on the first line, as this will be different for each person).

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Response;
import com.android.volley.Request;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
view raw1602-imports.java hosted with ❤ by GitHub

It will look something like this

The reason some are grey is because Android Studio is letting us know which ones are unused. Don’t worry, we’ll use them later.

Now let’s add some instance variables. Instance variables are defined when we initialise our app. These variables are used in various methods later on in the code.

We define them immediately below the “Public class MainActivity…” and above the first “@Override” statement:

EditText etGitHubUser; // This will be a reference to our GitHub username input.
Button btnGetRepos; // This is a reference to the "Get Repos" button.
TextView tvRepoList; // This will reference our repo list text box.
RequestQueue requestQueue; // This is our requests queue to process our HTTP requests.
String baseUrl = "https://api.github.com/users/"; // This is the API base URL (GitHub API)
String url; // This will hold the full URL which will include the username entered in the etGitHubUser.

So our code now looks like this:

Getting there…

Next, let’s update our “onCreate” to register our views and setup our queue. As the name suggests, “onCreate()” is the function that is created when our Android Activity (the screen in-front of our code) is created.

We need to link the view elements we created earlier (the text input, button and text output) with the instance variables we defined above, so we can use them in our code.

Update the onCreate method to look like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // This is some magic for Android to load a previously saved state for when you are switching between actvities.
setContentView(R.layout.activity_main); // This links our code to our layout which we defined earlier.
this.etGitHubUser = (EditText) findViewById(R.id.et_github_user); // Link our github user text box.
this.btnGetRepos = (Button) findViewById(R.id.btn_get_repos); // Link our clicky button.
this.tvRepoList = (TextView) findViewById(R.id.tv_repo_list); // Link our repository list text output box.
this.tvRepoList.setMovementMethod(new ScrollingMovementMethod()); // This makes our text box scrollable, for those big GitHub contributors with lots of repos :)
requestQueue = Volley.newRequestQueue(this); // This setups up a new request queue which we will need to make HTTP requests.
}

So now our code looks like this:

Next, let’s add some helper functions to our code.

I described what each function does in the comments block.

Insert the following below the onCreate() block which we just updated (below the end bracket):

private void clearRepoList() {
// This will clear the repo list (set it as a blank string).
this.tvRepoList.setText("");
}
private void addToRepoList(String repoName, String lastUpdated) {
// This will add a new repo to our list.
// It combines the repoName and lastUpdated strings together.
// And then adds them followed by a new line (\n\n make two new lines).
String strRow = repoName + " / " + lastUpdated;
String currentText = tvRepoList.getText().toString();
this.tvRepoList.setText(currentText + "\n\n" + strRow);
}
private void setRepoListText(String str) {
// This is used for setting the text of our repo list box to a specific string.
// We will use this to write a "No repos found" message if the user doens't have any.
this.tvRepoList.setText(str);
}

So the code will look something like this:

Alright, so this is the part where we make our HTTP request.

Insert this code underneath our last function (setRepoListText). This code might look confusing but it’s actually quite simple. I’ve described what each section does in the inline comments. If you want to gain a more in-depth understanding, I highly recommend you read the official guide Transmitting Network Data Using Volley.

private void getRepoList(String username) {
// First, we insert the username into the repo url.
// The repo url is defined in GitHubs API docs (https://developer.github.com/v3/repos/).
this.url = this.baseUrl + username + "/repos";
// Next, we create a new JsonArrayRequest. This will use Volley to make a HTTP request
// that expects a JSON Array Response.
// To fully understand this, I'd recommend readng the office docs: https://developer.android.com/training/volley/index.html
JsonArrayRequest arrReq = new JsonArrayRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// Check the length of our response (to see if the user has any repos)
if (response.length() > 0) {
// The user does have repos, so let's loop through them all.
for (int i = 0; i < response.length(); i++) {
try {
// For each repo, add a new line to our repo list.
JSONObject jsonObj = response.getJSONObject(i);
String repoName = jsonObj.get("name").toString();
String lastUpdated = jsonObj.get("updated_at").toString();
addToRepoList(repoName, lastUpdated);
} catch (JSONException e) {
// If there is an error then output this to the logs.
Log.e("Volley", "Invalid JSON Object.");
}
}
} else {
// The user didn't have any repos.
setRepoListText("No repos found.");
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// If there a HTTP error then add a note to our repo list.
setRepoListText("Error while calling REST API");
Log.e("Volley", error.toString());
}
}
);
// Add the request we just defined to our request queue.
// The request queue will automatically handle the request as soon as it can.
requestQueue.add(arrReq);
}

Now our code looks like this:

One final code change to make. You may have noticed above that in our Layout Snippet we added the following on line 25:

android:onClick="getReposClicked"

This basically tells Android that when the user clicks that button, call the getReposClicked() function in our app.

So the last step is to define this function.

Add this code below the Volley function we just added:

public void getReposClicked(View v) {
// Clear the repo list (so we have a fresh screen to add to)
clearRepoList();
// Call our getRepoList() function that is defined above and pass in the
// text which has been entered into the etGitHubUser text input field.
getRepoList(etGitHubUser.getText().toString());
}

Now the code looks like this:

Alright, the code is complete!

Test Our App

Finally, let’s test our app.

At the top of Android Studio, click on the play button:

In the Select Deployment Target screen, choose either a Connected Device (if you have a real Android Device that you use to test your apps on), or a device under Available Virtual Devices.

If you don’t already have a device setup, then you can click on Create New Virtual Device and follow the steps on-screen to create a new one.

Alright, once that’s done, your app should load on the selected target.

Test it out! Enter your GitHub username and watch it retrieve a list of all your GitHub repos right before your eyes.

I hope this helped Jasmine?

If you have any questions, feedback, or want me to cover a specific topic, please let me know in the comments below!

Cheers
Mark

5REPLIES
  1. elegantuniverse
    elegantuniversesays:

    hello
    thank u for your useful tutorial
    i have problem with compiling volley

    compile ‘com.mcxiaoke.volley:library:1.0.19’
    and i added this
    compile ‘com.android.volley:volley:1.0.0’
    and the error solved
    but when I want to run the project 2 errors appear as below:

    Error:(75, 35) error: no suitable constructor found for JsonArrayRequest(int,String,<anonymous Listener>,)
    constructor JsonArrayRequest.JsonArrayRequest(String,Listener,ErrorListener) is not applicable
    (actual and formal argument lists differ in length)
    constructor JsonArrayRequest.JsonArrayRequest(int,String,JSONArray,Listener,ErrorListener) is not applicable
    (actual and formal argument lists differ in length)

    what should i do?

    Reply
  2. elegantuniverse
    elegantuniversesays:

    hello
    thank u for your useful tutorial
    i had problem with compiling volley

    compile ‘com.mcxiaoke.volley:library:1.0.19’
    and i added this
    compile ‘com.android.volley:volley:1.0.0’
    compile ‘com.mcxiaoke.volley:library:1.0.19’
    and the error solved
    but when I want to run the project 2 errors appear as below:
    error1:
    Error:(75, 35) error: no suitable constructor found for JsonArrayRequest(int,String,<anonymous Listener>,)
    constructor JsonArrayRequest.JsonArrayRequest(String,Listener,ErrorListener) is not applicable
    (actual and formal argument lists differ in length)
    constructor JsonArrayRequest.JsonArrayRequest(int,String,JSONArray,Listener,ErrorListener) is not applicable
    (actual and formal argument lists differ in length)
    error2:
    Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
    > Compilation failed; see the compiler error output for details.
    what should i do?

    Reply

Leave a Reply

Want to join the discussion? 
Feel free to contribute!

번호
제목
글쓴이
66 JavaScript & Node.js node 웹서버 구현 강의 설명 매우 잘됨 가장중요한 내용
admin
9175   2019-11-20
 
65 Node.js 익스프레스 웹 서버 Express-generator로 빠르게 설치하기
admin
8542   2019-11-17
 
64 [Express.js] Express 로 웹 애플리케이션 만들기 express 사용법
admin
8510   2019-11-17
 
63 [node.js] express, 웹서버 구축, 설계, 제작
admin
8915   2019-11-17
 
62 npm init 초기화
admin
14017   2019-11-17
 
61 Node.JS vhost 사용 설명
admin
9168   2019-05-31
 
60 How to build scalable node js and express website rest api
admin
8531   2019-05-31
 
59 Hosting multiple websites using NodeJS and Express 멀티 도메인 호스팅
admin
8704   2019-05-31
 
58 Node.js SSL / TLS 인증서 갱신 실제 적용 방법 초간단 설명 재발급
admin
9085   2019-05-26
 
57 node js 와 Jade 를 이용한 Database 를 홈페이지에 출력
admin
10922   2018-06-23
 
56 node.js로 서버를 구축하고 mysql을 데이터 베이스로 회원가입과 로그인 기능을 구현
admin
18061   2018-06-23
 
55 [Node.js] JWT(JSON Web Token)로 로그인 REST API 만들기 총 정리
admin
13319   2018-06-14
 
54 webstorm The smartest JavaScript IDE
admin
10482   2018-06-02
 
53 Node js 보안 Express
admin
14415   2018-05-07
 
52 안드로이드 배우기: REST API 사용하기
admin
16732   2018-05-06
 
51 Getting Started with REST: Consuming simple REST APIs in Android
admin
10851   2018-05-06
 
50 Android - JSON Parser JSONArray,JSONObject,JSONStringer JSONTokenizer
admin
11113   2018-05-02
 
49 GET & POST Requests in Node.js Using Express-4
admin
11427   2018-04-30
 
48 Writing middleware for use in Express apps
admin
10514   2018-04-29
 
47 Use ExpressJS to Get URL and POST Parameters
admin
10787   2018-04-29
 
46 body-parser Learn about the anatomy of an HTTP transaction in Node.js
admin
10922   2018-04-29
 
45 How to handle the POST request body in Node.js without using a framework
admin
10903   2018-04-29
 
44 How can I read the data received in application/x-www-form-urlencoded format on Node server?
admin
11975   2018-04-29
 
43 postman google
admin
10157   2018-04-29
 
42 How to set custom favicon in Express?
admin
16159   2018-04-29
 
41 serve-favicon install and how to
admin
11032   2018-04-29
 
40 'Express' is not recognized command (windows) 기초
admin
11007   2018-04-28
 
39 AWS 람다로 서버 없이 간단한 REST API 만들기
admin
16870   2018-04-15
 
38 Android Login Registration System with PHP and MySQL (Updated) – Reset Password #3
admin
15651   2018-04-14
 
37 Android Login Registration System with PHP and MySQL (Updated) – Client #2
admin
13846   2018-04-14
 
36 Android Login Registration System with PHP and MySQL (Updated) – Server #1
admin
19583   2018-04-14
 
35 Working with JSON in MySQL perfect
admin
10023   2018-04-14
 
34 MySQL Data Access API Development Using Express.JS, Node.JS
admin
10267   2018-04-14
 
33 How to connect to a MySQL database with Node.js
admin
10775   2018-04-14
 
Consuming a JSON REST API in Android
admin
10786   2018-04-14
https://www.londonappdeveloper.com/consuming-a-json-rest-api-in-android/ Consuming a JSON REST API in Android February 24, 2017/5 Comments/in Android, Android Studio /by mark This week’s blog post was request...  
31 NODE.JS REST API
admin
10298   2018-04-14
 
30 NODE.JS DATABASE MYSQL TUTORIAL
admin
12732   2018-04-14
 
29 How can I send a post request with JSON from Android to a Node.js server?
admin
10111   2018-04-14
 
28 How do I send data to a Node.js server from an Android app?
admin
10408   2018-04-14
 
27 Android User Registration and Login with Node.js and MongoDB – Server #1
admin
14352   2018-04-14
 
26 Node.js Parse JSON Little information to use JSON Data
admin
10890   2018-04-14
 
25 Build a REST API for Your Mobile Apps using Node.js
admin
10034   2018-04-14
 
24 Android Asynchronous Http Client A Callback-Based Http Client Library for Android
admin
15604   2018-04-14
 
23 RESTful Api using node.js,Express and Mysql
admin
10330   2018-04-14
 
22 노드에서 MySQL을 사용하는 방법 MySQL with Node.js and the mysql JavaScript Client
admin
17114   2018-04-14
 
21 Check that you have node and npm installed
admin
9788   2018-01-16
 
20 mongodb 설치
admin
9846   2018-01-15
 
19 node js 설치 install 리눅스 데비안
admin
10545   2018-01-15
 
18 nodejs windows 윈도우 노드 제이에스 설치 다운로드
admin
10611   2018-01-15
 
17 Node.js paypal PayPal-node-SDK 사용해보자 상세한설명 연습 사례
admin
9967   2018-01-15
 
16 Simple, unobtrusive authentication for Node.js passport facebook twitter gmail etc
admin
9834   2018-01-07
 
15 Your first Node.js HTTP server [ this chapter ]
admin
9874   2018-01-07
 
14 NodeJS - Setup a Simple HTTP Server Local Web Server
admin
10175   2018-01-07
 
13 NodeJS를 이용한 API 서버만들기 3 자세한 설명 잘됨 매우 좋음 기초 노드
admin
11636   2017-12-24
 
12 JSON. Using the JSONObject in android and java.
admin
10086   2017-12-24
 
11 Android PHP MySQL 데이터베이스에서 데이터를 JSON 형식으로 가져오기
admin
23038   2017-12-24
 
10 Android에서 REST 요청 후 JSON 응답 받기
admin
12226   2017-12-24
 
9 Node.js를 이용하여 MySQL 데이터 가져오기
admin
23627   2017-12-24
 
8 Node.js - mysql 연결
admin
11829   2017-12-24
 
7 RESTful Api using node.js,Express and Mysql
admin
10725   2017-12-24
 
6 Using MySQL with Node.js & the mysql JavaScript Client 매우 설명 잘됨 공부 좋음
admin
22228   2017-12-24
 
5 Android Login Registration System with Node.js and MongoDB – Server #1
admin
31278   2017-12-24
 
4 How to Setup Node.js and MongoDB in Ubuntu and Windows
admin
11070   2017-12-24
 
3 Build a REST API for Your Mobile Apps using Node.js
admin
10711   2017-12-24
 
2 MySQL version 5.7.8 introduces a JSON data type
admin
10065   2017-12-24
 
1 Best Practices|| 128- Connect Android to MYSQL use Node.JS
admin
9607   2017-12-24