티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Using context in a fragment

Fragment에서 Context 사용하기

 문제 내용 

How can I get the context in a fragment?

어떻게 하면 fragment의 context를 얻을 수 있을까요?

 

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

생성자가 컨텍스트를 사용하는 데이터베이스를 사용해야 하지만 getApplicationContext() 및 FragmentClass.this는 동작하지 않습니다. 어떻게 해야 하나요?

 

Database constructor

데이터베이스 생성자

 

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

 

 

 높은 점수를 받은 Solution 

You can use getActivity(), which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).

getActivity()를 사용하면 fragment와 관련된 Activity를 반환할 수 있습니다. Activity는 컨텍스트입니다.(Activity는 Context를 상속하기때문에).

 

 

 

 가장 최근 달린 Solution 

requireContext() method is the simplest option

requireContext() 메서드가 가장 간단한 옵션입니다.

 

requireContext()

Example

 

MyDatabase(requireContext())

 

 

출처 : https://stackoverflow.com/questions/8215308/using-context-in-a-fragment

반응형
댓글
공지사항
최근에 올라온 글