You are on page 1of 42

or this retrofit android demonstration, I have my web api ready. It is actually a simple json.

http://simplifiedcoding.16mb.com/RetrofitExample/books.json

If we will go to the above URL we will get the following json string.

books json

1 [

2 {

3 "bookId":"1",

4 "name":"Harry Potter and The Prisoner of Azkaban",

5 "price":"INR 700.00",

6 "inStock":"52"

7 },

9 {

1 "bookId":"2",

0 "name":"Hamlet",

1 "price":"INR 1700.00",

1 "inStock":"47"

1 },

1 {

3 "bookId":"3",

1 "name":"Willy Wonka and His Chocolate Factory",

4 "price":"INR 500.00",

1 "inStock":"48"

5 },

1
6

2 {

2 "bookId":"4",

2 "name":"Before I Fall",

3 "price":"INR 750.00",

2 "inStock":"49"

4 }

5
]
2

0
As you can see it is a JSON Array having some details of books. We will fetch this data to our
android app using retrofit android library. So lets create a new android project.

Retrofit Android Tutorial


Adding dependencies and Creating Layout

Create a new Android Studio project and add the following to you dependencies (in
build.gradle)

adding retrofit

1 compile 'com.squareup.retrofit:retrofit:1.9.0'

Now because we will be doing a networking operation we need internet permission. So


add it to your manifest.

internet permission

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

Now come to activity_main.xml and create a ListView. In this tutorial I will display the
name of books in a ListView.

activity_main.xml

1 <?xml version="1.0" encoding="utf-8"?>

2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

3 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

4 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
5

8 android:paddingRight="@dimen/activity_horizontal_margin"

9 android:paddingTop="@dimen/activity_vertical_margin"

1 android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

1 <ListView

1 android:id="@+id/listViewBooks"

1 android:layout_width="match_parent"

2 android:layout_height="wrap_content">

1 </ListView>

1 </RelativeLayout>

Create a new Layout Resource file for our ListView. I have created simple_list.xml.

simple_list.xml

1 <?xml version="1.0" encoding="utf-8"?>

2 <TextView xmlns:android="http://schemas.android.com/apk/res/android"

3 android:layout_width="fill_parent"

4 android:layout_height="fill_parent"

5 android:padding="10dp"

6 android:textSize="20sp" >

8 </TextView>
Creating Retrofit Model

A great thing with using retrofit is that, you do not need to parse json by yourself. Retrofit
android library will do it for you. You only need to create a model. So as we have our
json having the details of some books. I am creating a java class named Book.

Create a new class named Book.java and write the following code.

Book.java
Java

1 package net.simplifiedcoding.androidretrofitexample;

3 /**

4 * Created by Belal on 11/3/2015.

5 */

6 public class Book {

8 //Variables that are in our json

9 private int bookId;

1 private String name;

0 private String price;

1 private int inStock;

1 //Getters and setters

2 public int getBookId() {

1 return bookId;

3 }

4 public void setBookId(int bookId) {

1 this.bookId = bookId;
5 }

6 public String getName() {

1 return name;

7 }

8 public void setName(String name) {

1 this.name = name;

9 }

0 public String getPrice() {

2 return price;

1 }

2 public void setPrice(String price) {

2 this.price = price;

3 }

4 public int getInStock() {

2 return inStock;

5 }

6 public void setInStock(int inStock) {

2 this.inStock = inStock;

7 }

2 }

0
3

4
6

You do not need to do much in the model class. You only need to define variables that are
in your json. In my json object I am having 4 properties (id, name, price and stock) so I
created 4 variables here.

And then you need to define getters and setters for the variables.

Now we will create our Retrofit API.

Creating Interface to Send HTTP Request using Retrofit

We have to create an interface to handle our requests. So create a new java interface. I
have createdBookAPI.java. Write the following code.

BooksAPI.java
Java

1 package net.simplifiedcoding.androidretrofitexample;

3 import java.util.List;

5 import retrofit.Callback;

6 import retrofit.http.GET;

8 /**

9 * Created by Belal on 11/3/2015.

1 */

0 public interface BooksAPI {

1 /*Retrofit get annotation with our URL

1 And our method that will return us the list ob Book

2 */
1

1
@GET("/RetrofitExample/books.json")
5
public void getBooks(Callback<List<Book>> response);
1
}
6

Above we have defined a GET Request. And if you are confused about the URL that is
passed then dont bother. Actually in retrofit we cannot pass the whole URL. Here we
have just excluded the root part of the URL which
is http://www.simplifiedcoding.16mb.com/ we will define the root part of the URL
inMainActivity.java.

And we have also declared a method having a Callback in argument. We have the
callback of type List and the type of the List is Book i.e. our data model. So this method
will return us a List of type Book. As the method is only declaration we havent added
any functionality to the method now.

In the first activity we will show only the name of the books in a ListView. And when
user will click on a List Item we will show the book details in the next activity. So create
a new activity for displaying the book details.

I have created ShowBookDetails.java and activity_show_book_details.xml in the .xml


file we will create 4 TextViews to display book id, name, price and stock. So in your
layout xml file write the following code.

activity_show_book_details.xml
1 <?xml version="1.0" encoding="utf-8"?>

2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

4 android:orientation="vertical"

5 android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

6 android:paddingRight="@dimen/activity_horizontal_margin"

7 android:paddingTop="@dimen/activity_vertical_margin"

8 android:paddingBottom="@dimen/activity_vertical_margin"

9 tools:context="net.simplifiedcoding.androidretrofitexample.ShowBookDetails">

0 <TextView

1 android:id="@+id/textViewBookId"

1 android:textSize="24dp"

1 android:layout_width="match_parent"

2 android:layout_height="wrap_content" />

3 <TextView

1 android:id="@+id/textViewBookName"

4 android:textSize="24dp"

1 android:layout_width="match_parent"

5 android:layout_height="wrap_content" />

6 <TextView

1 android:id="@+id/textViewBookPrice"

7 android:textSize="24dp"

1 android:layout_width="match_parent"

8 android:layout_height="wrap_content" />
1

9 <TextView

2 android:id="@+id/textViewBookInStock"

0 android:textSize="24dp"

2 android:layout_width="match_parent"

1 android:layout_height="wrap_content" />

2 </LinearLayout>

3
4

Now come to MainActivity.java and write the following code.

MainActivitiy.java
Java

1 package net.simplifiedcoding.androidretrofitexample;

3 import android.app.ProgressDialog;

4 import android.content.Intent;

5 import android.support.v7.app.AppCompatActivity;

6 import android.os.Bundle;

7 import android.view.View;

8 import android.widget.AdapterView;

9 import android.widget.ArrayAdapter;

10 import android.widget.ListView;

11

12 import java.util.List;

13

14 import retrofit.Callback;

15 import retrofit.RestAdapter;

16 import retrofit.RetrofitError;

17 import retrofit.client.Response;

18

19 //Class having OnItemClickListener to handle the clicks on list

20 public class MainActivity extends AppCompatActivity implements ListView.OnItemClickListener {

21

22 //Root URL of our web service


23 public static final String ROOT_URL = "http://simplifiedcoding.16mb.com/";

24

25 //Strings to bind with intent will be used to send data to other activity

26 public static final String KEY_BOOK_ID = "key_book_id";

27 public static final String KEY_BOOK_NAME = "key_book_name";

28 public static final String KEY_BOOK_PRICE = "key_book_price";

29 public static final String KEY_BOOK_STOCK = "key_book_stock";

30

31 //List view to show data

32 private ListView listView;

33

34 //List of type books this list will store type Book which is our data model

35 private List<Book> books;

36

37 @Override

38 protected void onCreate(Bundle savedInstanceState) {

39 super.onCreate(savedInstanceState);

40 setContentView(R.layout.activity_main);

41

42 //Initializing the listview

43 listView = (ListView) findViewById(R.id.listViewBooks);

44

45 //Calling the method that will fetch data

46 getBooks();

47

48 //Setting onItemClickListener to listview

49 listView.setOnItemClickListener(this);

50 }

51

52 private void getBooks(){

53 //While the app fetched data we are displaying a progress dialog


54 final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please

55 wait...",false,false);

56

57 //Creating a rest adapter

58 RestAdapter adapter = new RestAdapter.Builder()

59 .setEndpoint(ROOT_URL)

60 .build();

61

62 //Creating an object of our api interface

63 BooksAPI api = adapter.create(BooksAPI.class);

64

65 //Defining the method

66 api.getBooks(new Callback<List<Book>>() {

67 @Override

68 public void success(List<Book> list, Response response) {

69 //Dismissing the loading progressbar

70 loading.dismiss();

71

72 //Storing the data in our list

73 books = list;

74

75 //Calling a method to show the list

76 showList();

77 }

78

79 @Override

80 public void failure(RetrofitError error) {

81 //you can handle the errors here

82 }

83 });

84 }
85

86 //Our method to show list

87 private void showList(){

88 //String array to store all the book names

89 String[] items = new String[books.size()];

90

91 //Traversing through the whole list to get all the names

92 for(int i=0; i<books.size(); i++){

93 //Storing names to string array

94 items[i] = books.get(i).getName();

95 }

96

97 //Creating an array adapter for list view

98 ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.simple_list,items);

99

10 //Setting adapter to listview

0 listView.setAdapter(adapter);

10 }

10

2 //This method will execute on listitem click

10 @Override

3 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

10 //Creating an intent

4 Intent intent = new Intent(this, ShowBookDetails.class);

10

5 //Getting the requested book from the list

10 Book book = books.get(position);

10 //Adding book details to intent

7 intent.putExtra(KEY_BOOK_ID,book.getBookId());
10

10

11

11

11

11

3 intent.putExtra(KEY_BOOK_NAME,book.getName());

11 intent.putExtra(KEY_BOOK_PRICE,book.getPrice());

4 intent.putExtra(KEY_BOOK_STOCK,book.getInStock());

11

5 //Starting another activity to show book details

11 startActivity(intent);

6 }

11 }

11

11

12

12

12

2
Now we need to code our second activity to show the details. Simply go to the next
activity which is in my case ShowBookDetails.java and write the following code.

ShowBookDetails.java
Java

1 package net.simplifiedcoding.androidretrofitexample;

3 import android.content.Intent;

4 import android.support.v7.app.AppCompatActivity;

5 import android.os.Bundle;

6 import android.widget.TextView;

8 public class ShowBookDetails extends AppCompatActivity {

1 //Defining views

0 private TextView textViewBookId;

1 private TextView textViewBookName;

1 private TextView textViewBookPrice;

1 private TextView textViewBookInStock;

3 @Override

1 protected void onCreate(Bundle savedInstanceState) {

4 super.onCreate(savedInstanceState);

1 setContentView(R.layout.activity_show_book_details);

1 //Initializing Views

6 textViewBookId = (TextView) findViewById(R.id.textViewBookId);

1 textViewBookName = (TextView) findViewById(R.id.textViewBookName);


7 textViewBookPrice = (TextView) findViewById(R.id.textViewBookPrice);

1 textViewBookInStock = (TextView) findViewById(R.id.textViewBookInStock);

1 //Getting intent

9 Intent intent = getIntent();

0 //Displaying values by fetching from intent

2 textViewBookId.setText(String.valueOf(intent.getIntExtra(MainActivity.KEY_BOOK_ID, 0)));

1 textViewBookName.setText(intent.getStringExtra(MainActivity.KEY_BOOK_NAME));

2 textViewBookPrice.setText(intent.getStringExtra(MainActivity.KEY_BOOK_PRICE));

2 textViewBookInStock.setText(String.valueOf(intent.getIntExtra(MainActivity.KEY_BOOK_STOCK,0

2 )));

3 }

2 }

2
3

Now run your application. You will see the following output.
Retrofit Android Example
Retrofit Android Example

Bingo! Its working fine. You can also download the source code of this retrofit android
example from below.
Manambahkan Marker Dan
Menampilkan Nilai Garis
Lintang Dan Bujur Dengan
Google Maps API Pada
Android Studio

Dengan memanfaatkan Google Maps API dengan Android Studio kita dapat
menandai suatu lokasi dengan menggunakan objek yang disebut marker dan dari
marker yang telah dibuat dapat diambil data lokasi berupa koordinat lintang dan
bujur atau latitude dan longtitude dari suatu lokasi.

Marker menunjukkan lokasi tunggal pada peta.


Anda bisa menyesuaikan marker dengan
mengubah warna default, atau mengganti ikon
marker dengan gambar custom. Jendela informasi
bisa memberikan konteks tambahan pada marker.
-https://developers.google.com
Disini akan dijelaskan bagaimana cara membuat sebuah aplikasi android
sederhana untuk menampilkan data koordinat lintang dan bujur dari marker
yang telah dibuat dengan memanfaatkan Google Maps API yang akan dibangun
menggunakan Android Studio. Sebelum memulai diperlukan aplikasi yang
sebelumnya dibangun di tutorial Menampilkan Peta Dengan Google Maps API
Pada Android Studio dan Menampilkan Lokasi Saat Ini Dengan Maps API Pada
Android Studio.

Persiapan
Beberapa hal yang perlu disiapkan antara lain :

1. Android Studio.

2. Perangkat android untuk uji coba aplikasi yang akan dibuat, pastikan
perangkat terhubung dengan internet dan aktifkan akses lokasi.

3. Aplikasi android dengan Google Maps API yang sebelumnnya dibuat di


tutorial Menampilkan Peta Dengan Google Maps API Pada Android
Studiodan Menampilkan Lokasi Saat Ini Dengan Maps API Pada Android
Studio.

Menambahkan Marker
Buka MapsActivity.java pada package java, Masukan script dibawah ini pada
callback OnLocationChanged di bawah
kodemMap.animateCamera(CameraUpdateFactory.newCameraPosition(came
raPosition));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

@Override

public void onMapClick(final LatLng point) {

//Hapus Marker lama jika sebelumnya terdapat marker

if (mCurrLocationMarker != null) {

mCurrLocationMarker.remove();

//Buat Marker baru

MarkerOptions marker = new MarkerOptions().position( new


LatLng(point.latitude, point.longitude)).title("Lokasi saya");

mCurrLocationMarker = mMap.addMarker(marker);

//Masukan baris kode selanjutnya disini

});

script tersebut berfungsi untuk membuat marker baru setiap suatu area pada map
dipilih.
Menampillkan Koordinat
Tambahkan kode dibawah setelah baris mCurrLocationMarker =
mMap.addMarker(marker); yang sebelumnya dibuat

//Menampilkan garis lintang dan bujur pada toast

String latid = String.valueOf(point.latitude);

String longtid = String.valueOf(point.longitude);

Toast.makeText(MapsActivity.this, "Lat : "+latid+" Long : "+longtid,


Toast.LENGTH_SHORT).show();

script tersebut berfungsi untuk menampilkan data koordinat lokasi terpilih


dengan menggunakan Toast.

Hasil akhir dari callback OnLocationChanged akan terlihat seperti berikut :

@Override

public void onLocationChanged(Location location) {

mLastLocation = location;

if (mCurrLocationMarker != null) {

mCurrLocationMarker.remove();

}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

CameraPosition cameraPosition = new CameraPosition.Builder().target(new


LatLng(latLng.latitude, latLng.longitude)).zoom(16).build();

mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

@Override

public void onMapClick(final LatLng point) {

//Hapus Marker lama jika sebelumnya terdapat marker

if (mCurrLocationMarker != null) {

mCurrLocationMarker.remove();

//Buat Marker baru

MarkerOptions marker = new MarkerOptions().position( new


LatLng(point.latitude, point.longitude)).title("Lokasi saya");

mCurrLocationMarker = mMap.addMarker(marker);
//Masukan baris kode selanjutnya disini

//Menampilkan garis lintang dan bujur pada toast

String latid = String.valueOf(point.latitude);

String longtid = String.valueOf(point.longitude);

Toast.makeText(MapsActivity.this, "Lat : "+latid+" Long : "+longtid,


Toast.LENGTH_SHORT).show();

});

//menghentikan pembaruan lokasi

if (mGoogleApiClient != null) {

LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);

Untuk uji coba aplikasi yang telah dibuat gunakan perangkat android yang
terhubung ke android studio dan memiliki koneksi internet serta aktifkan akses
lokasi pada pengaturan perangkat android. Jika uji coba berhasil maka akan
muncul gambar seperti di bawah ini
Menampilkan Peta Dengan
Google Maps API Pada
Android Studio

Belakangan ini semakin banyak aplikasi android yang memberikan fitur


berbasis lokasi, karena dengan fitur tersebut pengguna dapat memberikan
informasi berupa lokasi yang ditampilkan dalam bentuk peta sehingga dapat
dengan mudah dimengerti oleh penerima informasi. Maps API dari Google play
service adalah salah satu API yang dapat dimanfaatkan dalam mengembangkan
aplikasi android yang memberikan fitur berbasis lokasi.

Disini akan dijelaskan bagaimana cara menampilkan peta menggunakan Maps


API di dalam aplikasi android yang nantinya akan dijalankan dalam perangkat
android.

Persiapan
Beberapa hal yang perlu disiapkan antara lain :

1. Android Studio.
2. Perangkat android untuk uji coba aplikasi yang akan dibuat, pastikan
perangkat terhubung dengan internet dan aktifkan akses lokasi.

Membuat Project Baru


1. Buka Android Studio dan buat Project baru dangan nama "Peta", lalu klik
next.

2. Pilih versi SDK android minimal, disini dipilih Android 4.1, lalu klik next.

3. Pada opsi "Add an Activity to mobile" pilih "Google maps activity", lalu
klik
next.

4. Tinggalkan nama activity, lalu klik Finish.

Mendaftar Maps API


1. Buka google_maps_api.xml pada package res/value, di
google_maps_api.xml terdapat alamat untuk mengaktifkan Maps API,
disini alamatnya adalah
Copy alamat tersebut lalu buka dalam browser, bila perlu daftarkan akun
gmail untuk konfigurasi API.

2. Setelah halama google API terbuka, pilih "Tidak" untuk opsi dapatkan
email, dan pilih "Ya" untuk opsi setuju dengan Syarat dan ketentuan, lalu
klik setuju dan
lanjutkan.

3. Setelah halaman "API diaktifkan" terbuka, klik buat kunci


API.

4. Setelah terbuka halaman "Kredensial" lalu muncul kotak dialog "Kunci


API Dibuat" copy kode API key yang ada didalam box "Kunci API
Anda".

5. Buka kembali google_maps_api.xml pada package res/value di Android


Studio, lalu masukan kode API key diantara <string
name="google_maps_key" templateMergeStrategy="preserve"

translatable="false"> dan </string>menggantikan text

YOUR_KEY_HERE, Hingga
menjadi

Manifests dan
build.gradle(Module:app)
Manifest
1. Buka AndroidManifest.xml pada package manifests.

2. Masukan Permission yang diperlukan antara


lain ACCESS_NETWORK_STATEUntuk memeriksa apakah perangkat
terhubung ke suatu jaringan atau tidak,INTERNET Untuk memeriksa
apakah perangkat terhubung ke Internet atau
tidak, ACCESS_COARSE_LOCATION Untuk memperkirakan lokasi pengguna
menggunakan WiFi atau sinyal mobile, ACCESS_FINE_LOCATION Untuk
memperkirakan lokasi terkini pengguna, OpenGL ES V2 Dibutuhkan
untuk Google Maps V2 sehingga AndroidManifest.xml menjadi :
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.root.peta">

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

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

<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<!--

The ACCESS_COARSE/FINE_LOCATION permissions are not required to use


Google Maps Android API v2, but you must specify either coarse or fine

location permissions for the 'MyLocation' functionality.

-->

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

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

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<!--

The API key for Google Maps-based APIs is defined as a string resource.

(See the file "res/values/google_maps_api.xml").


Note that the API key is linked to the encryption key used to sign the
APK.

You need a different API key for each encryption key, including the
release key that is used to

sign the APK for publishing.

You can define the keys for the debug and release targets in src/debug/
and src/release/.

-->

<meta-data

android:name="com.google.android.geo.API_KEY"

android:value="@string/google_maps_key" />

<activity

android:name=".MapsActivity"

android:label="@string/title_activity_maps">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>

</activity>

</application>

</manifest>

build.gradle(Module:app)
1. Buka build.gradle(Module:app) pada Gradle Scripts

2. Masukan compile com.google.android.gms:play-


services:9.8.0 sebelumtestCompile 'junit:junit:4.12 Hingga

menjadi

maps.java
1. Buka MapsActivity.java pada package java, tidak perlu mengubah script
tersebut namun pastikan MapsActivity.java terlihat seperti berikut
package com.example.root.peta;
import android.support.v4.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);

// Obtain the SupportMapFragment and get notified when the map is ready to be
used.

SupportMapFragment mapFragment = (SupportMapFragment)


getSupportFragmentManager()

.findFragmentById(R.id.map);

mapFragment.getMapAsync(this);

/**

* Manipulates the map once available.

* This callback is triggered when the map is ready to be used.

* This is where we can add markers or lines, add listeners or move the camera.
In this case,

* we just add a marker near Sydney, Australia.

* If Google Play services is not installed on the device, the user will be
prompted to install

* it inside the SupportMapFragment. This method will only be triggered once the
user has
* installed Google Play services and returned to the app.

*/

@Override

public void onMapReady(GoogleMap googleMap) {

mMap = googleMap;

// Add a marker in Sydney and move the camera

LatLng sydney = new LatLng(-34, 151);

mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

Pada script diatas telah ditambahkan koordinat Sydney Australia secara default
di onMapReady(). Jadi saat aplikasi dijalankan pertama kali marker akan
ditempatkan di Sydney Australia.

Untuk uji coba aplikasi yang telah dibuat gunakan perangkat android yang
terhubung ke android studio dan memiliki koneksi internet serta aktifkan akses
lokasi pada pengaturan perangkat android. Jika uji coba berhasil maka akan
muncul gambar seperti di bawah ini

You might also like