顯示具有 API 標籤的文章。 顯示所有文章
顯示具有 API 標籤的文章。 顯示所有文章

2013年9月3日 星期二

[JPA] Note

<tx:jta-transaction-manager>
觸發系統去找 JTA Transaction Manager


singulatAttribute 
A extends B, if B 中的屬性不是基本型別 在 A 中無法識別 所以 singulatAttribute 要寫在 A 中 寫在 B 中無效

embedded object 必須宣告在 child's metamodel


namedQuery
server 開啟後便會執行 像是函數 只要有參數就能直接執行
不能做子查詢
不能使用 like


entityManager.detach(Object);
和 Object 脫鉤


construct
建立物件時 只取出其中某些欄位
criteriaQuery.select(builder.construct(
    User.class,
     root.get(User_.name)
))


boolean attribute 
預設是 insert 0/1
加上 @Type(type = "yes_no") 則 insert Y/N


A join B
In A, if joinColumn is not primary key JPA not allowed lazy fetch.


@filterDef
filter join 後的結果

2013年9月2日 星期一

[Java] Not a Number (NaN)

NaN - Not a Number 表示非定義的數字

ex:
0.0 / 0 (被 0 除的結果)
0.0 / 0.0

不論是和數字或是和 NaN 都不能用關係運算子做比較(<, <=, >, and >=)

Double.isNaN()/Float.isNaN()


* Reference

[JQuery] API


:first 


.prev()      


  
$(selector1).find(selector2);      


$(selector1).filter(selector2);  



$(selector).length 


$(selector).eq(i)  


$("p").insertBefore("#foo") = $("#foo").before("p")   



* Reference
- jQuery基础---filter()和find()
- Difference Between Filter() And Find() In JQuery

2013年3月26日 星期二

[Android] Directory path for APIs


  • getFilesDir = /data/data/{package name}/files
  • getDatabasePath = /data/data/{package name}/databases/{database name}.db
  • // 私人的檔案,當移除 APP,此路徑下的也都會移除。
  • getExternalFilesDir = /mnt/sdcard/Android/data/{package name}/files/{file}
  • getDownloadCacheDirectory = /cache
  • getDataDirectory = /data
  • // 與應用程式的關聯直接分開的,當移除 APP,此路徑下的也不會被移除。
  • getExternalStorageDirectory = /mnt/sdcard 
  • getExternalStoragePublicDirectory = /mnt/sdcard/pub_test

2012年12月1日 星期六

[JPA] transaction annotation values

TRANSACTION
  • support: 依附 transaction 無則沒 transaction
  • required: 裡頭行為綁在一起, 一起成功/失敗
  • never: 行為分開獨立 有些成功 有些失敗

2012年6月15日 星期五

[Android] Context

public abstract class Context
  • 管理 global application 資訊的 interface,是由 Android System 實作。
    • Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system.
  • 可由此取得 application-specific 的 resources and classes。
    • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

getApplicationContext()
  • 在啟動 app 時,預設會啟動 Application,也就是 AndroidManifest.xml 中的 <application>,因此也能自己實作指定在此 tag 中,替代此預設。
  • 回傳所在 process 中的 global application context。
    • Return the context of the single, global Application object of the current process.
  • 應被使用在當 lifecycle 不和當前 component 綁在一起時。
    • This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.
ex: 
  • registerReceiver(BroadcastReceiver, IntentFilter)
    • 如果使用的是 Activity context,這個 receiver 就是被註冊在此 Activity,所以你必須在此 Activity destroy 前 unregister 此 receiver,若沒有這樣做則會發生 exception。
      • If you use the Activity context to register a receiver that is static (global to the process, not associated with an Activity instance) then that registration will be removed on you at whatever point the activity you used is destroyed.
    • 如果是使用 Application context,這個 receiver 是和 application 相關連,因此不會被 unregistered,但有可能會造成 leak。
      • However using the ApplicationContext elsewhere can easily lead to serious leaks if you forget to unregister, unbind, etc.
  • 使用在 DB 操作時。


* Reference
- 求getApplicationContext用法-Android 问题&解答-eoeAndroid开发者社区 - Powered by Discuz!
谈谈Android里的Context的使用!!! - Android_Tutor的专栏 - 博客频道 - CSDN.NET

[JPA] @OneToMany

// ObjectA many-to-one with ObjectB

// In ObjectA
// mappedBy  的值是在 ObjectB 中的 attribute
@OneToMany(fetch = FetchType.LAZY, mappedBy = "objectA")
public List<ObjectB> getObjectB()  {  
    return objectBs;  
}

// In ObjectB
@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumns({
    @JoinColumn(name = "FIELD_X", referencedColumnName = "FIELD_X", insertable = false, updatable = false )
})
public ObjectA getObjectA() {  return objectA; }

[Database] BigDecimal

當 table 對應為物件時

若其 value 長度可能會超過 java int

這時候就會使用 BigDecimal type

ex: 流水號


* Reference
- How big is BigDecimal?

2012年6月3日 星期日

[Android] WebView WebViewClient

  • WebViewClient.onLoadResource
    • Anything loaded in webview will pass by.
  • WebViewClient.shouldOverrideUrlLoading
    • Actions occured in webview will pass by.
    • But! Standard links and server redirects trigger shouldOverrideUrlLoading(); window.location does not.

2012年6月2日 星期六

[AndroidProcess] Background works

Main thread 負責處理 UI event,所以也稱為 UI thread,Activity、Service、Receiver、Provider,都是由 main thread 負責執行。因此不能在此 thread 中執行耗時的動作,android 會發出 ANR,這時候就得在 background thread 中執行,讓 main thread 同時仍能回應或執行 UI event,以避免 ANR 狀況。

sendBroadcast() 與 startService() 都一樣會被丟到 main message queue 裡,等待 main thread 的執行,只有呼叫 local content provider 不會進到 main message queue 裡,而是由 main thread 直接執行。但如果是 remote content provider 則是由 thread pool 中取得 thread 來執行,外部 client 呼叫 service 也是如此。

每個 Thread 中都有 Looper 和 Message Queue,Message Queue 中儲存著要被處理的 events (UI event and System event),Looper 負責 Thread 和 Message Queue 間的連繫。

另外,因為是 main thread 負責更新 UI,所以若是試圖在 worker thread 中更新 UI,是會得到 exception 的,必須把更新 UI 的動作再丟給 main thread 處理。


可選擇以下方式:

* Simple Worker Thread and runOnUiThread()/View.post()
View.post()
Each View object has a message queue which is processed sequentially on the UI thread. post() allows us to add a new message to the message queue.
new Thread(new Runnable() {
    @Override
    public void run() {
        // TODO works here.
        
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // UI event
            }
        });

        // or
        final TextView textView =
            (TextView) findViewById( R.id.textview );
        textView.post(new Runnable() {
            @Override
            public void run() {
                // UI event
                textView.setText( "Hello World" );
            }
        });
    }
}).start();

* new Thread + Handler
Handler: 負責處理 thread 的訊息(message)。
private Handler handler = new Handler() {
    @Override
    public void handleMessage(android.os.Message msg) {
        // UI event
        progressDialog.dismiss();
    };
}

new Thread() {new Runnable() {
    @Override
    public void run() {
        // TODO works here.

        // 把 message 送給 handler 處理。
        handler.sendEmptyMessage(0);

        // or 將 Runnable post 到 handler。
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.setText( "Hello World" );
            }
        });
    }
}.start();

* AsyncTask
  • 如果只會 Override doInBackground 則可考慮使用 Thread 即可。
  • AsyncTask 會 hold Activity context 直到工作結束,所以可能會有 context leak 問題。
new AsyncTask() {
    // onPreExecute(), onProgressUpdate()

    @Override
    protected Void doInBackground(Void... params) {
        // TODO works here.
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // UI event
    };
}.execute();


** AsyncTask and Handler
  • AsyncTask 內部實做機制為較新且較強的 java.util.concurrent,但較佔資源,而 Handler Thread 則為基本的 Java Thread。
  • 由於 Handler Thread 依靠 Message Queue 與 Main Thread 互動,相對於 AsyncTask,Handler Thread 比較可能發生塞車情況。
  • 但 Handler Thread 在即時互動上優於 AsyncTask,因為 Main Thread 可以隨時傳送 Message 給 Handler Thread,而 AsyncTask 不行,只能依照事先定義 Callback 進行。
  • 基於輕量環境資源的有限,當執行單一的工作時建議使用 AsyncTask,如下載一個大檔案,但是當執行大量重複性的工作時,建議使用 Handler Thread,如下載多個小圖。

* Loader
  • Introduced in Android 3.0 and also included in the Support Library.
  • Used to asynchronously load data in an activity or fragment.
  • Quite effectively to perform these tasks:
    • Loading content either from a SQLite database or file storage, or from a network resource as a background task.
  • There are essentially three components that we need:
  • How to use:
    • Obtain LoaderManager instance from Activity/Fragment/FragmentActivity.
    • Implement LoaderManager.LoaderCallbacks.
      • Will create a loader.
      • Get called when the loader either finishes, or is reset.
      • These will all be executed on the UI thread, and we will typically implement them within our Activity / FragmentActivity.
      • 也就是在 Loader 中處理 UI event。(?)

* Service
  • Services is a means of performing some task which is not attached to a specific Activity.
  • Run in the main thread of their hosting process. (並不會在另一個 thread 中執行,所以不適做耗費 CPU 的工作 會有 ANR 的可能,或者是必須 new a thread。)
  • There are two types of Service:
    • A background Service
      • The default type of Service and can be killed by the OS (or Task Killer apps, more of them later) to free up system resources.
    • A foreground service
      • Not be killed by the OS, but requires an ongoing Notification to be displayed in the Notification bar while it is running so that the user is aware that the foreground Service is active and will not be killed automatically by the OS.
      • ex: music player.

* IntentService extends Service
  • Service + Handler + HandlerThread。
  • Will receive a single Intent and then shut down automatically once we have processed it.
  • 和 Service 不同,此 api 會執行在自己的 worker thread,陸續執行交給它的 request,但只會有一個 worker thread 同時也只會執行一個 request,當執行完後會自行停止。
  • 實做其 onHandleIntent(Intent intent),在這裡處理 request。
  • 是設計用來可以在一個 Service 中服務多項工作,因此在 onHandleIntent(),不可以呼叫 stopSelf(),全部工作結束,它會自行停止。
  • start service -> send message to handler that has non-UI thread looper -> handlerMessage() -> onHandleIntent()
    • Looper 就是訊息迴圈 (message loop),這是 Android UI 在處理各式訊息時,最重要的元件之一。
  • One word of warning:
    • Performing long tasks in an IntentService does have the inherent risk that it will stop if the device goes to sleep. You can prevent this from happening by holding a WakeLock while onHandleIntent() is executing. Just make sure you release it before onHandleIntent() returns. Alternatively use Mark Murphy’s WakefulIntentServicepattern.

* Pending
  • StrictMode
    • API level 9。
    • 可用於發現潛在問題,ex: 你該使用 background thread 的動作。
  • Loader
    • API level 11。


* Reference
- Background Tasks – Part 1 (Introduction)
- Background Tasks – Part 2 (Worker thread, Handler)
- Background Tasks – Part 3 (AsyncTask)
- Background Tasks – Part 4 (Loader)
- Background Tasks – Part 5 (Service)
- Background Tasks – Part 6 (IntentService)
- Android之Service与IntentService的比较 - HiPhoneZhu的专栏 - 博客频道 - CSDN.NET **
- 深入研究 IntentService 原始碼 ***
- IntentService的功用
- Android Handler 筆記 **
- Java Artisan: Android AsyncTask 與 Handler Thread 的差異 **
- Java Artisan: 在 Android 裡使用 Local Service

2012年5月6日 星期日

[Spring] configurations


<!-- Activates various annotations to be detected in bean classes -->
<!-- 設定註釋注册到Spring容器 -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct base-package-->
<!-- 在 base-package下尋找有 @Component 和 @Configuration 的 target Class予註冊為 bean -->
<context:component-scan base-package="org.krams.tutorial" />

<!-- Configures the annotation-driven Spring MVC Controller programming model.
Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
<mvc:annotation-driven />


* Reference
- krams::: Spring 3 MVC: Using @ModelAttribute in Your JSPs

2012年4月28日 星期六

[SQL] AND has more priority than OR

* Priority
  • In SQL: AND > OR
  • In Java: && > ||

SELECT count(*) FROM TABLE_A
    WHERE (X= 2 OR X = 5) AND Y = 0;
   
SELECT count(*) FROM TABLE_A
    WHERE X IN (2,5) AND Y = 0;


2012年4月21日 星期六

[AndroidNet] HTTP API

Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

  • android.net.http.AndroidHttpClient - API 8 - 主要使用 Apache 的 HttpClient
    • Implementation of the Apache DefaultHttpClient that is configured with reasonable default settings and registered schemes for Android, and also lets the user add HttpRequestInterceptor classes. 
    • Don't create this directly, use the newInstance(String) factory method.

Their implementation is stable and they have few bugs. But Android Team is not actively working on Apache HTTP Client.


  • abstract java.net.URLConnection
    • Instances of URLConnection are not reusable: you must use a different instance for each connection to a resource.
    • An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length.
  • java.net.HttpURLConnection extends URLConnection
    • This class may be used to send and receive streaming data whose length is not known in advance.
    • Is a general-purpose, lightweight HTTP client suitable for most applications.
    • Prior to Froyo, HttpURLConnection had some frustrating bugs.
    • Work around this by disabling connection pooling (Refer:  Android’s HTTP Clients | Android Developers Blog)
    • In Gingerbread, we added transparent response compression.
    • In Ice Cream Sandwich, we are adding a response cache.

  • How to choose?
    • Eclair and Froyo  - Apache HTTP client that has fewer bugs.
    • For Gingerbread and better -  HttpURLConnection.
      • Its simple API and small size makes it great fit for Android.
      • Transparent compression and response caching reduce network use, improve speed and save battery.
      • Android Team will be spending our energy going forward.

* Reference
- Android’s HTTP Clients | Android Developers Blog
- Android 上的 HTTP 服務相關函式 (I)
- Android 上的 HTTP 服務相關函式 (II)
- Android 上的 HTTP 服務相關函式 (III)

2012年3月25日 星期日

[AndroidLayout] getWidth() and getHeight()

Error
當 view 還未完整被 layout 前,呼叫 getWidth() and getHeight() 所得的值會是 0。


Solution
  • The view's size is assigned when view.onSizeChanged is called with oldw = oldh = 0.
  • Assuming your view is visible, its size has been assigned by the time the activity's window receives focus. That is, when activity.onWindowFocusChanged is called with hasFocus = true.

The sequence is roughly:
  1. view.onFinishInflate
  2. view.onMeasure
  3. view.onSizeChanged(width, height, 0, 0)
  4. view.onLayout
  5. activity.onWindowFocusChanged(true)
// 這樣能確保得到正確的 width and height.
view.post(new Runnable() {
  // TODO
});


* Reference
- Re: When are View.getWidth and getHeight values valid? - joebowbeer - com.googlegroups.android-developers - MarkMail

[Android] Log

The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE.
  • Verbose should never be compiled into an application except during development.
  • Debug logs are compiled in but stripped at runtime.
  • Error, warning and info logs are always kept.

  • When you're building the string to pass into Log.d, the compiler uses a StringBuilder and at least three allocations occur: 
    • the StringBuilder itself
    • the buffer
    • the String object.
    • Realistically, there is also another buffer allocation and copy, and even more pressure on the gc.
  • That means that if your log message is filtered out, you might be doing significant work and incurring significant overhead.



* Reference
- Log | Android Developers

[SQL][Java] Date


java.sql.date:  沒有時分秒

java date: 到時分秒

2012年3月3日 星期六

[AndroidLayout] android:weightSum and android:layout_weight

android:weightSum
  • If unspecified, the sum is computed by adding the layout_weight of all of the children.
  • Must be a floating point value, such as "1.2".

android:layout_weight
  • Linear layout提供此屬性,讓其所有的子顯示物件可以透過設定該屬性來表明自己的重要性。
  • 當所有有定義明確長寬的物件都好之後,剩下的空間分配給有宣告layout_weight屬性的物件,按照優先權使所有剩下空間被填滿。
  • 分配方式:
    • 若是指定在 child,值越分配到越空間。
    • ex: 假設剩下空間有三個View(A、B、C)要分配,其權值大小分別為3、1、1,因此它們所分配到的空間大小將會是3:1:1。
    • 若是指定在 parent,值越則分配到越空間。

利用這兩個屬性可以分配 LinearLayout 中 widgets 的比例:
This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

# Update on 2012/06/18
假設是兩個 widgets 要依比例分配寬,那麼此兩 widgets 的寬則應設為 0 dp,讓系統可調整其比例。


* Reference
- LinearLayout | Android Developers
- Chickenrice's Workshop: [Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)
- milkmidi Blog: Android LinearLayout **

[AndroidManifest] uses-sdk

android:minSdkVersion
  • An integer designating the minimum API Level required for the application to run.
  • The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute.
  • Default value of "1", which indicates that your application is compatible with all versions of Android.
  • The application will crash during runtime when attempting to access the unavailable APIs.

android:targetSdkVersion
  • An integer designating the API Level that the application targets.
  • Default value equals that given to minSdkVersion.
  • This attribute informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version.
  • The application is still able to run on older versions (down to minSdkVersion).
  • The system may enable compatibility behaviors to ensure when system API level > target.
  • For example, 
    • setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher
    • disables screen compatibility mode when running on larger screens (because support for API level 11 implicitly supports larger screens).
  • There are many compatibility behaviors that the system may enable based on the value you set for this attribute.
  • 也就是說,在執行時起作用,如果版本相同時,效率可能會高點。

android:maxSdkVersion
  • An integer designating the maximum API Level on which the application is designed to run.
  • In Android 1.5, 1.6, 2.0, and 2.0.1, the system checks the value of this attribute when installing an application and when re-validating the application after a system update.
  • In the case of re-validation after system update, this effectively removes your application from the device.
  • Declaring this attribute is not recommended.
    • By design, new versions of the platform are fully backward-compatible.
    • Declaring the attribute can result in your application being removed from users' devices after a system update to a higher API Level.
  • Future versions of Android (beyond Android 2.0.1) will no longer check or enforce the maxSdkVersion attribute during installation or re-validation. 
    • Google Play will continue to use the attribute as a filter, however, when presenting users with applications available for download.

target API level
指定要 compiler 的 API 版本。


* Reference
- uses-sdk
- minSdkVersion、targetSdkVersion、targetApiLevel的区别