Hiển thị các bài đăng có nhãn java. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn java. Hiển thị tất cả bài đăng

29/12/2018

[Android] Custom error page for WebView

Trong rất nhiều tình huống bạn cần show trang error page ví dụ 404.html cho WebView. Trong trường hợp lỗi xảy ra. Lỗi xảy ra có thể tóm tắt hai trường hợp sau đây:
  1. Web server không thể trả về kết quả . Trường hợp này chỉ cần hiện thực các phương thức sau đây:
    
    void onReceivedError(WebView view, int errorCode, String description,String failingUrl) (API < 23) 
    void onReceivedError(WebView view, WebResourceRequest request,WebResourceError error) (API >= 23)
    
  2. Web server trả về kết quả nhưng là kết quả lỗi như 404, 502, 403, ... Trường hợp này nếu chương trình bạn chỉ dùng API >= 23 thì dùng các phương thức sau đây:

    
    void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
    void onReceivedSslError (WebView view,SslErrorHandler handler,SslError error)
    
    Tuy nhiên nếu bạn hỗ trợ API < 23 thì sao? Trong trường hợp của mình thì cần hỗ trợ từ API >=21 nên mình để ý đến phương thức sau:
    
    public WebResourceResponse shouldInterceptRequest (WebView view,WebResourceRequest request)
    
    Sau đây là skeleton code:
    
    OkHttpClient okClient = new OkHttpClient();
    try{
    final Call call = new Call (new Request.Builder()
                            .url(request.getUrl().toString())
                            .build());
    final Response response = okClient.exec(call);
    if (response.code() != 200){
        return getErrorWebResourceResponse();
    }else{
        return new WebResourceResponse(
            response.header("Content-type","text/html").split(";")[0],
            response.header("Content-Encoding","utf-8"),
            response.body().getByteStream()    
        );
    }                        
    } catch (Exception ignore){
     return getErrorWebResourceResponse();
    }
    }
    

15/03/2013

Kiểm tra một số có là luỹ thừa của 2 hay không nhanh nhất

Thông thường để muốn kiểm tra một số có là luỹ thừa của 2 hay không thì chúng ta đem số này chia cho 2 như sau:

public boolean isPowerOfTwo(int n){
	if( 0 == n|| 1 == n ) return true;
	int x = n / 2;
	int y = n%2;
	if (1 == y) return false;
	return isPowerOfTwo(x);
}
Hoặc chúng ta không cần viết đệ qui như sau:

  public boolean isPowerOfTwo(int n){
    boolean ret;        
	if( 0 == n|| 1 == n ){
    	     ret = false;       
    }else{
        int x = n / 2;
        int y = n%2;
        while ( x > 0){
        	if (1 == y) {
            ret = false;
            break;
 		};
		x = x / 2;
        y = x%2;
	}
	ret = true;
	}
   return ret;
 } 

Sau đây là cách nhanh hơn sử dụng hàm logarit:

public boolean isPowerOfTwo(int n){
	double logn2 = Math.log(n)/Math.log(2);
	int logn2i = (int) (Math.floor(logn2));
	if(logn2-logn2i==0)
		return true;
	else
	return false;
}

Tuy nhiên nếu chúng ta để ý một chút chúng ta sẽ có cách kiểm tra nhanh nhất. Các số là luỹ thừa của 2 đều có 1 chữ số 1 trong biểu diễn nhị phân của chúng. Ví dụ số
1: 000001
2: 000010
4: 000100
8: 001000
16: 010000
32:     100000
Xét số n = 32 ( 100000) và n -1 = 31 (011111) và rõ ràng n&(n-1) = 0.
Ta có giải thuật như sau:

public boolean isPowerOfTwo(int n){
	return ((n!=0) && (n&(n-1))==0);
}

Thật ngắn gọn, đơn giản phải không các bạn!

24/03/2011

Alert Dialog trong Android

Trong lập trình phát triển ứng dụng Android để giao tiếp với người dùng có hai cách:
  1. Sử dụng một màn hình (Activity)
  2. Sử dụng hộp thoại (Dialog)
Tuỳ tình huống cụ thể chúng ta chọn giải pháp phù hợp.
Việc sử dụng một Dialog thông minh đôi khi cho chúng ta một giải pháp tuyệt vời.
Để hiển thị Dialog trong Android chúng ta thường sử dụng AlertDialog.
Sau đây là đoạn mã sử dụng AlertDialog tôi thường sử dụng:
AlertDialog.Builder mAltBld = new AlertDialog.Builder(this);
mAltBld.setMessage("")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface aDialog, int aID){
//Thực hiện điều gì đó khi người dùng bấm nút Yes.
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface aDialog, int aID){
//Thực hiện điều gì đó khi người dùng bấm nút No.
aDialog.cancel();
}

});
AlertDialog mAlert = mAltBld.create();
//Tiêu đề cho AlertDialog
mAlert.setTitle("Tiêu đề");
//Biểu tượng cho AlertDialog
mAlert.setIcon(R.drawable.icon);
mAlert.show();

03/03/2011

Lấy tên phương thưc hiện tại

Trong lập trình Java. Dôi khi bạn muốn lấy tên phương thức hiện tại ví dụ để xuất thông tin phục vụ cho gỡ rối chẳng hạn. Sau đây là kinh nghiệm của cá nhân mình:
Đối với Java 4:
new Exception().getStackTrace()[0].getMethodName();
Đối với Java 5:
Thread.currentThread().getStackTrace()[1].getMethodName();

04/03/2010

Java Database Connectivity (JDBC)

Đây là slide trình diễn về JDBC trong loạt bài Java Training. ACE nào quan tâm thì có thể gửi email cho tôi để nhận bài giảng đầy đủ bằng tập tin word.

Java Data Object (JDO)

ACE nào thích chủ đề này, xin vui lòng liên hệ mình để có phần bài giảng đầy đủ bằng tập tin word nha.

15/09/2009

Security breach in default installing JBoss

If JBoss is installed by default, you can access web console to shutdown JBoss instance remotely by a normal browser without authentication:
Following menu tree will appears, you can do what you want:

29/06/2009

Eclipse Galileo was released

Eclipse 3.5 or Eclipse Galileo was released on June 24th, 2009.
This is the fourth version Eclipse. Its predecessors are Calisto, Europa, Ganymede.
Its new features has been listed here.
You can download Eclipse Galileo here.
Plz, remember to write your review about Eclipse Galileo at Blogathon and receive a thank you gift.

10/06/2009

Java 7 & Java EE 6

Java 7 (will be released in Feb 2010) have many new things:
  1. modules (you can customize the features of Java as you need, classpath will be deprecated).
  2. null check operator/condition:"?:"
  3. switch with string type.
  4. multiple exception in catch block.
  5. using diamond symbol for generics instead of greater symbol.
Java EE 6 (will be released in Oct 2009) have some interesting features:
  1. JAX-RS (support fully RESTful service)
  2. JFS 2.0
  3. Asynchronous servlets.
  4. Bean validation.
  5. web.xml is replaced by web annotation or xml fragments.
  6. web beans (session bean in WAR file).
Spring Roo is a new project, it is like Rails or Grails with pure Java.
Eclipse Galileo will be release in June 24, 2009. Its chronological priors are Calisto, Europa and Ganymede.