2010년 12월 30일 목요일

[Android Course][English][Theme] - DB Query () API uses the wrong





: ContentProvider between the Application is the only way to share data. ContentProvider to store and retrieve the data and allows access from any Application. Usually at this time to have access to Database "Cursor & Query ()" API is used.

=> Here I am 'Query ()' instead, 'managedQuery ()' is recommended for use.
Operating the same, but
managedQuery () write the life cycle of the activity has the advantage that it behaves like.
In other words, cursor.close onDestroy do not call the call automatically when the cursor is a Close.

- "Cursor & Query()" Wrong usage example
Cursor cursor = ContentResolver.query(....................................);
=> After straightening using 'cursor.close ();' If I tell you, leak or dead can happen.

- "Cursor & Query()" Recommended Usage Examples
Cursor cursor = managedQuery(....................................);


In addition, inquiries, or questions, please contact us.
(joonryang@gmail.com)

[Android 강좌][Korean][테마] - DB Query() API의 잘못된 사용





: ContentProvider는 Application들 사이의 데이터를 공유할 수 있는 유일한 방법이다. ContentProvider는 데이터를 저장하고 검색하고, 모든 Application에서 액세스 할 수 있도록 한다. 이 때 Database에 접근하기 위해서 보통 "Cursor & Query()" API를 사용합니다.

=> 여기서 나는 'Query()' 가 아닌, 'managedQuery()' 사용을 권장한다.
동작은 동일하지만,
managedQuery() 를 쓰는 경우 activity 의 life cycle 과 같이 동작한다는 장점이 있다.
즉, cursor.close 를 호출해 주지 않아도 onDestroy 가 호출되면 자동으로 cursor가 Close 됩니다.

- "Cursor & Query()" 잘 못된 사용 예제
Cursor cursor = ContentResolver.query(....................................);
=> 반듯이 사용 후에 'cursor.close();' 를 해주지 않는다면, leak 또는 dead 현상이 발생할 수 있다.

- "Cursor & Query()" 추천 사용 예제
Cursor cursor = managedQuery(....................................);


추가로 문의 사항이나, 궁금한 점이 계시면 연락주세요.
(joonryang@gmail.com)
※ 도움이 되셨다면, ^^. 맨 위 광고클릭 좀..ㅎㅎ

[Android Course][English][Theme] - Sdcard related API




1. Sdcard Path
: 'Sdcard' path '/ sdcard /' and so can not be used.
'android phone' every little 'sdcard root path' may be different.

ex) sdcard/...
ex) mnt/sdcard/...
....ETC

Therefore, 'sdcard root path' to access the API must be used as follows.
=> File path = Environment.getExternalStorageDirectory();


2. Check Sdcard capacity


: Sdcard Data Write and the other when working on, to check if the pre-dose program, maybe better.

File sdcard_path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(sdcard_path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();

- Total capacity
long Total_Size = totalBlocks * blockSize;
- Available capacity
long Available_Size = availableBlocks * blockSize;
- Capacity is being used
long Used_Size = Total_Size * Available_Size;
3. Sdcard Permission Setting
: Sdcard needed for the Data Write operation is set.
- AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


In addition, inquiries, or questions, please contact us.
(joonryang@gmail.com)

[Android 강좌][Korean][테마] - Sdcard 관련 API




1. Sdcard Path
: 'sdcard' 경로를 '/sdcard/' 등으로 사용할 수 없다.
'android phone' 마다 약간의 'sdcard root path'가 다른 경우가 있다.

ex) sdcard/...
ex) mnt/sdcard/...
....ETC

그러므로,  'sdcard root path' 에 접근하려면 아래와 같은 API를 사용해야 한다.
=> File path = Environment.getExternalStorageDirectory();


2. Sdcard 용량 체크


: Sdcard에 Data Write 및 기타 작업 할 때, 사전 용량 체크를 한다면 더 좋은 프로그램이 되지 않을까요.
File sdcard_path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(sdcard_path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();

- 총 용량
long Total_Size = totalBlocks * blockSize;
- 사용 가능한 용량
long Available_Size = availableBlocks * blockSize;
- 사용 중인 용량
long Used_Size = Total_Size * Available_Size;
3. Sdcard Permission 설정
: Sdcard에 Data Write 작업을 위해 필요한 설정입니다.
- AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


추가로 문의 사항이나, 궁금한 점이 계시면 연락주세요.
(joonryang@gmail.com)
※ 도움이 되셨다면, ^^. 맨 위 광고클릭 좀..ㅎㅎ

[Android Course][English][Theme] - Screen Resolution (Size) to obtain




Of the Android API, how to obtain the screen size is shown below.

1. 'Metrics' Use.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int deviceWidth = displayMetrics.widthPixels;
int deviceHeight =displayMetrics.heightPixels;

2. 'Display' Use.
Display display = getWindowManager().getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();

In addition, inquiries, or questions, please contact us.
(joonryang@gmail.com)

[Android 강좌][Korean][테마] - 화면 해상도(Size) 구하는 방법




Android API 중, 화면 사이즈를 구하는 방법은 아래와 같다.

1. 'Metrics' 사용
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int deviceWidth = displayMetrics.widthPixels;
int deviceHeight =displayMetrics.heightPixels;

2. 'Display' 사용
Display display = getWindowManager().getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();

추가로 문의 사항이나, 궁금한 점이 계시면 연락주세요.
(joonryang@gmail.com)

[Android Course][English][Theme] - screenOrientation / Rotation





Android 'Rotation / screenOrientation' Let's examine each of the relevant information.

1. screenOrientation
(1) 'Xml' Setting
: "AndroidManifest.xml" in the Activity Tag "android: screenOrientation" When you are setting.
- Portrait: 'vertical' Show only
- Landscape: 'horizontal' Show only
- Norsensor: 'horizontal and vertical' transitions both X
- Sensor: 'Aspect' convert all O
=> Cons: phone 'Settings - System - Display - Automatic screen rotation feature and independent works.
In other words, the 'Auto Screen Painting' and 'Diable' rotation is set to'm in is the problem.
- Unspecified: 'Aspect' convert all O
=> Features: Pawn 'Settings - System - Display - Automatic screen rotation feature based on the works.
In other words, the 'Auto Screen Painting' and 'Diable' If you set the rotation does not work.

(2) 'Code' Setting
: Code on the "setRequestedOrientation ()" API to be used.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
...ETC...

2. 'Rotation' NOTICE
: Android will support the screen rotation feature.
However, if there is any set, each time rotating existing Activity does not preserve the Data. In other words, the horizontal / vertical conversion while at the UI Activity of a newly drawn onDestroy () and onCreate () is being performed.

1) 'onDestroy() & onCreate()' How not to reload
- 'AndroidManifest.xml' Setting
 : android:configChanges="keyboardHidden|orientation"

- 'Code' Setting
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    switch(newConfig.orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            .....working......
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            .....working......
            break;
    }
}
: Activity is being reloaded because the screen size remains unchanged. Therefore, 'Code' section of the above would have to work.

2) 'onDestroy() & onCreate()' 호출 시, Data Backup 방법
 - Screen rotation, Data Save.
: 'Public Object onRetainNonConfigurationInstance ()' on the screen, in turn, is to store the data coding.

public Object onRetainNonConfigurationInstance() {
    HashMap<String, Object> DataBackup = null;
    DataBackup = new HashMap<String, Object>();
    ...... Data Save Working.....
    return DataBackup;
}

- 'OnCreate ()' call back, Data Loading.
: 'Public void onCreate (Bundle savedInstanceState)' call back, 'Data Loading' job is.
public void onCreate(Bundle savedInstanceState) {
    ....
    Object obj = getLastNonConfigurationInstance()
    if (obj != null) {
        HashMap<String, Object> DataBackup = (HashMap<String, Object>) obj;
        ..... Data Loading .....
    }
    ....
}

3. AVD(Android Virtual Device) Horizontal / vertical mode switching Tip
: Android aemyulreyiteoin AVD (Android Virtual Device) of the 'horizontal and vertical' transition [CTRL] + F11 or [CTRL] + F12 and pressed, the screen 'aspect' is turned into.
While pressing the Control key and continue pressing the key until you change aneuni attention.

: Function Key
 [CTRL] + F11
 [CTRL] + F12
On the numeric keypad [7] (numeric keypad [7] [NumLock] can be off work)

4. Screen rotation
1) Android 2.1 -Eclar
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int orientation = display.getOrientation();
=> orientation ==  0 :  Vertical Mode
=> orientation  == 1. Horizontal Mode

2) Android 2.2-Froyo
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int rotation = display.getRotation();
=> Surface.ROTATION_0   : Vertical Mode
=> Surface.ROTATION_90  : Horizontal Mode
=> Surface.ROTATION_180 : Vertical Mode
=> Surface.ROTATION_270 : Horizontal Mode

In addition, inquiries, or questions, please contact us.
(joonryang@gmail.com)

[Android강좌][Korean][테마] - screenOrientation / Rotation





Android 'Rotation / screenOrientation' 에 관련된 내용을 하나씩 살펴보자.

1. screenOrientation
(1) 'Xml' 설정
: “AndroidManifest.xml” 에서 Activity Tag 에 "android:screenOrientation"을 설정하면 된다.
- portrait : '세로'만 보기
- landscape : '가로'만 보기
- norsensor : '가로/세로' 모두 전환 X
- sensor : '가로/세로' 모두 전환 O
=> 단점 : 폰의 '설정-시스템-디스플레이-자동화면 회전' 기능과 무관하게 동작한다.
즉, '자동화면 화전'을 'Diable'로 설정하더라고 회전이되는 것이 문제다.
- unspecified : '가로/세로' 모두 전환 O
=> 특징 : 폰의 '설정-시스템-디스플레이-자동화면 회전' 기능에 따라 동작한다.
즉, '자동화면 화전'을 'Diable'로 설정한다면 회전이 동작하지 않는다.

(2) 'Code' 설정
: Code 상에서 “setRequestedOrientation()” API를 사용하면 된다.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
...ETC...

2. 'Rotation' 주의 사항
: 안드로이드는 화면 회전 기능을 지원한다.
하지만, 아무런 설정이 없다면, 회전 할 때마다 기존에 있던 Activity의 Data를 보존하지 않는다. 즉, 가로/세로 전환 시에 UI가 새로 그려지면서 Activity의 onDestroy()와 onCreate()가 수행되기 때문이다.
1) 'onDestroy() & onCreate()' 다시 로딩하지 않는 방법
- 'AndroidManifest.xml' 설정
 : android:configChanges="keyboardHidden|orientation"

- 'Code' 설정
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    switch(newConfig.orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            .....working......
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            .....working......
            break;
    }
}
 : Activity가 다시 로딩되지 않기 때문에 화면의 크기는 변하지 않는다.  그러므로 'Code' 부분에서 위의 작업을 해주어야 한다.

2) 'onDestroy() & onCreate()' 호출 시, Data Backup 방법
 - 화면 회전 시, Data Save.
: 'public Object onRetainNonConfigurationInstance()'에 화면 회전시, 데이터를 저장하는 코딩을 한다.

public Object onRetainNonConfigurationInstance() {
    HashMap<String, Object> DataBackup = null;
    DataBackup = new HashMap<String, Object>();
    ...... Data Save Working.....
    return DataBackup;
}

- 'onCreate()' 다시 호출 시, Data Loading.
: 'public void onCreate(Bundle savedInstanceState)' 다시 호출 시, 'Data Loading' 작업을 한다.
public void onCreate(Bundle savedInstanceState) {
    ....
    Object obj = getLastNonConfigurationInstance()
    if (obj != null) {
        HashMap<String, Object> DataBackup = (HashMap<String, Object>) obj;
        ..... Data Loading .....
    }
    ....
}

3. AVD(Android Virtual Device) 가로/세로 모드 전환 Tip
: 안드로이드 애뮬레이터인 AVD(Android Virtual Device)의 '가로/세로' 전환은 [CTRL] + F11 또는 [CTRL] + F12를 누르면, 화면이 '가로/세로'로 전환된다.
※ 컨트롤 키를 계속 누른상태에서 키를 계속 누르면 바뀌지 않으니 주의.

: Function Key
 [CTRL] + F11
 [CTRL] + F12
 숫자키패드의 [7](숫자키패드의 [7]은 [NumLock]이 꺼져 있어야  작동 가능)

4. 화면 회전 각도
1) Android 2.1 -Eclar
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int orientation = display.getOrientation();
=> orientation ==  0 :  세로
=> orientation  == 1. 가로

2) Android 2.2-Froyo
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int rotation = display.getRotation();
=> Surface.ROTATION_0   : 세로
=> Surface.ROTATION_90  : 가로
=> Surface.ROTATION_180 : 세로
=> Surface.ROTATION_270 : 가로

추가로 문의 사항이나, 궁금한 점이 계시면 연락주세요.
(joonryang@gmail.com)
※ 도움이 되셨다면, ^^. 맨 위 광고클릭 좀..ㅎㅎ

[Android Course][English][Theme] - AsyncTask




Thread normal use, the following have been using a lot.
First, Subclassing the Thread class to define a new object that fired Thread: run () method to override.
Second, the new operator to create a new Thread object as an argument and creates the Runnable interface (including logic executed on the thread) is the way forward.

If these methods complicated and Logic, management seems to be harder.
So I was looking the other way was found during a New Class.
That "AsyncTask" Class is.



AsyncTask (Asynchronous Task) - [Overview]

: Background working in all aspects of Android (thread object creation, use, UI thread and communication, etc.), especially in the Activity code is included in the background thread is the UI widgets and more frequent communication, more and more hungry Activity Code because of the complexity, the problem To solve the API level 3 (1.5 version) that provides a class called from the AsyncTask.

: AsyncTask class every day for a background task (thread creation, job execution, UI and communications, etc.) are abstractions.
And each of the 'background' task implementation and management of objects in units that aims to be convenient.

AsyncTask (Asynchronous Task) - Usage











: AsyncTask look at the inheritance relationship,
AsyncTask a Generic Class that inherits from Object, because you must specify the type you want to use. AsyncTask class must be specified when using the generic type is used for each of the following.
     - Params: doInBackground () data type of the specified
     - Progress: onProgressUpdate () data type for the specified
     - Result: onPostExecute () data type of the specified

- AsyncTask Class Base.
private class receiveRollback extends AsyncTask<Object, Object, Object> {

  // UI Thread AsynchTask CallBack is executed by the first
  protected void onPreExecute() {
  }

  // UI Thread AsynchTask actual work done by the CallBack
  protected String doInBackground(Object... params) {
    return result;
  }

  // OnInBackground CallBack for displaying the progress of work
  protected void onProgressUpdate(Object... progress) {
  }

  // Once onInBackground CallBack automatically runs
  protected void onPostExecute(Object result) {
  }

  // Cancel this operation is executed when onInBackground CallBack
  protected void onCanelled(){
  }
}



※ 주의 사항
1) AsyncTask class should always be used by subclassing.

2) AsyncTask instance is always created on the UI thread.
3) AsyncTask: execute (...) method is always invoked in UI thread.

4) AsyncTask: execute (...) method generated by AsyncTask instance can be used just once. Another such instance execute (...) When you run the exception occurs, which AsyncTask: cancel (...) method has been canceled by the work done before the same is true if AsyncTask instance. So the background work needed for the task using the new operator creates a new instance should AsyncTask.

5) The callback function ncTask onPreExecute (), doInBackground (...), onProgressUpdate (...), onPostExecute (...) should not be called directly. (I only use callback)

[Example Test Code]
1. main.xml
<?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" >
 <ProgressBar
  android:id="@+id/progressbar"
  style="?android:attr/progressBarStyleHorizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:paddingBottom="20px" />

 <TextView 
  android:id="@+id/result"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Result"
     android:paddingBottom="20px" />
    
    <Button
     android:id="@+id/executetask"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="AsyncTask Start" />
   
</LinearLayout>

2. main.java
package com.Example_AsyncTask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class main extends Activity {
 ProgressBar m_progressBar = null;
 TextView m_Result = null;
 Button m_ExecuteTask = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        m_progressBar = (ProgressBar)findViewById(R.id.progressbar);
        m_Result = (TextView)findViewById(R.id.result);
        m_ExecuteTask = (Button)findViewById(R.id.executetask);
       
        m_ExecuteTask.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    new ExampleAsyncTask().execute("1","2","3","4","5","6");
   }
       
        });
    }
   
   
    private class ExampleAsyncTask extends AsyncTask<String, Integer, Long> {     
     // UI Thread AsynchTask CallBack is executed by the first
     @Override
  protected void onPreExecute() {
      m_Result.setText("Background Thread Start");
   super.onPreExecute();
  }
     // UI Thread AsynchTask actual work done by the CallBack
  @Override
     protected Long doInBackground(String... strData) {
   long result = 0;
      int numberOfParams = strData.length;
   
      for(int i=0; i<numberOfParams; i++) {   
       SystemClock.sleep(1000);
       // onProgressUpdate callback
       publishProgress((int)(((i+1)/(float)numberOfParams)*100));
      }   
      return result;
     }
   
  // OnInBackground CallBack for displaying the progress of work
     @Override
     protected void onProgressUpdate(Integer... progress) {
      m_progressBar.setProgress(progress[0]);
     }
   
     //  Once onInBackground CallBack automatically runs
     @Override
     protected void onPostExecute(Long result) {
      m_Result.setText("Background Thread End");
     }
   
     //Cancel this operation is executed when onInBackground CallBack
     @Override
  protected void onCancelled() {
   // TODO Auto-generated method stub
   super.onCancelled();
  }   
    }
}


=> Example Source Code: If you need, please contact us.