2012-07-04 2 views
1

나는 안드로이드 애플리케이션을 개발 중이며 애플리케이션 클래스에 글로벌 변수를 유지 관리 중이다. MyAppData. 내 활동으로안드로이드 : BaseAdapter 클래스에서 애플리케이션 클래스 객체를 생성하는 방법

MyAppData mad; 
mad = (MyAppData)getApplication(); 

사용자 정의 목록보기가 나는 LstView를 채울 BaseAdapter을 사용하고 있습니다 : 이제 그 전역 변수를 사용하기 위해서는 다음과 같이 내 활동에 MyAppData 객체를 생성하고있다. 이제 BaseAdapter 클래스에서 전역 변수를 사용해야합니다. 나를 MyAppData 클래스의 객체를 생성 할 수 있도록 다음 코드 나던 :

public class AlbumList_Adapter extends BaseAdapter{ 
Context context; 
MyAppData mad; 

     public AlbumList_Adapter(Context context){ 
     this.context = context 
     mad = (MyAppData)getApplication(); 
     } 
} 

심지어 나는 mad = (MyAppData)context;하지만 행운을 시도했다. 내가 잘못 본 것을 모른다.

+0

http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android/3827166#3827166 –

+0

어떤 종류의 전역 변수가 있습니까? 이것은 아마도 나쁜 설계 일 것입니다. – Egor

+0

그리고 코드를 추가로 만들면 * 객체가 생기지 않습니다. 객체를 얻게됩니다. – pawelzieba

답변

9

당신은 할 수 있습니다 :

class MyApplication extends Application { 

private static MyApplication mInstance; 

@Override 
public void onCreate() { 
    super.onCreate(); 
    mInstance = this; 
} 

public static MyApplication getInstance() { return mInstance; } 

} 

그런 다음 당신은 당신의 코드를 통해 MyApplication.getInstance()를 사용할 수 있습니다.

+0

답장을 보내 주셔서 감사 드리며 죄송합니다. 이제 완벽하게 작동했습니다 –

+0

+1이 도움이되었습니다! –

관련 문제