레이블이 Android인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Android인 게시물을 표시합니다. 모든 게시물 표시

2017년 6월 19일 월요일

[Android] Cursor 전체를 탐색하는 가장 안정적인 코드

여러가지 방법이 있지만, 제가 가장 바람직하다고 생각하는 방법입니다.

if (cursor != null) {
    if (cursor.moveToFirst()) {
        do {
            // access cursor items
        } while (cursor.moveToNext());
    }

    cursor.close();
}


moveToFirst() : Cursor를 가장 처음 item을 가리키도록 조작하고, item이 하나도 없다면 false를 return함. (정상동작시 true)

moveToNext() : Cursor를 현재 item의 다음 item을 가리키도록 조작하고, 이미 가장 마지막 item이라면 false를 return함. (정상동작시 true)

※ 주의 : cursor != null 과 moveToFirst()를 한번에 확인하면 Cursor를 close()할 조것을 놓치게 됨.

[Android] 어디서나 Context 가져오기


Android 프로그래밍을 하다보면 Context를 요구하는 API들을 많이 접하게 됩니다.

원칙적으로는 현재 루틴을 수행하는 owner component의 Context를 사용하는 것이 좋으나

다음과 같이 Application class를 사용하여 간단히 global Context를 어디에서나 사용할 수 있는 방법도 있습니다.

Android platform에서 singleton을 보장해주는 Application class를 이용하면 됩니다.

1. ApplicationClass.java 작성

// ApplicationClass.java

import android.app.Application;
import android.content.Context;

public class ApplicationClass extends Application {
    private static Context mContext;

    public ApplicationClass() {
        super();

        mContext = this;
    }

    public static Context getContext() {
        return mContext;
    }
}


2. AndroidManifest.xml에 등록


<Appilcation... android:name=".ApplicationClass" ... />



    
        
            
                
                
            
        
    


3. 사용법


Applicatoin 어디에서나...
    // 사용법

    Context globalContext = ApplicationClass.getContext();