Professional Documents
Culture Documents
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",
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",
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.
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'
internet permission
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
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
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 /**
5 */
1 return bookId;
3 }
1 this.bookId = bookId;
5 }
1 return name;
7 }
1 this.name = name;
9 }
2 return price;
1 }
2 this.price = price;
3 }
2 return inStock;
5 }
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.
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 /**
1 */
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.
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
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
21
24
25 //Strings to bind with intent will be used to send data to other activity
30
33
34 //List of type books this list will store type Book which is our data model
36
37 @Override
39 super.onCreate(savedInstanceState);
40 setContentView(R.layout.activity_main);
41
44
46 getBooks();
47
49 listView.setOnItemClickListener(this);
50 }
51
55 wait...",false,false);
56
59 .setEndpoint(ROOT_URL)
60 .build();
61
64
66 api.getBooks(new Callback<List<Book>>() {
67 @Override
70 loading.dismiss();
71
73 books = list;
74
76 showList();
77 }
78
79 @Override
82 }
83 });
84 }
85
90
94 items[i] = books.get(i).getName();
95 }
96
99
0 listView.setAdapter(adapter);
10 }
10
10 @Override
3 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
10 //Creating an intent
10
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
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;
1 //Defining views
3 @Override
4 super.onCreate(savedInstanceState);
1 setContentView(R.layout.activity_show_book_details);
1 //Initializing Views
1 //Getting 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.
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.
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
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
mCurrLocationMarker = mMap.addMarker(marker);
});
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
@Override
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
mCurrLocationMarker = mMap.addMarker(marker);
//Masukan baris kode selanjutnya disini
});
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
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.
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.
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.
YOUR_KEY_HERE, Hingga
menjadi
Manifests dan
build.gradle(Module:app)
Manifest
1. Buka AndroidManifest.xml pada package manifests.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.root.peta">
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_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.
You need a different API key for each encryption key, including the
release key that is used to
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>
</activity>
</application>
</manifest>
build.gradle(Module:app)
1. Buka build.gradle(Module:app) pada Gradle Scripts
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;
@Override
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be
used.
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
/**
* This is where we can add markers or lines, add listeners or move the camera.
In this case,
* 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
mMap = googleMap;
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