Android

Membuat Aplikasi CRUD Sederhana di Android Menggunakan PHP dan MySQL PART 3

Posted by:

 

  1. Pertama buat sebuah package baru dengan nama activities.                    
  2. Lalu buatlah sebuah activty (Empty Activity) dalam folder activities dengan nama FormActivity
  3. Lalu masuk ke appres > layout > activity_form.xml . Masukkan source code di bawah
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        tools:context="id.co.contactperson.contactperson.activities.FormActivity">
    
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <EditText
                android:id="@+id/et_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Nama :"
                android:inputType="textPersonName"
                android:maxLines="1"
                android:singleLine="true" />
    
        </android.support.design.widget.TextInputLayout>
    
        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <EditText
                android:id="@+id/et_contact_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="No Telp :"
                android:inputType="number"
                android:maxLength="15"
                android:singleLine="true" />
    
        </android.support.design.widget.TextInputLayout>
    
        <Button
            android:id="@+id/btn_simpan"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="Simpan"
            android:textAllCaps="false"
            android:textStyle="bold" />
    
    </LinearLayout>
    
    
  4. Lalu masuk ke app > res > layout > activity_main.xml . Masukkan source code di bawah
    
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="id.co.contactperson.contactperson.MainActivity>
    
        <ListView
            android:id="@+id/lv_person_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
        </ListView>
    </FrameLayout>
    
    
  5. Kemudian buat sebuah layout dengan nama item_person
  6. Lalu klik Finish .
  7. Lalu masuk ke app > res > layout >item_person.xml . Masukkan source code di bawah
    
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">
    
        <android.support.v7.widget.CardView
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp">
    
            &amp;lt;LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="5dp"&amp;gt;
    
                <TextView
                    android:id="@+id/tv_name"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="Nama :"
                    android:textSize="20sp"
                    android:textStyle="bold" />
    
                <TextView
                    android:id="@+id/tv_contact_number"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="No :"
                    android:textSize="20sp" />
    
            </LinearLayout>
    
        </android.support.v7.widget.CardView>
    </FrameLayout>
    
    
  8. Buatlah sebuah package dengan nama adapters                                           
  9. Buatlah sebuah file di dalam package adapters dengan nama PersonItemAdapter 
  10. Masuk ke file PersonItemAdapter.java , kemudian isi dengan source code di bawah
    
    public class PersonItemAdapter extends ArrayAdapter<Person> {
    
        private List<Person> personList;
        private Context context;
        private LayoutInflater layoutInflater;
    
        public PersonItemAdapter(@NonNull Context context, List<Person> persons) {
            super(context, R.layout.item_person ,persons);
            this.context=context;
            personList=persons;
            layoutInflater=LayoutInflater.from(context);
        }
    
        @Override
        public int getCount() {
            return personList.size();
        }
    
        @Nullable
        @Override
        public Person getItem(int position) {
            return personList.get(position);
        }
    
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view=convertView;
    
            if(view==null){
    
                view=layoutInflater.inflate(R.layout.item_person,null);
            }
            TextView name=view.findViewById(R.id.tv_name);
            TextView contactNunmber=view.findViewById(R.id.tv_contact_number);
    
            Person person=getItem(position);
    
            //Kasih nilai ke Person_item layout
            name.setText(person.getPersonName());
            contactNunmber.setText(person.getContactNumber());
    
            return view;
        }
    }
    
    
  11. Masuk ke file MainActivity.java , kemudian isi dengan source code di bawah
    
    public class MainActivity extends AppCompatActivity  {
    
        @BindView(R.id.lv_person_list)
        ListView lvPersonList;
    
        List<Person> personItemList;
        PersonItemAdapter personItemAdapter;
    
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
    
            //Masukkan adapter ke listView
            personItemAdapter = new PersonItemAdapter(this, personItemList);
    
        
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            getAllPerson(generateToken());
            personItemAdapter.notifyDataSetChanged();
        }
        
    
        private String generateToken() {
    
            SecureRandom random = new SecureRandom();
            byte bytes[] = new byte[20];
            random.nextBytes(bytes);
            return bytes.toString();
        }
    
        public void getAllPerson(final String token) {
    
            ApiEndPoint apiEndPoint = ApiClient.getClient().create(ApiEndPoint.class);
            Call<ReadResponse> call = apiEndPoint.readRequest(token);
    
            call.enqueue(new Callback<ReadResponse>() {
                @Override
                public void onResponse(Call<ReadResponse> call, Response<ReadResponse> response) {
    
                    final ReadResponse readResponse = response.body();
    
                    if (readResponse != null) {
                        Log.d("Response Data ", "Total Data" + readResponse.getStatus());
                        if (readResponse.getStatus()) {
    
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
    
                                    personItemList = readResponse.getPersons();
    
                                    lvPersonList.setAdapter(new PersonItemAdapter(getApplicationContext(), personItemList));
                                    personItemAdapter.notifyDataSetChanged();
                                }
                            });
    
                        } else {
                            Toast.makeText(getApplicationContext(), "Data Kosong", Toast.LENGTH_SHORT).show();
                        }
    
                    } else {
                        Log.d("Login : ", "Data Null");
                    }
                }
    
                @Override
                public void onFailure(Call<ReadResponse> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "Koneksi Bermasalah", Toast.LENGTH_SHORT).show();
    
                }
            });
        }
    
    }
    
    
  12. Lalu masuk ke app > manifests > AndroidManifest.xml  . Tambahkan perizinan untuk koneksi ke internet<uses-permission android:name=”android.permission.INTERNET” />
  13. Sekarang kita coba running dengan emulator . Klik tombol hijau yang ada di menu bar    
  14. Pilih emulator yang ingin anda gunakan, lalu klik OK. 

0

Membuat Aplikasi CRUD Sederhana di Android Menggunakan PHP dan MySQL PART 2

Posted by:

  1. Buka Android Studio anda. Klik Start a new Android Studio project .
  2. Isi data seperti gambar dibawah ini , untuk Project location sesuaikan dengan directory anda. Kemudian klik Next.
  3. Isi data seperti gambar dibawah ini. Kemudian klik Next.
  4. Pilih Empty Activity Isi data seperti gambar dibawah ini. Kemudian klik Next.
  5. Kemudian klik Finish.
  6. Jika berhasil, akan muncul tampilan seperti gambar dibawah ini.
  7. Kita install library lewat Gradle . Klik Gradle Scripts -> pilih build.gradle (Module:app)
  8. Masukkan code berikut                                                                                                                                            //Install Library Tambahan
    implementation ‘com.android.support:design:26.1.0’
    implementation ‘com.android.support:cardview-v7:26.1.0’
    //BindView
    implementation ‘com.jakewharton:butterknife:8.8.1’
    annotationProcessor ‘com.jakewharton:butterknife-compiler:8.8.1’//Retrofit
    implementation ‘com.squareup.retrofit2:retrofit:2.3.0’
    //GSON Converter
    implementation ‘com.squareup.retrofit2:converter-gson:2.3.0’
  9. Kemudian pilih app -> java -> id.co.contactperson.contactperson lalu klik kanan seperti gambar dibawah
  10. Isikan nama Package Name services Kemudian klik OK.
  11. Sekarang kita akan buat file .java di dalam package services. Klik kanan pada package services seperti gambar dibawah ini.
  12. Pada isian kolom Name : kita isi dengan ApiClient . Lalu klik OK.
  13. Isikan file java dengan Source Code dibawah ini. Class ini digunakan untuk memulai koneksi dengan API ContactPerson. Untuk Ip dan Nama Folder Server sesuaikan dengan koneksi anda.
  14. Kemudian buatlah sebuah package seperti cara no 9 dengan nama responses.
  15. Kemudian buatlah sebuah file .java seperti cara no 11. Pada kolom isian Name : isi dengan ApiEndPoint lalu kolom Kind : pilih Interface . Lalu klik OK.
  16. Jika berhasil, tampak seperti gambar dibawah.                                                     
  17. Sebelum kita membuat fungsi Interface ApiEndPoint, kita buat file di package responses untuk meresponse data dari server. Balik lagi ke phpMyAdmin pilih databse contact_person -> person lalu pilih menu bar Insert. Isi data seeperti gambar dibawah, kemudian klik Go
  18. Buka file php pada folder ContactPerson kemudian ubah sementara source code nya seperti gambar di bawah. Save file yang sudah diubah.
  19. Buka localserver ContactPerson , isikan url dengan http://localhost/ContactPerson/read.php
  20. Untuk mendapatkan tampilan data JSON seperti gambar di atas, anda perlu install JSON VIEWER pada web browser anda. Kemudian tekan Crtrl + U pada URL di atas.
  21. Copy isi source data dalam satu baris dari view-source.
  22. Masuk ke link ini http://jsonschema2pojo.org kemudian paste di kotak yang ada. Isi kolom Package sesuai package pada file ApiEndPoint.java lalu isi Class name dengan ReadResponse .
  23. Lalu klik Zip                                                                                             
  24. Lalu klik tulisan warna biru ( ReadResponse-sources.zip ) untuk mendownload
  25. Extract file nya, sampai ada folder baru dengan nama id
  26. Masuk ke dalam folder id sampai ketemu 2 file berikut
  27. Copy 2 file diatas, lalu paste di dalam folder responses pada Android Studio
  28. Lalu buat file StatusResponse.java di dalam folder responses. Kemudian isi kan code berikut
  29. Ok sekarang anda buka file read.php, kemudian kita ubah lagi code nya ke bentuk awal. Jangan lupa untuk save file nya.                 
  30. Balik lagi keApiEndPoint.java java , isi kan code di bawah ini.
    
    public interface ApiEndPoint {
    
        @FormUrlEncoded
        @POST("read.php")
        Call<ReadResponse> readRequest(@Field("key") String key);
    
        @FormUrlEncoded
        @POST("readPerson.php")
        Call<ReadResponse> readPersonRequest(@Field("key") String key,@Field("id") int id);
    
        @FormUrlEncoded
        @POST("create.php")
        Call<StatusResponse> createRequest(@Field("name") String name,
                                           @Field("contact_number") String contact_number);
    
        @FormUrlEncoded
        @POST("update.php")
        Call<StatusResponse> updateRequest(@Field("id") int id,
                                           @Field("name") String name,
                                           @Field("contact_number") String contact_number);
    
        @FormUrlEncoded
        @POST("delete.php")
        Call<StatusResponse> deleteRequest(@Field("id") int id);
    
    }
    
    

     

0

Membuat Aplikasi CRUD Sederhana di Android Menggunakan PHP dan MySQL PART 1

Posted by:

    1. Aktifkan xampp anda terlebih dahulu. Tekan      pada keyboard anda, lalu ketik xampp .
    2. Klik Start pada Apache serta MySQL
    3. Kemudian buka salah satu Web Browser Anda Google Chrome, Mozilla, dll. Lalu ketik http://localhost/dashboard/ pada link URL anda.
    4. Jika sudah muncul tampilan seperti gambar di atas, klik  phpMyAdmin.
    5. Klik New.
    6. Isikan nama tabel dengan contact_person . Lalu klik Create.
    7. Isikan kolom Name : dengan person serta Number of columns: 3 . Kemudian klik Go.
    8. Isikan struktur tabel seperti gambar dibawah. Kemudian klik Save.
    9. Jika berhasil, maka muncul tampilan seperti ini. 
    10. Sekarang, kita membuat folder untuk Masuk ke folder htdocs anda. Secara default ada di C:\xampp\htdocs . Kemudian buat folder baru dengan nama ContactPerson.
    11. Buka SublimeText anda, lalu masuk ke folder Klik File -> Open Folder … . Pilih Lokasi C:\xampp\htdocs , lalu klik Select Folder.
    12. Sekarang buat file namakan dengan index.php yang berguna untuk menampilkan Tulisan Contact Person API  v.1.0 pada halaman index. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php class ContactPersonApi { public function index() { echo "Contact Person API v.1.0"; } } $contactPersonApi=new ContactPersonApi(); $contactPersonApi->index();
      
      
    13. Sekarang buat file namakan dengan models.php yang berguna untuk melakukan koneksi ke databse, serta CRUD query. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php class database{ //Fungsi constructor untuk membuat koneksi ke database public function __construct(){ $this->db=new PDO('mysql:host=localhost;dbname=contact_person','root','');
      	}
      
      		//Fungsi query untuk mendapatkan data dari database
      	public function getPersons(){
      		$query="SELECT * FROM person ";
      		$sql=$this->db->query($query);
      		return $sql;
      	}
      
      	public function getPerson($Id){
      		$query="SELECT * FROM person  where  id=$Id  LIMIT 1";
      		$sql=$this->db->query($query);
      		return $sql;
      	}
      
      	public function setPerson($Name,$ContactNumber){
      		$query="INSERT into person VALUES(null,'$Name','$ContactNumber')";
      		$sql=$this->db->query($query);
      		return $sql;
      	}
      
      	public function updatePerson($Id,$Name,$ContactNumber){
      		$query="UPDATE person SET person_name='$Name',contact_number='$ContactNumber' where id=$Id";
      		$sql=$this->db->query($query);
      		return $sql;
      	}
      
      	public function deletePerson($Id){
      		$query="DELETE FROM person  where  id=$Id  ";
      		$sql=$this->db->query($query);
      		return $sql;
      	}
      
      }
      
      
    14. Sekarang buat file namakan dengan create.php yang berguna untuk menyimpan data ke database. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php include 'models.php'; //Mengambil Data Dari Android $name=$_REQUEST['name']; $contactNumber=$_REQUEST['contact_number']; //Membuat objek dari class database $MakeConnection=new database(); $MakeConnection->setPerson($name,$contactNumber);
      
      	//mengirim data ke android dengan format JSON 
      echo json_encode(array('status'=>true));
      
      ?>
      
      
    15. Sekarang buat file namakan dengan update.php yang berguna untuk merubah isi data ke database. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php include 'models.php'; //Mengambil Data Dari Android $id=$_REQUEST['id']; $name=$_REQUEST['name']; $contactNumber=$_REQUEST['contact_number']; //Membuat objek dari class database $MakeConnection=new database(); $MakeConnection->updatePerson($id,$name,$contactNumber);
      
      	//mengirim data ke android dengan format JSON 
      echo json_encode(array('status'=>true));
      
      ?>
      
      
    16. Sekarang buat file namakan dengan delete.php yang berguna untuk menghapus isi data dari database. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php include 'models.php'; //Mengambil Data Dari Android $id=$_REQUEST['id']; //Membuat objek dari class database $MakeConnection=new database(); $MakeConnection->deletePerson($id);
      
      	//mengirim data ke android dengan format JSON 
      echo json_encode(array('status'=>true));
      
      ?>
      
      
    17. Sekarang buat file namakan dengan read.php yang berguna untuk mendapatkan semua  data person dari database. Isikan file tersebut dengan soruce code di bawah ini .
      
      <?php include 'models.php'; //Mengambil Data Dari Android $key=$_REQUEST['key']; if (empty($key)) { echo " UnAuthorization User"; }else{ $MakeConnection=new database(); //membuat variable array $jsonResponse=array(); $getObject=$MakeConnection->getPersons();
      	
      	while ($row=$getObject->fetch(PDO::FETCH_OBJ)) {
      		$jsonResponse[]=$row;
      	}
      	
      	//mengirim data ke android dengan format JSON 
      	echo json_encode(array('status'=>true,'persons'=>$jsonResponse));	
      }
      
      ?>
      
      

      18. Sekarang buat file namakan dengan readPerson.php yang berguna untuk mendapatkan semua data person dari database. Isikan file tersebut dengan soruce code di bawah ini .

      
      <php
      include 'models.php';
      
      	//Mengambil Data Dari Android
      $key=$_REQUEST['key'];	
      
      if (empty($key)) {
      	echo " UnAuthorization User";
      }else{
      
      	$MakeConnection=new database();	
      	//membuat variable array
      
      	$jsonResponse=array();
      	$id=$_REQUEST['id'];
      	$getObject=$MakeConnection->getPerson($id);
      	
      	while ($row=$getObject->fetch(PDO::FETCH_OBJ)) {
      		$jsonResponse[]=$row;
      	}
      	
      	//mengirim data ke android dengan format JSON 
      	echo json_encode(array('status'=>true,'persons'=>$jsonResponse));	
      }
      
      ?>
      
      

0

60 Aplikasi Android Untuk Blog Non Komersil

Posted by:

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:

  1. Pembuatan aplikasi android hanya berlaku untuk blog non komersil.
  2. Pembuatan aplikasi android tidak bersifat custom. Hanya mengikuti format aplikasi yang kami tawarkan.
  3. Tidak ada iklan apapun dalam aplikasi.
  4. Gratis upload ke Google Play Store menggunakan akun Rumah Coding.
  5. Hanya untuk 60 blog yang terpilih.
  6. 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:

  1. Mengisi form di bawah paling lambat tanggal 24 Juni 2017.
  2. Blog yang terpilih akan dihubungi secara bertahap melalui whatsapp atau email pada tanggal 1-7 Juli 2017.
  3. Peserta yang terpilih akan diminta melengkapi berbagai macam data untuk keperluan upload ke Google Play Store, seperti icon, deskripsi dan lain-lain.
  4. Proses pembuatan dan upload ke Google Play Store secara bertahap pada tanggal 8-15 Juli 2017

 

0

Menampilkan Data dari MySQL ke Dalam List View Pada Android Menggunakan PHP

Posted by:

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.

var json = {
    'title' : 'Facebook',
    'rating' : 5,
    'total_dl' : 10990998,
    'icon' : 'facebook'
};

Sebuah array dari JSON merupakan serangkaian object JSON. Di bawah ini merupakan contoh array dari beberapa objek JSON di atas.

var json = [
    {'title' : 'Facebook',
    'rating' : 5,
    'total_dl' : 10990998,
    'icon' : 'facebook'},
    {'title' : 'Twitter',
    'rating' : 5,
    'total_dl' : 12343487,
    'icon' : 'twitter'},
    {'title' : 'Whatsapp',
    'rating' : 4,
    'total_dl' : 5635989,
    'icon' : 'whatsapp'}
    ];

 

Konsep Dasar

 

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

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

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.

<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=".MainActivity" >

    <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

 

2. Create Custom List View Layout File

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.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

    <ImageView android:id="@+id/appIcon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="3dp" android:layout_marginTop="3dp" android:src="@drawable/facebook" />
    <TextView android:id="@+id/titleTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/appIcon" android:layout_toRightOf="@id/appIcon" android:layout_marginLeft="3dp" android:text="Application Title" android:textSize="22dp"/>

    <LinearLayout android:id="@+id/ratingCntr" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/appIcon" android:layout_below="@id/titleTxt" android:layout_marginLeft="5dp" >
    </LinearLayout>

    <TextView android:id="@+id/dlTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/titleTxt" android:layout_alignParentRight="true" android:layout_marginRight="3dp" android:text="0 dl" />    

</RelativeLayout>

 

3. Create Application Value Object File

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.

package com.sj.jsondemo;

import java.text.NumberFormat;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ApplicationAdapter extends ArrayAdapter<Application>{
    private List<Application> items;
    
    public ApplicationAdapter(Context context, List<Application> items) {
        super(context, R.layout.app_custom_list, items);
        this.items = items;
    }
    
    @Override
    public int getCount() {
        return items.size();
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        
        if(v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.app_custom_list, null);            
        }
        
        Application app = items.get(position);
        
        if(app != null) {
            ImageView icon = (ImageView)v.findViewById(R.id.appIcon);
            TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
            LinearLayout ratingCntr = (LinearLayout)v.findViewById(R.id.ratingCntr);
            TextView dlText = (TextView)v.findViewById(R.id.dlTxt);
            
            if(icon != null) {
                Resources res = getContext().getResources();
                String sIcon = "com.sj.jsondemo:drawable/" + app.getIcon();
                icon.setImageDrawable(res.getDrawable(res.getIdentifier(sIcon, null, null)));
            }
            
            if(titleText != null) titleText.setText(app.getTitle());
            
            if(dlText != null) {
                NumberFormat nf = NumberFormat.getNumberInstance();
                dlText.setText(nf.format(app.getTotalDl())+" dl");            
            }
            
            if(ratingCntr != null && ratingCntr.getChildCount() == 0) {        
                /*
                 * max rating: 5
                 */
                for(int i=1; i<=5; i++) {
                    ImageView iv = new ImageView(getContext());
                    
                    if(i <= app.getRating()) {
                        iv.setImageDrawable(getContext().
                        getResources().getDrawable(R.drawable.start_checked));
                    }
                    else {                
                        iv.setImageDrawable(getContext().
                        getResources().getDrawable(R.drawable.start_unchecked));
                    }
                    
                    ratingCntr.addView(iv);
                }
            }
        }
        
        return v;
    }
}

 

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.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sj.jsondemo" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name="com.sj.jsondemo.MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

0

Building Simple Image Slider Using Pure CSS3

Posted by:

CSS is an acronym for Cascading Style Sheets, it is used to format web page look. The latest version of CSS is CSS3. This new version of CSS gives web developers more flexibility when styling the webpage. It comes with a set of new rules that make CSS3 better than the old version. CSS3 provides way to create an animation. In this tutorial, we’ll build simple image slider using pure CSS3.

CSS Overview

Before we start into deep explanation to create the slider, I’ll give some overview of CSS feature that is used to create the slider.

    1. Transform Property
      The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.
    2. :target Selector

URLs with an # followed by an anchor name, link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element.

    1. :before and :after Selector
      The :before selector inserts content before the selected element(s). The :after selector inserts content after the selected element(s).
    2. ~ (Tilde Selector)

Tilde selector also called general sibling combination. The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that that the element being selected doesn’t need immediately succeed the first element, but can appear anywhere after it.

  1. Vendor Specific Property
    In order to make our slider runs cross browser, we must add vendor specific property by adding the following prefix into several CSS properties:

    • -moz-: Mozila Firefox
    • -webkit-: Safari, Chrome (and other WebKit-based browsers)
    • -ms-: Microsoft
    • -o-: Opera

Prepare the Stage

The stage of the slider is a div HTML tag where the slider takes place. We’ll create the stage which have 640px x 320px dimensions. The following HTML tags define the slider stage. We give id [cci]slider[/cci] to the stage.

<html>
<head>
    <title>CSS3 Image Slider</title>
</head>
<body>
    <div id="slider"></div>
</body>
</html>

 

Give Style to the Stage

After the stage has been created, now it’s time to give a style to the stage. At this step, we give dimension, margin, background and shadow to the stage.

#slider {
    width: 640px;
    height: 320px;
    margin: 50px auto 0;
    position: relative;
    background: #fff;

    /* give shadow to the stage*/
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
}

Now, our stage looks like below image.

Stage Preview

Stage Preview

Add Drop Shadow Effect at the Bottom of Stage

We’ll add a drop shadow effect to the stage at the bottom left and bottom right. The drop shadow that we used is simply a blank div element with the following style.

#slider:before, #slider:after {
    content: '';
    position: absolute;
    width: 60%;
    height: 20px;
    
    /* Adding shadow to this content*/
    -webkit-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
    -moz-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
    -ms-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
    -o-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);        
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
    
    /* Transform the content*/
    -webkit-transform: rotate(-4deg) skew(-10deg);
    -moz-transform: rotate(-4deg) skew(-10deg);
    -o-transform: rotate(-4deg) skew(-10deg);
    -ms-transform: rotate(-4deg) skew(-10deg);
    transform: rotate(-4deg) skew(-10deg);
    
    left: 10px;
    bottom: 13px;
    z-index: -1;
}

Move the second drop shadow to the right.

#slider:after {
    left: auto;
    right: 10px;
    
    -webkit-transform: rotate(4deg) skew(10deg);
    -moz-transform: rotate(4deg) skew(10deg);
    -o-transform: rotate(4deg) skew(10deg);
    -ms-transform: rotate(4deg) skew(10deg);
    transform: rotate(4deg) skew(10deg);
}

Now, the stage looks like below image:

Drop Shadow on Stage

Drop Shadow on Stage

Add Control Button

Control buttons is a set of buttons to control the slider. The button is used as a transition trigger for the slider. If user click a button, the slider will change the image on the stage.

<html>
<head>
    <title>CSS3 Image Slider</title>
</head>
<body>
    <div id="slider"></div>
    
    <!-- Control buttons! -->
	<ul>
		<li>
			<a href="#one"></a>
		</li>
		<li>
			<a href="#two"></a>
		</li>
		<li>
			<a href="#three"></a>
		</li>
		<li>
			<a href="#four"></a>
		</li>
		<li>
			<a href="#five"></a>
		</li>
	</ul>
</body>
</html>

Add style to control buttons.

#slider ul {
    width: 140px;
    height: 40px;
    padding: 0 0 0 0;
    position: absolute;
    z-index: 10;
    list-style: none;
    left: 50%;
    margin-left: -70px;
    bottom: -60px;
}

#slider ul li:first-child {
    margin-left: 16px;
}

#slider ul li {
    float: left;
    margin-right: 12px;
    margin-top: 14px;
}

#slider ul li:last-child {
    margin-right: 0;
}

#slider ul li a {
    width: 12px;
    height: 12px;
    display: block;
    outline: none;
    border: none;
    position: relative;
    z-index: 2;
    background: #aaa;
    
    box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
    -moz-box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
    -webkit-box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
    
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
}

#slider ul li a:hover {
    background: #888;
}

Now, our slider will look like image bellow.

Style Control Button

Style Control Button

Add images

Images is the heart of our slider. You can download the images we used in this tutorial by downloading source code. The donwload button is located on the top.

<html>
<head>
    <title>CSS3 Image Slider</title>
</head>
<body>
    <!-- Images -->
    <img id="one" src="1.jpg" />
	<img id="two" src="2.jpg" />
	<img id="three" src="3.jpg" />
	<img id="four" src="4.jpg" />
	<img id="five" src="5.jpg" />
    
    <div id="slider"></div>
    
    <!-- Control buttons! -->
	<ul>
		<li>
			<a href="#one"></a>
		</li>
		<li>
			<a href="#two"></a>
		</li>
		<li>
			<a href="#three"></a>
		</li>
		<li>
			<a href="#four"></a>
		</li>
		<li>
			<a href="#five"></a>
		</li>
	</ul>
</body>
</html>

Now, we give style to the images.

#slider img {
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
    
    /* scale images*/
    -webkit-transform: scale(1.2);
    -moz-transform: scale(1.2);
    -ms-transform: scale(1.2);
    -o-transform: scale(1.2);
    transform: scale(1.2);
    
    /* set transition*/
    -webkit-transition: all .5s ease;
    -moz-transition: all .5s ease;
    -ms-transition: all .5s ease;
    -o-transition: all .5s ease;
    transition: all .5s ease;
}

 

Make The Image Slidding When Control Button Clicked

We’ll make the slider to change active image by using :target property

#slider img:target {
    opacity: 1;        
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1);
}
#slider img:not(:target){
    opacity: 0;
    
    -webkit-transform: scale(1.2);        
    -moz-transform: scale(1.2);        
    -ms-transform: scale(1.2);        
    -o-transform: scale(1.2);        
    transform: scale(1.2);        
}

 

Make The Control Buttons Selected When The Button Clicked

#one:target ~ ul li a[href="#one"],
#two:target ~ ul li a[href="#two"],
#three:target ~ ul li a[href="#three"],
#four:target ~ ul li a[href="#four"],
#five:target ~ ul li a[href="#five"] {
    background: #777;
}
#two:target ~ ul li a[href="#one"],
#three:target ~ ul li a[href="#one"],
#four:target ~ ul li a[href="#one"],
#one:target ~ ul li a[href="#one"] {
    background: #aaa;
}

 

Make First Image Appear When Page Loaded

#slider img#one {
    opacity: 1;
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    -o-transform: scale(1);
    transform: scale(1);
}
#slider ul li a[href="#one"] {
    background: #777;
}
Final Image Slider

Final Image Slider

 

Final Source Codes

Below the final source codes. Save it as HTML file and open it on your favorite browser.

<html>
<head>
    <title>CSS3 Image Slider</title>    
    <style>
    body {
        padding: 0;
        margin: 0;
        background: #ccc;
    }
    
    #slider {
        width: 640px;
        height: 320px;
        margin: 50px auto 0;
        position: relative;
        background: #fff;

        box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
        -moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
        -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2);
    }

    #slider:before, #slider:after {
        content: '';
        position: absolute;
        width: 60%;
        height: 20px;
        
        -webkit-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
        -moz-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
        -ms-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
        -o-box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);        
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.5);
        
        -webkit-transform: rotate(-4deg) skew(-10deg);
        -moz-transform: rotate(-4deg) skew(-10deg);
        -o-transform: rotate(-4deg) skew(-10deg);
        -ms-transform: rotate(-4deg) skew(-10deg);
        transform: rotate(-4deg) skew(-10deg);
        
        left: 10px;
        bottom: 13px;
        z-index: -1;
    }

    #slider:after {
        left: auto;
        right: 10px;
        
        -webkit-transform: rotate(4deg) skew(10deg);
        -moz-transform: rotate(4deg) skew(10deg);
        -o-transform: rotate(4deg) skew(10deg);
        -ms-transform: rotate(4deg) skew(10deg);
        transform: rotate(4deg) skew(10deg);
    }

    #slider ul {
        width: 140px;
        height: 40px;
        padding: 0 0 0 0;
        position: absolute;
        z-index: 10;
        list-style: none;
        left: 50%;
        margin-left: -70px;
        bottom: -60px;
    }

    #slider ul li:first-child {
        margin-left: 16px;
    }

    #slider ul li {
        float: left;
        margin-right: 12px;
        margin-top: 14px;
    }

    #slider ul li:last-child {
        margin-right: 0;
    }

    #slider ul li a {
        width: 12px;
        height: 12px;
        display: block;
        outline: none;
        border: none;
        position: relative;
        z-index: 2;
        background: #aaa;
        
        box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
        -moz-box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
        -webkit-box-shadow: inset 0 1px 1px 0px rgba(0, 0, 0, 0.6), 0px 1px 1px 0px white;
        
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        border-radius: 50%;
    }

    #slider ul li a:hover {
        background: #888;
    }

    #slider img {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        
        -webkit-transform: scale(1.2);
        -moz-transform: scale(1.2);
        -ms-transform: scale(1.2);
        -o-transform: scale(1.2);
        transform: scale(1.2);
        
        -webkit-transition: all .5s ease;
        -moz-transition: all .5s ease;
        -ms-transition: all .5s ease;
        -o-transition: all .5s ease;
        transition: all .5s ease;
    }

    #slider img:target {
        opacity: 1;        
        -webkit-transform: scale(1);
        -moz-transform: scale(1);
        -ms-transform: scale(1);
        -o-transform: scale(1);
        transform: scale(1);
    }
    
    #slider img#one {
        opacity: 1;
        -webkit-transform: scale(1);
        -moz-transform: scale(1);
        -ms-transform: scale(1);
        -o-transform: scale(1);
        transform: scale(1);
    }
    
    #slider img:not(:target){
        opacity: 0;
        
        -webkit-transform: scale(1.2);        
        -moz-transform: scale(1.2);        
        -ms-transform: scale(1.2);        
        -o-transform: scale(1.2);        
        transform: scale(1.2);        
    }

    #slider ul li a[href="#one"] {
        background: #777;
    }

    #one:target ~ ul li a[href="#one"],
    #two:target ~ ul li a[href="#two"],
    #three:target ~ ul li a[href="#three"],
    #four:target ~ ul li a[href="#four"],
    #five:target ~ ul li a[href="#five"] {
        background: #777;
    }

    #two:target ~ ul li a[href="#one"],
    #three:target ~ ul li a[href="#one"],
    #four:target ~ ul li a[href="#one"],
    #five:target ~ ul li a[href="#one"] {
        background: #aaa;
    }
    </style>
</head>
<body>
    <div id="slider">
	
	<!-- Images -->
	<img id="one" src="1.jpg" />
	<img id="two" src="2.jpg" />
	<img id="three" src="3.jpg" />
	<img id="four" src="4.jpg" />
	<img id="five" src="5.jpg" />
	
	<!-- Control buttons! -->
	<ul>
		<li>
			<a href="#one"></a>
		</li>
		<li>
			<a href="#two"></a>
		</li>
		<li>
			<a href="#three"></a>
		</li>
		<li>
			<a href="#four"></a>
		</li>
		<li>
			<a href="#five"></a>
		</li>
	</ul>
</div>
</body>
</html>

0

Using Android Async Task to Perform Background Operations

Posted by:

Async Task is an android helper class that will allows you to run a background processes. If you are a Java programmer, may be you are familiar with thread. If you run a long task in the main thread, the current user interface will be blocked untill the task has finished. This is not a good practice. To avoid the user interface is being blocked, the long task must be perform in another thread.

Async Task Overview

In android, the only thread that can modify the user interface is called UI thread. This is means you can’t modify user interface from another thread. This is a problem, because in another side, we need to run a long task in separate thread and also we need to update the user interface to display the task progress. Actually, android provides a [cci]Handler[/cci] class that allows you to update the user interface from another thread. But we’ll discuss it in the next tutorial.

Rather than create new thread and handler, android has provides a helper class, [cci]AsyncTask[/cci], to do the same thing. The concept is same, [cci]AsyncTask[/cci] is a smart helper that encapsulates the creation of thread and handler.

[cci]AsyncTask[/cci] must be subclassed to be used. There are three methods that need to be overridden, [cci]doInbackground[/cci], [cci]onProgressUpdate[/cci] and [cci]onPostExecute[/cci]. The first method is mandatory to be overriden, the rest are optional.

[cci]doInbackground[/cci] is a method where the execution codes is placed. [cci]doProgressUpdate[/cci] and [cci]onPostExecute[/cci] run in UI thread, so user interface can be modified in both of methods. Put any codes for displaying the task progress on [cci]doProgressUpdate[/cci]. The [cci]doPostExecute[/cci] method will be called once the task has finished.

[cci]AsyncTask[/cci] is a generic class. [cci]AsyncTask[/cci] is subclassed in the form [cci]AsyncTask<Params, Progress, Result>[/cci].

  1. [cci]Params[/cci], the type of the parameters sent to the task upon execution.
  2. [cci]Progress[/cci], the type of the progress units published during the background computation.
  3. [cci]Result[/cci], the type of the result of the background computation.

To give a better understanding, a sample application that use [cci]AsyncTask[/cci] will be given.

Creating Sample Application

We’ll create a sample application to demonstrate the use of [cci]AsyncTask[/cci] class to perform background processes. Our goal is to create a simple application which download a file from server and display the download progress in the progress bar.

Our application have very simple user interface that only contains a progress bar and a button.

AsyncTask Simple Application

AsyncTask Simple Application

If user click Start Button above, the application will start download a file from server and display the progress in progress bar. After the download process has completed, the file is saved into android root folder (/sdcard).

In this demonstration, I will use a file located on my server, http://semurjengkol.com/dl/files/CustomArrayAdapter.rar(445KB), this is an eclipse project from previous tutorial. You can also use this file or change the url as you want.

Now, open your Eclipse IDE and create new Android Application Project, then follow step by step below:

  1. Create new layout file [cci]res/layout/activity_main.xml[/cci] This file defines the application main layout which contain a progress bar and a button.
<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"
    android:orientation="vertical"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="100"
        android:progress="0" />

    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/start_download" />

</LinearLayout>

The resource [cci]@string/start_download[/cci] we used above is defined in strings resources [cci]res/values/strings.xml[/cci]

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AsyncTaskSample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="start_download">Start Download</string>
</resources>
  • Create new java class [cci]src/DownloadListener.java[/cci] This is a listener that will be used by [cci]AsyncTask[/cci] to communicate with activity to change the user interface.

    package com.sj.asynctask;
    
    import java.io.File;
    
    public interface DownloadListener {
        public void onDownloadComplete(File filename);
        public void onProgressUpdate(int progress);
        public void onDownloadFailure(final String msg);
    }
    
  • Create new java class [cci]src/DownloadTask.java[/cci] This file extends [cci]AsyncTask[/cci] and will do the download task and call the listener to display the progress result. The [cci]doInBackground[/cci] method retrieves two string parameters:

    1. URL of the file to be downloaded
    2. The destination storage location to save the file
    package com.sj.asynctask;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    import android.os.AsyncTask;
    import android.os.Environment;
    
    public class DownloadTask extends AsyncTask<String, Integer, Boolean> {
        /** This is our listener*/
        private final DownloadListener listener;
        /** Hold message if download failure*/
        private String msg;
        /** Save Destination */
        private File saveTo; 
        
        public DownloadTask(DownloadListener listener) {
            this.listener = listener;
        }
        
        @Override
        protected Boolean doInBackground(String... params) {
            /** Params should be array of string with length 2. 
             * 1. url
             * 2. filename destination*/
            if(params == null || params.length < 2) {
                msg = "Incomplete parameters";
                return false;
            }
            
            String sUrl = params[0];
            String filename = params[1]; 
    
            /** get root directory: /sdcard */
            File rootDir = Environment.getExternalStorageDirectory(); 
            /** create destination file*/
            saveTo = new File(rootDir, filename);
        
            try {
                /** define url*/
                URL url = new URL(sUrl);
                /** open the connection*/
                URLConnection conn = url.openConnection();
                conn.connect();
                
                /** get the size of file that will be downloaded. It will be used to measure the progress*/
                int fileLength = conn.getContentLength(); 
                
                /** create input and outpout stream*/
                InputStream is = new BufferedInputStream(url.openStream());
                OutputStream os = new FileOutputStream(saveTo);
                
                /** create buffer*/
                byte buffer[] = new byte[512];
                /** hold total of downloaded bytes*/
                long totalDownloaded = 0;
                int count;
                
                while ((count = is.read(buffer)) != -1) {
                    totalDownloaded += count;
                    
                    /**cause call to onProgressUpdate, which is run on UI thread*/
                    publishProgress((int) (totalDownloaded * 100 / fileLength));                 
                    os.write(buffer, 0, count);
                }
                
                /** closing stream*/
                os.flush();
                os.close();
                is.close();
                return true;
            } 
            catch (MalformedURLException e) {
                msg = "Invalid URL";
            }
            catch (IOException e) {
                msg = "No internet connection";
            }
            
            return false;
        }
        
        @Override
        protected void onProgressUpdate(Integer... values) {
            if(listener != null) listener.onProgressUpdate(values[0]);
        }
        
        @Override
        protected void onPostExecute(Boolean result) {
            if(!result) {
                if(listener != null) listener.onDownloadFailure(msg);
                return;
            } 
            
            if(listener != null) listener.onDownloadComplete(saveTo);
        }
    }
    

 

  • Create main activity [cci]src/MainActivity.java[/cci] This is our main activity that will inflate the [cci]res/layout/activity_main.xml[/cci] to build our main user interface. The activity will create and execute [cci]DownloadTask[/cci] object when Start Button is clicked. Our activity also implements the [cci]DownloadListener[/cci] and set itself as a listener to [cci]DownloadTask[/cci] object. The [cci]DownloadTask[/cci] object will call the listener method implementation in the activity when the progress updated, download failure and when download completed.

    package com.sj.asynctask;
    
    import java.io.File;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    
    public class MainActivity extends Activity implements OnClickListener, DownloadListener{
        private ProgressBar progressBar;
        private Button startButton;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
        }
        
        private void initView() {
            progressBar = (ProgressBar) findViewById(R.id.progress_bar);
            startButton = (Button)findViewById(R.id.start_button);
            
            if(startButton != null) startButton.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.start_button:
                /** file url to be downloaded*/
                String url = "http://semurjengkol.com/dl/files/CustomArrayAdapter.rar";
                /** destination filename*/
                String filename = "CustomArrayAdapter.rar";
                
                if(startButton != null) startButton.setEnabled(false);
                
                DownloadTask task = new DownloadTask(this);
                task.execute(url, filename);
                break;
            default:
                break;
            }        
        }
    
        @Override
        public void onDownloadComplete(File filename) {
            if(filename != null) {
                Toast.makeText(this, "Download complete. File is saved to " + filename.getPath(), 
                        Toast.LENGTH_LONG).show();
            }
            
            if(startButton != null) startButton.setEnabled(true);
        }
    
        @Override
        public void onProgressUpdate(int progress) {
            if(progressBar != null) progressBar.setProgress(progress);
        }
    
        @Override
        public void onDownloadFailure(String msg) {
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
            if(progressBar != null) progressBar.setProgress(0);
            if(startButton != null) startButton.setEnabled(true);
        }
    }
    
  • Adding permission to [cci]AndroidManifest.xml[/cci] This simple application has two main features:

    • Connecting to internet to download a file
    • Save the file into sdcard storage

    In order to our application runs well, we must add [cci]uses-permission[/cci] in our [cci]AndroidManifest.xml[/cci] related to above features. Add the following lines into [cci]AndroidManifest.xml[/cci]:

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

    Below is our final [cci]AndroidManifest.xml[/cci]:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.sj.asynctask"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET" />
        
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.sj.asynctask.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    

Now run the project and click the start button, it will download the file and display the progress on the progress bar

Async Task Download Progress

Async Task Download Progress

0

Using Custom Array Adapter on Android List View

Posted by:

List View is an element that displays a collection of items in single column direction. It has an internal vertical scroll bar that enable user to scroll if it’s height bigger than display height. The type of single item in the list is any of java object.

[cci]ListView[/cci] needs an adapter to works. This adapter behaves as a data resources for the list. The adapter also defines how each items in the list is displayed. The adapter is attached to the list via [cci]setAdapter[/cci] method on the [cci]ListView[/cci] object. There are two commons used adapters:

  • Array Adapter: An adapter that is designed to work with arrays data resources.
  • Cursor Adapter: An adapter that is designed to handle database related data.

This tutorial will focuses on array adapter.

Simple Array Adapter

A simple array adapter is an array adapter that is built using array of string as items. The array of string is passed to the constructor of [cci]ArrayAdapter[/cci] object.

List<String> apps = new ArrayList<String>();
apps.add("Twitter");
apps.add("Whatsapp");
apps.add("Facebook");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, apps);

The constructor of array adapter have 3 arguments:

  1. context: this is the application context
  2. layout resource id: the layout resource id for item view
  3. array items: this is array object for items

We will attach the created adapter into the list by using [cci]setAdapter[/cci] method on [cci]ListView[/cci] object.

List Activity

[cci]ListActivity[/cci] is a subclass of [cci]Activity[/cci] that will make our work with [cci]ListView[/cci] easier. [cci]ListActivity[/cci] has internal implementation method that is related to [cci]ListView[/cci]. You must have list view object with id is [cci]android:id/list[/cci] in the layout file to use List Activity.

<ListView
   android:id="@android:id/list"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" >
</ListView>

Now we will create a sample list view application using simple array adapter. Open your Eclipse IDE and create new android project by selecting menu: File -> New -> Android Application Project. Fill out required fields.

    1. Create new xml file: [cci]activity_main.xml[/cci]
      <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" >
      
          <ListView
              android:id="@android:id/list"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">
          </ListView>
      
      </LinearLayout>
      
    2. Create new activity class: [cci]MainActivity.java[/cci]
      package com.sj.customlistview;
      
      import java.util.ArrayList;
      import java.util.List;
      
      import android.app.ListActivity;
      import android.os.Bundle;
      import android.widget.ArrayAdapter;
      
      public class MainActivity extends ListActivity{    
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);        
              setContentView(R.layout.activity_main);        
              initView();   
          }
      
          private void initView() {
              List<String> apps = new ArrayList<String>();
              apps.add("Twitter");
              apps.add("Whatsapp");
              apps.add("Facebook");
              ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, apps);
              setListAdapter(adapter);
          }
      }
      
    3. Put your activity in [cci]AndroidManifest.xml[/cci] file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sj.customlistview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sj.customlistview.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Run your project, your list view will be displayed like image below:

Simple Android List View

Simple Android List View


 

Customize Array Adapter

By default, array adapter displays a [cci]TextView[/cci] for each items and set the text of it by calling [cci]toString[/cci] method of item object. We can customize the default display of array adapter by overriding [cci]getView[/cci] method.
For a demo, we will modify previous project and use custom array adapter:

  1. Create new java class: [cci]Application.java[/cci].
    This class represents a single object of list item.

    package com.sj.customlistview;
    
    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;
        }
    }
    
  2. Create new xml file: [cci]app_custom_list.xml[/cci] This file defines a view for list item

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <ImageView
            android:id="@+id/appIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"        
            android:layout_marginLeft="3dp"
            android:layout_marginTop="3dp"
            android:src="@drawable/facebook" />
        <TextView
            android:id="@+id/titleTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/appIcon"
            android:layout_toRightOf="@id/appIcon"
            android:layout_marginLeft="3dp"
            android:text="Application Title"
            android:textSize="22dp"/>
    
        <LinearLayout
            android:id="@+id/ratingCntr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/appIcon"
            android:layout_below="@id/titleTxt"
            android:layout_marginLeft="5dp" >
        </LinearLayout>
    
        <TextView
            android:id="@+id/dlTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/titleTxt"
            android:layout_alignParentRight="true"
            android:layout_marginRight="3dp"
            android:text="0 dl" />    
    </RelativeLayout>
    
  3. Create new java class: [cci]AppAdapter.java[/cci] This is our adapter that will inflate [cci]app_custom_list.xml[/cci] and set the data into it.

    package com.sj.customlistview;
    
    import java.text.NumberFormat;
    import java.util.List;
    
    import android.content.Context;
    import android.content.res.Resources;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    
    public class AppAdapter extends ArrayAdapter<Application>{
        private List<Application> items;
        
        public AppAdapter(Context context, List<Application> items) {
            super(context, R.layout.app_custom_list, items);
            this.items = items;
        }
        
        @Override
        public int getCount() {
            return items.size();
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            
            if(v == null) {
                LayoutInflater li = LayoutInflater.from(getContext());
                v = li.inflate(R.layout.app_custom_list, null);            
            }
            
            Application app = items.get(position);
            
            if(app != null) {
                ImageView icon = (ImageView)v.findViewById(R.id.appIcon);
                TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
                LinearLayout ratingCntr = (LinearLayout)v.findViewById(R.id.ratingCntr);
                TextView dlText = (TextView)v.findViewById(R.id.dlTxt);
                
                if(icon != null) {
                    Resources res = getContext().getResources();
                    String sIcon = "com.sj.customlistview:drawable/" + app.getIcon();
                    icon.setImageDrawable(res.getDrawable(res.getIdentifier(sIcon, null, null)));
                }
                
                if(titleText != null) titleText.setText(app.getTitle());
                
                if(dlText != null) {
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    dlText.setText(nf.format(app.getTotalDl())+" dl");            
                }
                
                if(ratingCntr != null && ratingCntr.getChildCount() == 0) {        
                    /*
                     * max rating: 5
                     */
                    for(int i=1; i<=5; i++) {
                        ImageView iv = new ImageView(getContext());
                        
                        if(i <= app.getRating()) {
                            iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_checked));
                        }
                        else {                
                            iv.setImageDrawable(getContext().getResources().getDrawable(R.drawable.start_unchecked));
                        }
                        
                        ratingCntr.addView(iv);
                    }
                }
            }
            
            return v;
        }
    }
    
  4. Open your [cci]MainActivity.java[/cci] and modify several lines.
    package com.sj.customlistview;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import android.app.ListActivity;
    import android.os.Bundle;
    
    public class MainActivity extends ListActivity{    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);        
            setContentView(R.layout.activity_main);        
            initView();   
        }
    
        private void initView() {
            List<Application> apps = populateSampleApplication();
            AppAdapter adapter = new AppAdapter(this, apps);
            setListAdapter(adapter);        
        }
        
        private List<Application> populateSampleApplication(){        
            String[] apps = new String[] {                
                "Twitter,450000,5,twitter",
                "Skype,300002,2,skype",
                "Facebook,500560,4,facebook"
            };
            
            List<Application> list = new ArrayList<Application>();
            
            for(String app:apps) {
                String[] rApp = app.split(","); 
                Application ap = new Application();
                ap.setTitle(rApp[0]);
                ap.setTotalDl(Integer.parseInt(rApp[1]));
                ap.setRating(Integer.parseInt(rApp[2]));
                ap.setIcon(rApp[3]);
                list.add(ap);
            }
            
            return list;
        }
    }
    

I’ve used some social icons in this project. You can download the icons here: social icons
Now run your project, it will display list view below:

Custom Array Adapter

Custom Array Adapter

0

Android Gravity and Layout Gravity

Posted by:

Gravity is an android method for aligning view in a layout. There are two kinds of gravity, gravity and layout gravity. Basically a gravity is set in xml layout files, but you can also set a gravity of any view in java source code. To set gravity in xml use [cci]android:layout_gravity[/cci] and [cci]android:gravity[/cci] attributes. The values of both attributes is combination of the following constants:

top : Push object to the top of its container, not changing its size.
bottom : Push object to the bottom of its container, not changing its size.
left : Push object to the left of its container, not changing its size.
right : Push object to the right of its container, not changing its size.
center_vertical : Place object in the vertical center of its container, not changing its size.
fill_vertical : Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal : Place object in the horizontal center of its container, not changing its size.
fill_horizontal : Grow the horizontal size of the object if needed so it completely fills its container.
center : Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill : Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical : Additional option that can be set to have the top and/or bottom edges of the child clipped to its container’s bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
clip_horizontal : Additional option that can be set to have the left and/or right edges of the child clipped to its container’s bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.
start : Push object to the beginning of its container, not changing its size.
end : Push object to the end of its container, not changing its size.

 

android:gravity attribute

[cci]android:gravity[/cci] will set alignment to the content of a view. This aligment will only take effect if size of view is bigger than view’s content. Maybe you got confuse, what is the different between view and view content. Consider a button view below.

Button View

Button View

As you can see from image above, the button view is the rectangle boundary of a button, while the content of the button view is the text “button” it self.

Now, we will align the content of the button to bottom right of the button. To align content to bottom right we add [cci]android:gravity=”bottom|right”[/cci] attribute.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:text="Button"
        android:gravity="bottom|right" />

</LinearLayout>

Will result as follow:

Content of button view aligned to bottom right

Content of button view aligned to bottom right

android:layout_gravity attribute

[cci]android:layout_gravity[/cci] is used to align view child to its parent. Note that this attribute will only take effect if the parent is [cci]LinearLayout[/cci] and the size of child smaller than parent size.


 

Now we will align a button to the right of parent. To do this, we must add [cci]android:layout_gravity=”right”[/cci] attribute.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="right" />

</LinearLayout>

The result is as follow:

Button view is aligned to right

Button view is aligned to right

0

Advance Android Relative Layout Example

Posted by:

Relative Layout is an android view group to align all childrens relative to other view or its parent. Relative layout give you flexibiliy to place childs wherever you want. In the previous example, I have give some basic example of Relative Layout. Now, I will give you how to create a more complex relative layout example.

Our goal is to create layout like this:

Advance relative layout example

Advance relative layout example

See the following step by step to create above layout:

1. Aligning child to top left of parent

Actually, by default every childs is aligned to top left of parent in relative layout. So we needn’t add any special attribute to align chilc in top left of parent. But you can align child to top left of parent by adding [cci]android:layout_alignParentLeft=”true”[/cci] and [cci]android:layout_alignParentTop=”true”[/cci] attributes.

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

 

2. Aligning child in top right of parent

To align child in top right of parent, add the following attributes [cci]android:layout_alignParentRight=”true”[/cci] and [cci]android:layout_alignParentTop=”true”[/cci].

<Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

 

3. Aligning child in bottom left of parent

To align child in bottom left of parent, add the following attributes [cci]android:layout_alignParentBottom=”true”[/cci] and [cci]android:layout_alignParentLeft=”true”[/cci].

<Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" />

 

4. Aligning child in bottom right of parent

To align child in bottom right of parent, add the following attributes [cci]android:layout_alignParentBottom=”true”[/cci] and [cci]android:layout_alignParentRight=”true”[/cci].

<Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true" />

 

5. Align child in the center of parent

This is our center child and you must give it an [cci]id[/cci] as our other 4 childs aligned relative this child. To align a child center of the parent, add the following attribute [cci]android:layout_centerInParent=”true”[/cci]. This attribute will align our child center to the parent, vertically and horizontally.

<Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button5"
        android:layout_centerInParent="true"/>

 

6. Align child in top left of the center child

To align child in top left of the center child, add the following attributes [cci]android:layout_toLeftOf=”@id/button5″[/cci] and [cci]android:layout_above=”@id/button5″[/cci].

<Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button6"
        android:layout_toLeftOf="@id/button5"
        android:layout_above="@id/button5"/>

 


 

7. Align child in top right of the center child

To align child in top right of the center child, add the following attributes [cci]android:layout_toRightOf=”@id/button5″[/cci] and [cci]android:layout_above=”@id/button5″[/cci].

<Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button6"
        android:layout_toRightOf="@id/button5"
        android:layout_above="@id/button5"/>

 

8. Align child in bottom right of the center child

To align child in bottom right of the center child, add the following attributes [cci]android:layout_toRightOf=”@id/button5″[/cci] and [cci]android:layout_below=”@id/button5″[/cci].

<Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button6"
        android:layout_toRightOf="@id/button5"
        android:layout_below="@id/button5"/>

 

9. Align child in bottom left of the center child

To align child in bottom left of the center child, add the following attributes [cci]android:layout_toLeftOf=”@id/button5″[/cci] and [cci]android:layout_below=”@id/button5″[/cci].

<Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button6"
        android:layout_toLeftOf="@id/button5"
        android:layout_below="@id/button5"/>

 

Final Source Codes

Below is the final source codes:

<RelativeLayout 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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button3"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button4"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true" />
    
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button5"
        android:layout_centerInParent="true"/>
    
    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button6"
        android:layout_toLeftOf="@id/button5"
        android:layout_above="@id/button5"/>
    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button7"
        android:layout_toRightOf="@id/button5"
        android:layout_above="@id/button5"/>
    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button8"
        android:layout_toRightOf="@id/button5"
        android:layout_below="@id/button5"/>
    <Button
        android:id="@+id/button9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button9"
        android:layout_toLeftOf="@id/button5"
        android:layout_below="@id/button5"/>
</RelativeLayout>

0
Page 1 of 2 12