Android RecyclerView JSON Parsing using Retrofit

recyclerView

Dans nos précédents tutoriels nous avons appris à mettre en œuvre un RecyclerView simple et l’image de chargement dans RecyclerView utilisant Picasso . Dans ce tutoriel, nous allons apprendre comment analyser les données JSON d’ URL et de l’afficher dans RecyclerView en utilisant Rénovation. Nous analysons le JSON. réponse de l’URL http://api.learn2crack.com/android/jsonandroid.
Take a look at my previous RecyclerView tutorials for reference
Jetez un oeil à mes tutoriels RecyclerView précédentes pour référence

Retrofit est une bibliothèque de client HTTP par Square Inc. Il rend en réseau plus facile et aussi facile à mettre en œuvre .

Ici, je l’ai créé un projet Android Studio avec package com.learn2crack.recyclerjsonparsing également Activity as MainActivity et mise en page comme activity_main .

 

 

La dépendance pour Rénovation est

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'

Ensuite, nous devons ajouter la bibliothèque convertisseur Rénovation GSON . Cela prend en charge la sérialisation ( Convertis objets Java en JSON et vice versa )

compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'

Les autres dépendances dont nous avons besoin

compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.android.support:cardview-v7:23.2.0'
La complète build.gradle
apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultConfig {
        applicationId "com.learn2crack.recyclerjsonparsing"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:recyclerview-v7:23.2.0'
    compile 'com.android.support:cardview-v7:23.2.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
}

Nous avons besoin d’ajouter la permission d’ Internet dans notre AndroidManifest.xml

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

Mise en page Création

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.learn2crack.recyclerjsonparsing.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/card_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
La disposition suivante est pour la liste RecylerView article . Il dispose de trois widgets TextView à afficher Android nom de la version , le numéro de version et le niveau de l’API
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    card_view:cardCornerRadius="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_name"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="18sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"/>
        <TextView
            android:id="@+id/tv_version"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/tv_api_level"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</android.support.v7.widget.CardView>

Now we create AndroidVersion model class to store Android version name, version number and API level. We obtain a array of JSON objects similar to,

Maintenant, nous créons AndroidVersion classe modèle pour stocker Android nom de la version , le numéro de version et le niveau de l’API . Nous obtenons une gamme de JSON objets semblables,

{
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
}

This AndroidVersion model class stores the JSON object. The variable declaration name should be same as JSON object name. In the above JSON response, for JSON object name “ver” the variable name should be defined as “ver” ,

privateString ver;

The Retrofit GSON converter takes care of converting the JSON objects and store it in our model class.Then generate getter methods.

package com.ndesostyle.recyclerjsonparsing;
public class AndroidVersion {
    private String ver;
    private String name;
    private String api;
    public String getVer() {
        return ver;
    }
    public String getName() {
        return name;
    }
    public String getApi() {
        return api;
    }
}

Then we need to create a JSONResponse model. The JSON response has a only JSON object “android” with child JSON array. This child JSON array can be stored in AndroidVersion model class. In our JSONResponse model class create a AndroidVersion array variable named “android” and generate getter.

packagecom.ndesostyle.recyclerjsonparsing;
publicclassJSONResponse {
    privateAndroidVersion[] android;
    publicAndroidVersion[] getAndroid() {
        returnandroid;
    }
}

We need to create a Interface and define the Request endpoints. Here we use GET request to obtain JSON data. The endpoint is defined using @GET annotation. Our request URL is http://api.learn2crack.com/android/jsonandroid, wherehttp://api.learn2crack.com is base url and android/jsonandroid is endpoint.

For our request method getJSON() the JSONResponse object is wrapped in Call object. By using Call, the request is made Asynchronous so you need not worry about UI blocking or AsyncTask. The JSON response received after making the request it is stored in JSONResponse object.

package com.ndesostyle.recyclerjsonparsing;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
    @GET("android/jsonandroid")
    Call<JSONResponse> getJSON();
}

Creating Adapter

We are using the adapter similar to the one we used in our previous projects. We pass Androidversion model class as ArrayList in constructor. We obtain the Android version name, version number, API level from the AndroidVersion object using the getter methods and set it to TextView widgets.

package com.ndesostyle.recyclerjsonparsing;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
    private ArrayList<AndroidVersion> android;
    public DataAdapter(ArrayList<AndroidVersion> android) {
        this.android = android;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
        viewHolder.tv_name.setText(android.get(i).getName());
        viewHolder.tv_version.setText(android.get(i).getVer());
        viewHolder.tv_api_level.setText(android.get(i).getApi());
    }
    @Override
    public int getItemCount() {
        return android.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_name,tv_version,tv_api_level;
        public ViewHolder(View view) {
            super(view);
            tv_name = (TextView)view.findViewById(R.id.tv_name);
            tv_version = (TextView)view.findViewById(R.id.tv_version);
            tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
        }
    }
}

Creating Activity

The views are initialized in initViews() method. In the loadJSON() method we initialize Retrofit and carry out network operations. The Retrofit is defined using,

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.learn2crack.com")
.addConverterFactory(GsonConverterFactory.create())
.build();

RequestInterface object is created using

RequestInterface request = retrofit.create(RequestInterface.class);

To carry out a asyncronous request Call object should be created from RequestInterface object by calling getJSON() method.

Call<JSONResponse> call = request.getJSON();

The Asyncronous request is executed by calling enqueue() method on the call object. If the request is success and response is received onResponse() callback method is executed. The JSONResponse object is obtained by calling body() method on the Response object. From the JSONResponse object we obtain the AndroidVersion array object. We convert theAndroidVersion array object to ArrayList. Finally a new DataAdapter object is created and set to RecyclerView usingsetAdapter() method.

If the request fails onFailure() is executed.

package com.ndesostyle.recyclerjsonparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ArrayList<AndroidVersion> data;
    private DataAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    private void initViews(){
        recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
    }
    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.learn2crack.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
                JSONResponse jsonResponse = response.body();
                data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
                adapter = new DataAdapter(data);
                recyclerView.setAdapter(adapter);
            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }
}

Kursus Android di Jakarta

Buka Kelas Berseri : Kelas Kursus Berseri Android Di DKI Jakarta (Jakarta Selatan)

  1. Pengenalan Pemrograman Android dengan Android Studio

http://kelas.ruangguru.com/pengenalan-pemrograman-android-dengan-android-studio

2. Pemrograman User interface (UI) Android untuk pemula berbasis Android studio

http://kelas.ruangguru.com/pemrograman-user-interface-ui-android-untuk-pemula

course-android-studio-peduli-syambelajar-sekaligus-beramal

 

 

 

 

 

 

 

 

 

 

 

ruangguru pemrograman-android

 

 

 

 

 

 

 

 

kelas android kelas kelompok android

Import google play service library di eclipse

biasa nya file game/aplikasi anda yang anda dapatkan disertai : google play service library di dalamnya (berupa folder) import library

import folder code tersebut ( google-play-service_lib) import sekali saja seumur hidup.

import_code

selanjutnya browse folder : google play service library

import google play library

 

jangan lupa checklist  -> copy project into workspace-> centang ->lalu finish.

jika sudah terinstall, maka penampilannya seperti gambar di bawah ini.

library instal

 

Instalasi PATH JAVA di Windows

Instalasi PATH JAVA di Windows

computer ->control panel -> advanced system setting -> advenced -> PILIH Environments variable

variable name: CLASSPATH

variable value: C:\Program Files\Java\jdk1.8.0_60\lib\tools.jar;,

variable name: HOME

variable value: C:\Program Files\Java\jdk1.8.0_60;,

variable name: PATH

variable value: C:\Program Files\Java\jdk1.8.0_60\bin;,

PATH java

 

Belajar Android developer di jakarta

BELAJAR sambil AMAL, Programer juga manusia butuh silaturahmi dan Amal baik

acara sebelumnya: https://ndesostyle.wordpress.com/2015/11/08/belajar-android-sekaligus-amal/

Acara silaturahmi sekaligus belajar android  yang bertemakan “peduli kemanusiaan palestina dan suriah” ya memang tidak banyak yang kami berikan, hanya ingin menjadikan momen ini sebagai PENGINGAT bahwasanya ada yang lebih sengsara dari pada kita, red’ mungkin diantara kita masih ada yang masih mencari kerja, atau juga ingin tahu (belajar-belajar) yaa’ gak terlalu formil juga sih belajar nya. dari kegiatan yang kita laksanakan juga adanya infak yang secara terus menerus kita gelontorkan ke mereka yg lebih membutuhkan..ya tidak banyak memang yg bisa kita kumpulkan, hanya sekedar nya mungkin kita bisa bantu untuk mereka..

konfigurasi sdk manager

yang masih kuliah ada yang masih cari kerja, bisa gabung ke kita, ingat ada INFAK nya, waktunya juga biasanya weekend, tidak setiap weekend, nanti dijadwalkan berhubung tempat juga terbatas..

kelas android

Di acara ini ada 2 manfaat yang kita berikan: Ada kontribusi uang yang bisa kita berikan kepada mereka (korban pembantain rezim di suriah) sangat tragis memenag, mereka dibunuh di negerinya sendiri oleh orang2 di negeri2 nya, untuk Indonesia sudah merdeka,. ada rasa syukur lah kita bisa hidup damai. yang kedua ada ilmu yang bisa kita berikan ke temen2 untuk bekal kerja atau sekedar pengen tahu bagaimana belajar pemrograman android.

android layer activity

 

android studio architecture

 

kursus kilat lanjutan dari kursus kilat sebelumnya Memulai Pemrograman Android dengan Android Studio:

android list view 2 android list view autocomplete android list view