Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Thursday, October 6, 2011

Android Programming - Luas Bangun

I created (actually it based on someone tutorial and I modified it in some place, I can find the original link..) this very simple program to learn more about User Interface. How to layout, using Button, TextView and Edit Text. It is so simple, the function is to calculate the area of square, traingle and circle. User input the width, height or radius, and then the app calculate the area and show the result in a TextView.
Check out the source code in my GitHub. Here is the link.
1. As ussual create new project, I named it Luas Bangun, with LuasBangunActivity as a main activity.
2. Prepare AndroidManifest, create 3 new Activity from there, named it HitungLingkaran (for circle), HitungSegitiga (for triangle) and HitungPersegiPanjang (for square).
3. Let's begin templating. First create layout for LuasBangunActivity. It is in the main.xml file. You need to create three other XML file, one for each, lingkaran.xml (circle area), persegipanjang.xml (square area) and segitiga.xml (triangle area).
4. And then code the MainActivity. It is used for main screen, giving a link to another activity and exiting from application.
5. The lingkaran, persegipanjang and segitiga do not have any difference in programming structure, it is same, the difference is just the algorithm to calculate the area, and I think it will be easy, you know it from since elementary school.
6. Run your application, hope you found no error and I hope this example will help you a little to understand basic of User Interface in Android.





Categories: , , , ,

Friday, September 16, 2011

Android Programming - Access Localhost

When I developed an application that connect to my own web service ( I made my own simple web service too ^-^), I got this error "java.net.ConnectException localhost/127.0.0.1:8080 - Connection Refused".
Hei, why my application got this error? I check my web service, it up and running well, I check the AndroidManifest, I already added the permissions to access Internet, what else?
This is happen because I read no documentation before about connecting to Localhost in Android, it has stated in Android Doc, that connection to localhost is a loopback address of the Emulator or handset. I need to use 10.0.2.2 address. What a dumb, you can read the explanation here.

Categories: , , , ,

Android Push Notification

Dalam OS Android sampai saat ini belum tersedia dukungan untuk push notification secara native seperti milik Blackberry ataupu iOS.
Secara fasilitas UI sudah tersedia elemen STATUS BAR yang dapat mengakomodasi container untuk message yang akan di push. Ada beberapa alternatif untuk dapat menggunakan fasilitas Push Notification ini di Android :
  • Poll : request data ke server setiap periode waktu tertentu, tidak butuh cost tambahan apapun, tapi tidak akan pernah benar-benar real-time dan semakin sering request ke server, batere akan semakin boros.
  • SMS : Android mengijinkan kita meng-intercept SMS. Server mengirimkan SMS yang di-encode khusus, setting Listener di Android untuk mengecek SMS, dan bila ditemukan encode khusus tersebut sms akan di-intercept dan dijadikan notifikasi di status bar. Benar-benar bisa mencapai realtime, tetapi bisa dibilang costly karena butuh investasi SMS server dan biaya pengiriman SMS.
  • Persistent TCP/IP: HP kita menginisialisasi koneksi TCP-IP yang terbuka terus dan dimaintain dengan mengirimkan “keep alive messages”. Setiap ada hal yang baru di server akan mengirimkan pesan yang diterjemahkan sebagai notifikasi. Full realtime, benar-benar hanya tergantung kecepatan koneksi. Isu yang mungkin muncul tentang sistem android yang otomatis bisa kill program atau service bila membutuhkan memori, juga mengenai boros baterai.


Yang akan dibahas lebih lanjut mengenai TCP-IP connection. Ada beberapa riset dari orang-orang di web dan juga tawaran aplikasi.
  1. Urban Airship
    Layanan berbayar, satu API untuk Android, BB dan iOS. Sudah mantap layanannya, banyak yang sudah memakai. Kekurangannya kita harus menginstall aplikasi tambahan AirMail yang merupakan aplikasi penjaga koneksi.
    Secara sistem hampir tidak ada kekurangannya, sudah lengkap, banyak dukungan tutorial dan sample untuk development.
    Ada dua sistem Pricingnya, Basic yang berdasar jumlah message yang akan dikirim dan Premium yang berdasar jumlah user pemakai.
  2. Google C2DM
    Server dari Google yang mengijinkan pengiriman message dari 3rd Party application server ke aplikasi Android. Minimal Android 2.2, menggunakan Google Account, jadi harus setting account dan harus ada aplikasi Market terinstall.
    Aplikasi di hp Android tidak perlu berjalan terus ataupun membuat service tertentu, Google yang akan mengurus pemanggilan aplikasi dengan Intent Broadcast tertentu saat ada message yang masuk. C2DM tidak memberikan interface apapun, hanya mengirimkan raw data yang diterimanya dari server aplikasi apa adanya dan diharapkan aplikasi di handset Android memilliki kapabilitas penuh message itu menjadi suatu notification di status bar, dialog ataupun sinkronisasi data secara silent.
    Dukungan penuh API dari Google tentu bersama contoh developmentnya.
    Batasannya adalah maksimal ukuran message 1kb dan Google juga membatasi jumlah pengiriman pesan ke aplikasi secara agregat maupun jumlah pengiriman ke device tertentu.
  3. Ericsson Labs – Mobile Push Java
    API dan library berbasis JAVA bisa digunakan untuk J2ME dan Android. Menggunakan SMS yang dikirimkan melalui protokol HTTP.
    Utilisasi SMS.Intent.android.provider.Telephony.SMS_RECEIVED yang mulai ada di Android 1.6. Ada web interface dari Ericsson Lab untuk mengirim message langsung dari web, juga bisa menggunakan XML-RPC API yang sudah tersedia untuk mengirimkan message dari web application kita sendiri.
    Cukup menjanjikan karena lewat SMS dan cutting Cost tidak perlu biaya server sama sekali. Terbatas untuk Android(1.6++) dan J2ME. Dukungan sample dan dokumentasi bagus.
  4. Josh Guilfoyle – long keep alive message lewat alarm manager
    Riset dan working example menggunakan AlarmManager untuk membangunkan program dan koneksi juga penggunaan handler untuk running multiple thread dan waktu yang berbeda untuk memastikan koneksi ada terus. Sukses berjalan tapi bermasalah karena Android yang terkadang secara otomatis meng-kill aplikasi dan service. Meskipun kemudian bisa di bangunkan lagi tapi ada kemungkinan state program dan servie ada yang hilang , bisa diakali menggunakan shared preferences.
  5. Dave Rea – Deacon Project
    Merupakan project yang menggunakan Meteor Web Server dan Comet Technology untuk pengiriman notifikasi, masih dalam pengembangan, belum release versi 1 bahkan. Cukup emnjanjikan sebagai opensource Push Notification untuk Android dan JAVA tapi sekarang belum ada dokumentasi, WIKI tapi sudah ada demo aplikasi dan source codenya.
  6. Dale Lane – MQTT
    MQ Telemetry Transport (MQTT) adalah lightweight broker-based publish/subscribe messaging protocol yang didesain untuk menjadi terbuka, simpel, ringan dan mudah untuk diimplementasikan.Sangat cocok digunakan untuk environment yang memiliki banyak keterbatasan seperti ketika netwok mahal, bandwidth kecil dan tidak bisa diandalkan atau juga saat menjalankan embedded device yang terbatas prosesor dan memorynya.
    Menggunakan protokol TCP/IP, menyediakan beberapa kualitas service yang dapat digunakan sesuai kebutuhan, ukuran yang kecil (fixed-length headernya hanya 2bytes).
    MQTT kemudian membutuhkan suatu message broker untuk pengiriman pesan, server untuk pengiriman ke message broker dan library MQTT di aplikasi.
    Mr Dale membuat contoh aplikasi Twitter, dimana ia membuat server untuk mem-pool setiap tweet dan kemudian memilih beberapa tweet yang 'istimewa' untuk kemudian dilanjutkan ke message broker dan kemudian ke aplikasi androidnya.
  7. Anton Laproev – penyempurnaan MQTT (working example)
    Pengembangan dari contoh Mr Dale, lebih lengkap dan benar-benar sudah berjalan, lengkapa komponennya juga. Di bawah merupakan diagram sistemnya. RSMB (Really Small Message Broker) merupakan script dari IBM dan bis dipergunakan juga dengan bebas, bisa digantikan dengan web server lain misalnya Mosquitto. SAM (Simple Asynchronous Message) PHP Library merupakan library PHP yang akan menyediakan metode pengiriman pesan ke RSMB dan send_mqtt.php merupakan web services yang akan digunakan untuk proses input dan pengiriman. Di aplikasi akan digunakan library wmqtt.jar sebagai mekanisme penerimaan pesan di handset.
    Aplikasi bisa berjalan dengan baik dan menjalankan fungsi mengirim pesan dan menerimanya.
    Kelemahan penggunaan MQTT ini adalah mengenai keterbukaannya, bila ada orang yang mengetahui IP dan PORT dimana Message Broker (RSMB) berjalan akan dapat meng-intercept pesan dan membacanya. Untuk aplikasi dengan pesan yang sensitif kemudian bisa digunakan enkripsi.

Categories: , , , , ,

Android Programming - Hello World

Okay, the preparation phase is complete. You can now make Android Project. Let us start with the classic way in which a program Hello World. Let us immediately make, you need not know anything yet, we make first and I will explain later.
Example 1. Hello Android
Create a new project by accessing the File >> New >> Other >> Android >> Android Project.

Project name Hello Android
Target check one platform you have installed
Application name Hello Android
Package name com.capcay.helloandroid
Create Activity check the checkbox, the name "MainActivity"
Leave the others are. Click Finish and you've made ​​your first Android program. Congratulations!
Is this as easy? Of course, you are able to last and Run your project will get the output of the AVD like this (please wait loading AVD J).
Let me explain the structure of this android project. You can see on the left there is a Package Explorer. Expand all folders in your Android Project Halo. Appearance should be like this.
Src folder will contain the source code of your program. Because we just declare and use a single class then there would be only one file that is MainActivity.java. Can be seen that the source here in accordance with the concept of java class and contained in the package com.capcay.haloandroid. The contents of MainActivity:
package com.capcay.helloandroid;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
} 

Top line is a package declaration, it must be precisely written so as not to cause errors. Each command line in Java will end with ";" to signify its line-end. The next line that begins with the import is a process to import a library that we will use within that class.
Next is the creation of the component class MainActivity Android will enter the Activity groups that need to extends Activity (inherit / inheritance of class Activity). This class is then simply override (stacking / replace) the OnCreate method of the class Activity. The core of this code is to set the screen layout in accordance MainActivity declaration in files in a folder named main.xml layout.
Next is a file R.java, this is a magic file, therefore you do not even need to touch it and it will always be automatically updated by the SDK, if you change it manually will appear warning that the file R.java changed and will be returned as originally. This file lists every resource in your application, and about providing an integer id value for each resource, therefore we can use it as the file MainActivity had to call the appropriate layout file. If you are curious about the contents of this R.java file, you can open it and view its contents that there are many lists that hexadecimal code.
Android 2.2 folder contains the libraries that you can import into your program directly. Its contents will vary for each type of platform, because it is currently using the Android platform 2.2 Froyo the resource library will be in accordance with SDK 8.
Res folder handle placement and organization of resource files. There are lots of subfolders, at least at the beginning of the project made ​​no drawable folder-ldpi, hdpi and mdpi to separate resource file according to dpi (dots per inch), the usefulness of this separation of resource-based dpi for Android that will determine after knowing the dpi of the handset screen resource in the folder which will be used. Folder layout for placement of an XML file layout, here there are files that had been accessed by main.xml MainActivity, string folder also stores resource, here the origin of the words "Hello Android blah blah blah ..." which was contained in the emulator screen. Let's look at a file main.xml that make up the display as you see it. 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>  
Quite simply, this XML file begins with a declaration of his version and encoding type. It must exist in each file according to XM L. XML stands for eXtensible Markup Language that is actually providing flexibility for users to use their own tagnya, unlike HTML tag that already determined and has certain conventions, in XML we are free to use our own tag, Therefore Android chose XML as the language because it is easy to add markup tag with our own rules. Tag  linear layout and textview is a tag made ​​by programmers of Android OS for the layout definition. LinearLayout is one type of layouts are supported Android and TextView is similar to the label element in many other visual programming languages, ie text that can not be edited, just show what it is .
The first line on LinearLayout shows the XML schema used (all Android XML files using this scheme). Then the rules set its value orientation in the vertical screen. Then the width and height layout gives a chance fill_parent. Fill_parent means its value will follow the value of parentnya, while if its value wrap_content will follow the area occupied by the object in it. Therefore, in its height TextView element set wrap_content, to follow the text that will have high there. The last line tells Android TextView where to retrieve the value for the content of this element values ​​are in the folder, the file named string.xml and variable named hello. Try to open the file string.xml, you will see a variable declaration is also accompanied by hello there again that is one variable APP_NAME.
The last file which I will explain is AndroidManifest.xml (others yet to be discussed here). This file shows the structure of your program.
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.capcay.haloandroid"
      android:versionCode="1"
      android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="8" /><application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".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>  
As always begins with the declaration of type XML and then to show that he was the manifest file is used as a tag parent tag manifest. We immediately see the tag application, here there will be a child - a child activity, receiver, or broadcast content resolver. In the Hello Android program there is only one Activity of MainActivity labeled with take a string APP_NAME. In Activity was determined Intent to run Activity Activity MainActivity as they were when the launcher program starts. And then stay close tags that exist for each XML file must be ensured wellformed, there can be no formatting errors in it.
Congratulations you can make your own Android programs, and already understand (should be :p) what should exist in the project file Android.

Categories: , , , , ,

Android Programming - ListView, ListActivity with Header

Have been playing around with Android for 2 months maybe, I think ListView very important for me, I used it in my application, and help me build the UI faster. I like to use list adapter and ListActivity, it is simple and great for presenting data (my company app is about showing data :p). It simplify the onClick function, I can use the overriding method of onListItemClick, generating single reusable function for every list item, with ease of access to the data.
The idea to have listview with header is using a relative layout to positioning the listview below the header layout. It seems simple, but for the first time I need some trial and error before succedd.
This my example layout :
<?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="wrap_content">
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#585861"
    android:id="@+id/top_bar">
        <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HEADER" ></TextView>
    </LinearLayout>
    <ListView android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/top_bar"
        >
    </ListView>
    <TextView android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Nothing, it's empty" 
        android:layout_below="@id/top_bar" />
</RelativeLayout>

That for header, this is the ListView layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:id="@+id/header_list">
    <TextView android:id="@+id/text1"
        android:textSize="16sp"
        android:layout_width="30dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_column="0"/>
    <TextView android:id="@+id/text2"
        android:layout_width="30dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_column="1"/>
</LinearLayout>
You can also use default List layout from android, for example simple_list_item1, or the other, I just want to show you how to make your custom layout for ListView.
And finally this is the activity code :
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.header);
        dbHelper = new GSDbAdapter(this); //this is my database helper
        dbHelper.open(); //don't just copy it, use your own db helper
    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_main, cGrid, new String[]{"dataDb1", "dataDb2" }, new int[] {R.id.text1, R.id.text2});
        this.setListAdapter(adapter); //dataDb1 and dataDb2 is query from Db and then placed to textview with Id text1 and text2 in layout list_main, cGrid is cursor from my database, use your own too
}

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    //your code here
}
Don't forget to extend ListActivity instead of Activity. I hope this will help you a little bit, any comment and suggestion will be appreciated.
Thanks.

Categories: , , , , ,

Copyright © Johannes Dwi Cahyo | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑