Halo teman – teman, pada artikel kali ini kita akan membahas mengenai pembuatan program yang akan menghasilkan faktorial dari sebuah bilangan pada bahasa Kotlin.
Dalam matematika, faktorial dari bilangan aslin yaitu hasil perkalian selang bilangan bulat positif yang kurang dari atau sama dengan n. Faktorial ditulis sebagai n! dan dinamakan n faktorial.
Sebagai contoh, 4! yaitu mempunyai nilai 1×2×3×4 = 24.
Pada program Kotlin faktorial ini kita akan mengambil bilangan bulat dan menampilkan faktorial dari bilangan tersebut dan menghitung nilai nya menggunakan looping.
Program
fun main() {
var result: Int = 1
println("Masukkan bilangan bulat : ")
var n: Int = readLine()!!.toInt();
if (n <= 0){
print("Angka yang dimasukkan bukan bilangan bulat atau adalah angka 0")
} else {
for (i in 1..n) {
result *= i
}
print("Angka faktorial " + n + " adalah " + result)
}
}
Output nya adalah
Masukkan bilangan bulat :
4
Angka faktorial 4 adalah 24
Penjelasan
Kita akan membuat programnya di dalam method main. Buat variabel penampung hasil faktorial nya. Selanjutnya, buat variabel penampung hasil input user dari console. Jangan lupa untuk mengubah tipe data dari masukan user menjadi integer.
var result: Int = 1
println("Masukkan bilangan bulat : ")
var n: Int = readLine()!!.toInt();
Kita cek terlebih dahulu apakan nilai yang dimasukkan oleh user lebih dari 0. Jika nilai n kurang dari 0 maka akan di keluarkan output gagal.
if (n <= 0){
print("Angka yang dimasukkan bukan bilangan bulat atau adalah angka 0")
} else {
// Program
}
Selanjutnya, di bagian blok else kita buat loopingnya terlebih dahulu.
for (i in 1..n) {
// operasi
}
blok looping tersebut akan dijalankan ketika nilai i masih kurang atau sama dengan dari nilai yang diinputkan oleh user.
Di dalam blok looping nya kita panggil variabel faktorial yang nilai nya akan dikalikan dengan variable i
Halo teman – teman, pada artikel kali ini kita akan membahas mengenai pembuatan program yang akan menghasilkan faktorial dari sebuah bilangan pada bahasa Dart.
Dalam matematika, faktorial dari bilangan aslin yaitu hasil perkalian selang bilangan bulat positif yang kurang dari atau sama dengan n. Faktorial ditulis sebagai n! dan dinamakan n faktorial.
Sebagai contoh, 4! yaitu mempunyai nilai 1×2×3×4 = 24.
Pada program Dart faktorial ini kitaakan mengambil bilangan bulat dan menampilkan faktorial dari bilangan tersebut dan menghitung nilai nya menggunakan looping.
Program
import 'dart:io';
void main() {
int faktorial = 1;
print("Masukkan bilangan bulat : ");
int? n = int.parse(stdin.readLineSync()!);
if (n < 0){
print("Angka yang dimasukkan bukan bilangan bulat");
} else {
for (int i = 1; i <= n; i++){
faktorial *= i;
}
print("Hasil faktorial dari " + n.toString() + " adalah " + faktorial.toString());
}
}
Output nya adalah
Masukkan bilangan bulat :
4
Hasil faktorial dari 4 adalah 24
Penjelasan
Yang pertama, kita import library io untuk mengambil input dan mengeluarkan output dari console atau command line.
import 'dart:io';
Lalu, kita buat programnya di dalam method main. Buat variabel penampung hasil faktorial nya. Selanjutnya, buat variabel penampung hasil input user dari console.
int? n = int.parse(stdin.readLineSync()!);
Kita cek terlebih dahulu apakan nilai yang dimasukkan oleh user lebih dari 0. Jika nilai n kurang dari 0 maka akan di keluarkan output gagal.
if (n <= 0){
print("Angka yang dimasukkan bukan bilangan bulat atau adalah angka 0");
} else {
// Program
}
Selanjutnya, di bagian blok else kita buat loopingnya terlebih dahulu.
for (int i = 1; i <= n; i++){
// Operasi
}
blok looping tersebut akan dijalankan ketika nilai i masih kurang atau sama dengan dari nilai yang diinputkan oleh user.
Di dalam blok looping nya kita panggil variabel faktorial yang nilai nya akan dikalikan dengan variable i
Halo teman – teman, pada artikel kali ini kita akan membahas mengenai manipulasi variable tipe dengan tipe data String pada bahasa Kotlin.
String merupakan salah satu tipe data non – primitif yang digunakan untuk menampung kalimat, kata – kata, atau kumpulan karakter.
Terkadang, dalam dunia pemrograman ada kasus dimana kita harus melakukan penggabungan kalimat, pemisahan kalimat, merubah sebuah kalimat menjadi huruf kapital, dan lainnya. Operasi tersebut disebut dengan manipulasi String.
Pada bahasa pemrograman Kotlin sendiri disediakan beberapa fungsi yang digunakan untuk operasi manipulasi String. Kita akan bahas satu persatu.
1. Concat
Untuk menggabungkan beberapa kata atau Kalimat pada Kotlin, disebut dengan concatenation. Di Kotlin sendiri ada beberapa cara yang populer untuk melakukan concat.
// Menggunakan karakter (+) :
var namaDepan = "Rafi"
var namaBelakang = "Izzatul"
var namaLengkap = namaDepan + " " + namaBelakang
println(namaLengkap)
// output : Rafi Izzatul
// Menggunakan interpolasi
var namaDepan = "Rafi"
var namaBelakang = "Izzatul"
var namaLengkap = "$namaDepan $namaBelakang"
println(namaLengkap)
// output : Rafi Izzatul
2. Substring
Substring merupakan fungsi yang digunakan untuk mengambil beberapa karakter dari sebuah Kalimat atau kata. Fungsi ini memiliki 2 parameter, yaitu index awalan dan juga index akhir. Indexnya diambil sesuai dengan urutan karakter yang ada di Kalimat tersebut. (Karakter pertama berindex 0).
var namaLengkap = "Rafi Izzatul"
var namaBelakang = namaLengkap.substring(5, 12)
println(namaBelakang)
// output : Izzatul
3. Contains
Untuk mengecek Apakah sebuah Kalimat mengandung karakter yang kita tentukan atau tidak, kita bisa memakan fungsi contains. Fungsi ini akan mengembalikan atau menghasilkan boolean true jika Kalimat tersebut mengandung karakter yang kita inputkan. Sebaliknya, fungsi contains akan menghasilkan boolean false jika Kalimat tersebut tidak mengandung Kalimat yang kita inputkan.
ToLowerCase adalah fungsi yang digunakan untuk merubah Kalimat atau karakter menjadi huruf kecil.
var namaDepan = "RAFI"
println(namaDepan.toLowerCase())
// output : rafi
5. ToUpperCase
Kebalikan dari fungsi ToLowerCase, fungsi ToUpperCase adalah fungsi yang digunakan untuk merubah Kalimat atau karakter menjadi huruf kapital.
var namaBelakang = "izzatul"
println(namaBelakang.toUpperCase())
// output : IZZATUL
6. Replace
Fungsi Replace merupakan fungsi yang digunakan untuk mengganti karakter yang ada di dalam String menjadi karakter baru yang kita inginkan. Fungsi ini mempunyai 2 parameter. Parameter yang pertama berisi karakter apa yang ingin kita ganti dalam sebuah string. Parameter yang kedua berisi karakter baru yang akan menggantikan karakter lama yang kita isi pada parameter pertama.
var greeting = "Hai"
println(greeting.replace("a", "e"))
// output : Hei
7. Length
Length adalah fungsi yang digunakan untuk menghitung berapa banyak jumlah karakter yang ada di dalam sebuah String.
var namaLengkap = "Rafi Izzatul"
println(namaLengkap.length)
// output : 12
Oke teman teman, sekian dulu artikel kali ini. Sampai jumpa di artikel berikutnya.
Menyambut Ramadhan 1438H, Rumah Coding memberi kesempatan kepada pemiliki blog yang bersifat non komersil untuk memiliki versi android dari blog tersebut secara gratis.
Jika Anda adalah admin dan pengurusan sebuah blog non komersil, anda dapat mengajukan pembuatan aplikasi Android untuk blog anda tersebut. Dengan ketentuan:
Pembuatan aplikasi android hanya berlaku untuk blog non komersil.
Pembuatan aplikasi android tidak bersifat custom. Hanya mengikuti format aplikasi yang kami tawarkan.
Tidak ada iklan apapun dalam aplikasi.
Gratis upload ke Google Play Store menggunakan akun Rumah Coding.
Hanya untuk 60 blog yang terpilih.
Hanya admin dan pengurus blog terkait yang dapat mengajukan pembuatan aplikasi android. Anda tidak diperkenan mengajukan blog yang bukan milik anda. Pada form pengajuan anda akan diminta menyertakan screenshot dashboard dari blog anda untuk otentikasi.
Tampilan aplikasi android untuk blog kurang lebih akan seperti ini:
Tahapan pembuatan aplikasi android:
Mengisi form di bawah paling lambat tanggal 24 Juni 2017.
Blog yang terpilih akan dihubungi secara bertahap melalui whatsapp atau email pada tanggal 1-7 Juli 2017.
Peserta yang terpilih akan diminta melengkapi berbagai macam data untuk keperluan upload ke Google Play Store, seperti icon, deskripsi dan lain-lain.
Proses pembuatan dan upload ke Google Play Store secara bertahap pada tanggal 8-15 Juli 2017
Bulan Ramadhan sebentara lagi datang, apa yang sudah anda persiapkan? Bulan Ramadhan kali ini, Rumah Coding insya Allah akan mengadakan “Workshop Android Spesial Ramadhan”. Terdapat 3 workshop di bulan ramadhan mendatang. Melalui workshop ini, anda akan langsung praktek membuat aplikasi berikut
1. Kamus Arab Indonesia
Hari: Minggu,
Tanggal: 28 Mei 2017
Waktu: 09:00 – 17:00
Biaya: Rp. 100.000
Materi:
– Activity
– Frame Layout
– Google Translator API
– List View
– Card View
– Custom Adapter
– Share Intent
– Realm
2. Jadwal dan Pengingat Shalat
Hari: Kamis,
Tanggal: 1 Juni 2017
Waktu: 09:00 – 17:00
Biaya: Rp. 100.000
Setiap bulan, Rumah Coding mengadakan workshop untuk umum. Pada workshop ke-8 kali ini, Rumah Coding mengadakan workshop bertema “Membuat Aplikasi Android Untuk Pemula Menggunakan Android Studio”.
Tertarik membuat aplikasi android tapi tidak tau harus memulai dari mana? Jangan khawatir, Rumah Coding kembali akan mengadakan pelatihan/workshop android bertema “Membuat Aplikasi Android Untuk Pemula”. Pada pelatihan ini teman-teman akan diajarkan dasar-dasar pembuatan aplikasi android.
Materi yang akan di bahas, antara lain: – Activity – Layout dan View – Resource – Menu – List View – Custom List Adapter – Realm
Hari: Sabtu,
Tanggal: 20 Mei 2017
Waktu: 09:00 – 17:00
Tempat: DILo (Digital Innovation Longue ) Depok
Jl. Margonda Raya No. 23 (Rukan Sebelah BPJS Kesehatan Kota Depok),
Kel. Depok, Kec. Pancoran MAS, Depok, Pancoran MAS, Kota Depok, Jawa Barat 16431 https://goo.gl/maps/2cb1AZBRGZQ2
Biaya Workshop: Rp. 150.000
Persyaratan:
1. Memiliki laptop sendiri (Windows/Linux/Mac 4GB RAM)
Persyaratan Software:
1. JDK7 (https://goo.gl/8XHlU2)
2. Android Studio (https://goo.gl/fcKQbF)
3. Emulator: Blue Stack (www.bluestacks.com)
Tahap pendaftaran:
1. Mengisi formulir di bawah.
2. Peserta akan dihubungi melalui email/whatsapp
3. Pembayaran via transfer
4. Workshop.
Fasilitas:
1. Lunch
2. Sertifikat
Catatan:
– Tersedia koneksi internet, tetapi untuk berjaga-jaga, silahkan mempersiapkan koneksi internet masing-masing.
Tertarik membuat game android tapi tidak tau harus memulai dari mana? Jangan khawatir, Rumah Coding kembali akan mengadakan pelatihan/workshop android bertema “Membuat Game Android Untuk Pemula Menggunakan Unity”. Pada workshop ini teman-teman akan diajarkan dasar-dasar pembuatan game android menggunakan game engine Unity.
Materi yang akan di bahas, antara lain: – Game Object – Sprite Animations – Physics 2D – Collider – Prefabs – Canvas UI
Hari: Kamis
Tanggal: 11 Mei 2017
Waktu: 09:00 – 17:00
Tempat: Code Margonda, Jl. Margonda Raya No.349 Depok (di Atas Veneta System)
Lokasi: https://goo.gl/maps/uTt6GJV1vKC2
HTM: Rp. 200.000
Early Bird (s.d 7 Mei 2017) : Rp. 150.000
Persyaratan:
1. Memiliki laptop sendiri (Windows/Linux/Mac 4GB RAM)
Setiap bulan, Rumah Coding mengadakan workshop untuk umum. Pada workshop ke-6 kali ini, Rumah Coding mengadakan workshop bertema “Membuat Aplikasi Android Untuk Pemula”.
Tertarik membuat aplikasi android tapi tidak tau harus memulai dari mana? Jangan khawatir, Rumah Coding kembali akan mengadakan pelatihan/workshop android bertema “Membuat Aplikasi Android Untuk Pemula”. Pada pelatihan ini teman-teman akan diajarkan dasar-dasar pembuatan aplikasi android.
Materi yang akan di bahas, antara lain:
– Activity
– Layout dan View
– Resource
– Menu
– List View
– Custom List Adapter
– SqLite
Hari: Minggu,
Tanggal: 30 April 2017
Waktu: 09:00 – 17:00
Tempat: DILo (Digital Innovation Longue ) Depok
Jl. Margonda Raya No. 23 (Rukan Sebelah BPJS Kesehatan Kota Depok),
Kel. Depok, Kec. Pancoran MAS, Depok, Pancoran MAS, Kota Depok, Jawa Barat 16431
https://goo.gl/maps/2cb1AZBRGZQ2
Biaya Workshop: Gratis
Persyaratan:
1. Memiliki laptop sendiri (Windows/Linux/Mac 4GB RAM)
Pada tutorial ini, anda akan belajar membuat sebuah aplikasi android sederhana yang menggunakan List View. Data yang akan ditampilkan adalah kumpulan aplikasi android yang populer di Play Store lengkap dengan icon, total download dan data rating dari masing-masing aplikasi. Data total download dan rating yang kita gunakan dalam tutorial ini bukan merupakan data asli, akan tetapi hanya berupa data dumi untuk tujuan demo.
Data dumi tersebut akan disimpan dalam database MySQL. Kemudian anda juga akan membuat script PHP yang akan mengambil data dumi tadi dari database MySQL. Aplikasi android yang anda buat kemudian memanggil script PHP tadi untuk mengambil data dumi dalam format JSON (Javascript Object Notation). Sebelum saya menjelaskan tahap-tahap pembuatan aplikasi tersebut. Saya akan menjelaskan terlebih dahulu konsep-konsep dasar yang perlu anda pahami.
Mengenal JSON
JSON (Javascript Object Notation) merupakan format pertukaran data. Sebuah objek JSON merupakan kumpulan dari pasangan key dan value yang diawali dengan tanda “{” dan diakhiri dengan tanda “}”. Berikut ini adalah contoh sebuah objek JSON yang akan anda gunakan dalam tutorial ini.
As I’ve stated before, we’ll create simple android application that show a list of top application. We use android list view to display the data. The list data come from MySQL server. So this application will have a http connection feature. Communication between server and android application is use JSON based data. In this tutorial we’ll use apached server in localhost that running AVD (Android Virtual Device).
The data that are fetched from server including applicatoin title, rating, total download and icon name. For simplicity of the tutorial, we’ll use an icons that are saved in /res/drawable folder for applications. This will reduce the complexity of downloading the icons from server.
Below is final screenshot of our tutorial
Populate Listview Using JSON
Server Side Task
1. Creating A Database in MySQL
Before creating a database in MySQL, make sure you’ve create a user to login into the MySQL server. In this tutorial, we use a default user root with blank password.
We’ll create a simple database scheme for the application. The database will be used to store application data. Execute the following sql to create such database.
CREATE DATABASE apps;
Now, we have a database apps. We need to create a table in database apps that will store the application title, total download, rating and icon file name. Execute the following sql to create the table.
CREATE TABLE `app_data`(
`id` int unsigned NOT NULL AUTO_INCREMENT,
`app_title` varchar(150) NOT NULL,
`total_dl` int unsigned NOT NULL default 0,
`rating` int unsigned NOT NULL default 0,
`icon` varchar(120) NOT NULL,
primary key(`id`)
);
Now, we must put sample application data into the table. Execute the following sql to create sample application data.
INSERT INTO app_data VALUES(null, "Facebook", 20099099, 5, "facebook");
INSERT INTO app_data VALUES(null, "Twitter", 11342099, 5, "twitter");
INSERT INTO app_data VALUES(null, "Google +", 10123023, 4, "google");
INSERT INTO app_data VALUES(null, "Whatsapp", 10033876, 3, "whatsapp");
INSERT INTO app_data VALUES(null, "Youtube", 10023444, 4, "youtube");
INSERT INTO app_data VALUES(null, "Line", 9023434, 5, "line");
INSERT INTO app_data VALUES(null, "Kakao Talk", 8247836, 3, "kakao");
INSERT INTO app_data VALUES(null, "Linked In", 784736, 4, "linkedin");
INSERT INTO app_data VALUES(null, "Angry Bird", 693847, 2, "angrybird");
INSERT INTO app_data VALUES(null, "Skype", 528374, 3, "skype");
2. Create PHP Script to Fetch the Data
The database now ready, we need create a PHP script that connect to MySQL server and get the application data. Then the application data is converted into JSON string that will send into client (android application). This script use user root with blank password to login into MySQL server, you can change them to meet your server account.
<?php
$host = "localhost"; // host of MySQL server
$user = "root"; // MySQL user
$pwd = ""; // MySQL user's password
$db = "apps"; // database name
// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);
// Check connection
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// query the application data
$sql = "SELECT * FROM app_data ORDER By id";
$result = mysqli_query($con, $sql);
// an array to save the application data
$rows = array();
// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
// close the database connection
mysqli_close($con);
// echo the application data in json format
echo json_encode($rows);
Save above source as PHP file and give a name apps.php and you must place it in apache document root, for example http://localhost/test/apps.php.
3. Testing PHP Script in A Browser
We must test the PHP script we’ve created to make sure the script works well. Open your browser and goto http://localhost/test/apps.php (the url may depend on your environtment). If the script works well, you’ll see the following result in your browser.
JSON In Browser
Client Side Task (Android Application)
After the server side is ready and tested, now we’ll create an android application that will create a http request to PHP script that we’ve created previously to get all application data and display the data in a list view. In order to display all of data like application title, total downloads, rating and icon, we must create a custom adapter for the list view.
Open your Eclipse IDE and create new android application. Use JsonDemo as the project’s name.
Do the following step by step to create the application.
1. Create Main Layout File
This file is an xml layout file that defines the main user interface. It contains a list view that will display all of the application data.
Save below source code as /res/layout/activity_main.xml.
This file is an xml layout file. It responsibles to define a custom view the list view that is contained in the main layout. This file will be used in the custom adapter that will be defined later. The layout contains 3 TextView and 1 ImageView. The image view is used to display the application icon. It is placed on the left. First text view is used to display application’s title. It is placed on the right of the icon. Second text is used to display application’s rating. It is placed on the bottom application’s title. The last text view is used to display the application’ total download.
Save below source code as /res/layout/app_custom_list.xml.
This file is a java object class that represents an application value object. It has several properties that are mapped from the app_data table from our database. It has properties such as application name, total downloads, rating and icon. Below is definition of the file. Below is the source code that define application value object. Save it as /src/com/sj/jsondemo/Application.java.
package com.sj.jsondemo;
public class Application {
private String title;
private long totalDl;
private int rating;
private String icon;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getTotalDl() {
return totalDl;
}
public void setTotalDl(long totalDl) {
this.totalDl = totalDl;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
4. Create Custom Adapter File
This file is list view’s custom adapter that will inflate /res/layout/app_custom_list.xml layout file. It’s constructor is defined with 1 parameter. The parameter is an array list of application value object. The adapter will inflates the layout for each application object in the array list and change the application title, rating, total downloads and icons dynamically.
Below is source code that defines the custom adapter. Save it as /src/com/sj/jsondemo/ApplicationAdapter.java.
5. Create An Async Task File To Get The Data From Server
This file responsibles to get all the application data by creating a http request to PHP script. It is defined by subclassed AsyncTask object class. This means the task will be execute in the background, so it never block the user interface. When the task is executed, a progress bar will be shown to make the interface user friendly. This file communicate to activity via a listener that we’ll create later. This communication is important because we need to notify the activity when all the data has been fetched.
Below is the source code that define the async task. Save it as /src/com/sj/jsondemo/FetchDataTask.java.
package com.sj.jsondemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class FetchDataTask extends AsyncTask<String, Void, String>{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
if(params == null) return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if(entity == null) {
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch(IOException e){
msg = "No Network Connection";
}
return null;
}
@Override
protected void onPostExecute(String sJson) {
if(sJson == null) {
if(listener != null) listener.onFetchFailure(msg);
return;
}
try {
// convert json string to json array
JSONArray aJson = new JSONArray(sJson);
// create apps list
List<Application> apps = new ArrayList<Application>();
for(int i=0; i<aJson.length(); i++) {
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setTitle(json.getString("app_title"));
app.setTotalDl(Long.parseLong(json.getString("total_dl")));
app.setRating(Integer.parseInt(json.getString("rating")));
app.setIcon(json.getString("icon"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if(listener != null) listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if(listener != null) listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
* @param is respons string
* @return json string
* @throws IOException
*/
public String streamToString(final InputStream is) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
throw e;
}
finally {
try {
is.close();
}
catch (IOException e) {
throw e;
}
}
return sb.toString();
}
}
6. Create Fetch Data Listener
This file is simple Java interface. It has two method’s declarations, onFetchCompleted and onFetchFailure. onFetchCompleted method will be called from FetchDataTask when data fetching is complete. onFetchFailure will be called from FetchDataTask when data fetching is failure.
Save below source code as /src/com/sj/jsondemo/FetchDataListener.java.
package com.sj.jsondemo;
import java.util.List;
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
7. Create Activity
This is main activity that will inflate /res/layout/activity_main.xml to create main user interface. When the activity is created, it’s create new FetchDataTask instance and call execute method of the instance. The task runs and start to get all application data in the background. Before execute the task, the activity show progress bar to the user to indicate that the system is loading the data.
This activity also implements FecthDataListener and overriden onFetchCompleted and onFetchFailure. onFetchFailure is used by activity to hide the progress bar and display failure message to user. onFetchCompleted is used by activity to hide the progress bar and display the application data into the list.
The apache server that we used is localhost which same as host that run AVD(Android Virtual Device), so to refers this host from AVD, we must use IP address 10.0.2.2. For more information please visit Android Developer Site.
Save below source code as /src/com/sj/jsondemo/MainActivity.java.
package com.sj.jsondemo;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener{
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://10.0.2.2/test/apps.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
@Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
@Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
8. Create Manifest File
The application make a http request, so the the manifest file must contains network usage permission. Below is complete manifest file. Save it as Android.Manifest.