티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Android global variable
안드로이드 전역 변수
문제 내용
How can I create global variable keep remain values around the life cycle of the application regardless which activity running.
어떤 액티비티가 실행 중인지와 관계없이 어플리케이션 생명 주기 동안 값이 유지되는 전역 변수를 만드는 방법은 무엇인가요?
높은 점수를 받은 Solution
You can extend the base android.app.Application
class and add member variables like so:
android.app.Application 클래스를 상속하여 다음과 같이 멤버 변수를 추가할 수 있습니다.
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication"
attribute to the existing application tag):
안드로이드 매니페스트에서는 android.app.Application을 구현하는 클래스를 선언해야 합니다. (기존의 application 태그에 android:name=".MyApplication" 속성을 추가하십시오.)
<application
android:name=".MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name">
Then in your activities you can get and set the variable like so:
그런 다음 액티비티에서 다음과 같이 변수를 가져오고 설정할 수 있습니다:
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
가장 최근 달린 Solution
Use SharedPreferences to store and retrieve global variables.
SharedPreferences를 사용하여 전역 변수를 저장하고 검색하세요.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userid = preferences.getString("userid", null);
출처 : https://stackoverflow.com/questions/1944656/android-global-variable
'개발 > 안드로이드' 카테고리의 다른 글
'java.net.SocketException: socket failed: EACCES (Permission denied)' 수정하기 (0) | 2023.02.06 |
---|---|
안드로이드 화면 녹화하기 (0) | 2023.02.06 |
Android WebView가 HTTPS URL을 로드 못하는 문제 수정하기 (0) | 2023.02.06 |
startActivity() 동작 안할 때 확인해 볼 것들.. (0) | 2023.02.05 |
WebView 데이터 로드 후 스크롤뷰가 스크롤되는 문제 수정하기 (0) | 2023.02.05 |