Tuesday, January 31, 2012

Eclipse tips

1. Switch between "tabs"
Want to change to next tab?
Using Ctrl E or Ctrl Shift E is so ugly.
Use Ctrl Shift Tab, then use navigator left or right. When done, press Tab.

2. Switch Perspective
Ctrl F7

Wednesday, January 11, 2012

[Android] Tổng kết kinh nghiệm làm việc với service và activity

1. Một service có thể vẽ hình, đặt nó trên tất cả các View khác  và nhận event khi user touch vào màn hình nhờ thiết lập qua WindowManager.LayoutParams. Event service nhận được duy nhất là MotionEvent.ACTION_OUTSIDE.

2. Tọa độ khi bắt event bằng service bắt đầu từ (0,0) tại vị trí góc trên trái, dưới StatusBar. Trong StatusBar thì tọa độ y của nó là âm (từ -25 đến 0). Tọa độ bắt bằng View trong Activity bắt đầu từ (0,25) cũng tại điểm góc trên trái dưới StatusBar vừa nói. Bởi thế phải cộng thêm 25 vào tọa độ lấy được từ service nếu muốn sử dụng nó cho Activity.

3. Khi 1 activity không được active nữa (mở 1 activity khác từ nó), hệ thống gọi method onStop() trên nó. Hàm này khác với onDestroy (thoát bằng back...)

4. Nếu service của bạn có "nguy cơ" sẽ tương tác với Activity, tốt nhất là nên implement các method onBind, onUnbind. Chú ý nếu implement onBind mà ko implement onUnbind có thể dẫn đến lỗi "leaks service hay binder j đó"

5. Nếu cần update UI, nhớ dùng view.invalidate()

6. method bindService()  không phải là hàm cho kết quả "ngay lập tức" nên nếu dùng instance của service trả về qua binder để gọi method của service sẽ bị lỗi service đó là null.
Khắc phục: không gọi API của service ngay lập tức (vd 2 dòng này cùng nằm trong onCreate() chẳng hạn). Có thể gọi API trong onConnected, hay bindService trong onCreate()/onStart() và gọi API trong 1 listener nào đó.

Tuesday, January 10, 2012

Android: avoiding memory leaks

In summary, to avoid context-related memory leaks, remember the following:
  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  • Try using the context-application instead of a context-activity
  • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  • A garbage collector is not an insurance against memory leaks

Friday, January 6, 2012

Android: Frequent mistakes/bugs

(Use Eclipse)
1. When you setOnClickListener on a button, Eclipse requests you change it to other method...
SOLUTION: import android.view.View.OnClickListener;

2. When you write only a service. Installed it into VD and you don't see its start icon. Although you can see that service in "Setting> App Manager> Running Service"
SOLUTION: Create an activity.

3. You edited some file but Eclipse keeps warning you have errors.  
SOLUTION: clean you project : Menu >Project >Clean

4. Some activities or services not run?
SOLUTION: Add them to AndroidManifest

5. You logged something but don't see them?
SOLUTION: Choose device which using by logcat.

6.You use Toast  but it not show on your screen
SOLUTION: did you forget .show() method?

7. Eclipse: Can't bind to local 8600 for debugger.
SOLUTION: In addition to adding " localhost" to your hosts file, make the following changes in Eclipse.
Under Window -> Preferences -> Android -> DDMS:
  • Set Base local debugger port to "8601"
  • Check the box that says "Use ADBHOST" and the value should be ""
Then, call adb kill-server followed by adb start-server  
After done, if it still not work. Restart your computer

8. Bug when you want to change your UI
SOLUTION: Use  View.invalidate();

9.Error : NoSuchFieldError R$id...
SOLUTION: change that xml layout

10. Connect adb with you device  on Linux. Enter adb devices and get "Unknow device"
SOLUTION: sudo adb kill-server, sudo adb start-server, sudo adb service

11. Eclipse stops responding when changing to DDMS perspective

SOLUTION: The problem was that AVD hanged somewhere at 27% and then I couldn't do really anything with Eclipse. The problem is somewhere in the AVD and re-installing the AVD didn't help me.
Instead this seems to work every time:
  • Start virtual device from Eclipse's Window -> AVD menu
  • Then right click the project and "Debug as -> Android Application"
Here you never need to close the virtual device and it's also a lot faster to use it this way.

12. You are working with dialog and some view inside it not work

SOLUTION: make sure that you are work with approriate views. Maybe some findViewById() should be yourDialog.findViewById();

13. JUnit test
Logcat: Test run failed: Test run incomplete. Expected 1 tests, received 0

SOLUTION: you were using the wrong constructor. Eclipse auto generate the code and it created this:

public LoginTest(String pkg, Class<Login> activityClass) {
    super(pkg, Login.class);

change it to this:

public LoginTest() {
    super("pkg_name", Login.class);

note that all your test function must be start with test and its modifier is public
public void testPreconditions() {

14. Eclipse hangs on loading workbench (after .adt...)
remove .snap file from <<workspace_dir>>/.metadata/.plugins/org.eclipse.core.resources/ 
then run eclipse -clean

15. Create hotkey for commit current file with Subclipse
In order to get the shortcuts to work, you must go to Window > Customize Perspective, then under the Command Groups Availability tab, check the SVN option. It may require a restart of Eclipse, but the Subclipse keyboard shortcuts will now work.

Then create a key binding for 'Commit'
(under Preferences... General->Keys, search for Commit). Then you just need to click on the row SVN  and hit a key combination => Ok

16. Error on gen folder
check your res files, all filename must start with alphabet, not number.

17. Can't install your app on real device but emulator
Check your manifest, is there any duplicate activity?

Thursday, January 5, 2012

Open source android app



Android with Proguard

Proguard shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names.

To use Proguard, you should use SDK 2.3.3 (API 10). If you wrote your project in API < 10, you should upgrade it:
android update project --name MyApp --target 2 --path ./MyAppProject

to get the target,run command:
android list targets
Then config your project to use Proguard:

For more android command:

If you use Eclipse, choose File>Export to release your project in .apk file.
You should see proguard directory in your project directory after exported.

NOTE: you should keep mapping.txt file each time you release. It helps debug your app later.

Don't not mean can't

When someone say don't or impossible, it doesn't mean you CAN'T

Android tips, exp

By me, for me  :))
1. Remove all Log to speed up your App when release.
 Xóa tối đa số Log bạn tạo ra khi viết trước khi release để tăng tốc.
2. Try to use Log instead of print (if you come from C, Java).
Tập sử dụng Log thay vì print ra các kết quả để check xem bạn viết đúng hay không. Log rất tiện lợi.

3. Đọc error log TỪ TRÊN XUỐNG. Sau đó mới xem caused by...