2017-02-09 1 views
0

전체 응용 프로그램주기에서 다른 단계에서 필요한 전역 변수를 만들었습니다. 아래는 GlobalVariable.java가 생성됩니다안드로이드에서 ArrayList를 글로벌 ArrayList로 옮기기

import android.app.Application; 

public class GlobalVariable extends Application { 
    private String globalVariableOne; 

    public String getGlobalVariableOne() { 
     return globalVariableOne; 
    } 

    public void setGlobalVariableOne(String globalVariableOne) { 
     this.globalVariableOne = globalVariableOne; 
    } 
} 

그럼 난 쉽게 가서 아래의 코드를 사용하여 모든 활동에서이 글로벌 변수를 설정할 수 있어요.

final GlobalVariable globalVariable = (GlobalVariable) getApplicationContext(); 

//To Set the globalVariableOne Value in an Activity 
globalVariable.setGlobalVariableOne("My Value"); 

//To Get the globalVariableOne Value in a 
String readGlobalVariableOne = globalVariable.getGlobalVariableOne(); 

지금 내 활동에 아래의 코드를 사용하여 만든 ArrayList에 localArrayList 있습니다.

List<String> localArrayList = new ArrayList<String>(); 

int maxLength = "10"; 

for (int i = 0; i < maxLength; i++) { 
    String valueOne = "Value "+i; 
    String valueTwo = "Value "+i; 

    localArrayList.add(valueOne)); 
    localArrayList.add(valueTwo); 
} 

이 ArrayList를 내 응용 프로그램 내의 모든 활동에서 액세스하고 편집 할 수있는 전역 ArrayList로 저장하려고합니다. 어떻게해야할지 모르겠다.

누구나 내 GlobalVariable.java를 편집하여 Global ArrayList를 정의하고이 전역 ArrayList를 가져오고 설정하는 방법을 안내해 줄 수 있습니까?

답변

0

그것은이처럼 될해야합니다

public class GlobalVariable extends Application { 
    private String globalVariableOne; 
    private List<String> globalArrayList; 

    public String getGlobalVariableOne() { 
     return globalVariableOne; 
    } 

    public void setGlobalVariableOne(String globalVariableOne) { 
     this.globalVariableOne = globalVariableOne; 
    } 

    public List<String> getGlobalArrayList() { 
     return globalArrayList; 
    } 

    public void setGlobalArrayList(List<String> globalArrayList) { 
     this.globalArrayList = globalArrayList; 
    } 
} 

을 그럼 당신은 당신이 할 수있는 코드에서 :

GlobalVariable myAppClass = (GlobalVariable)getApplicationContext(); 
//saving the list 
myAppClass.setGlobalArrayList(/*put here the list to save*/); 
//getting the list 
List<String> globalArrayList = myAppClass.getGlobalArrayList(); 

을하지만 난 정말 응용 프로그램 사용자 정의 내부의 모든 전역 변수를두기의이 방법을 좋아하지 않는다 클래스 ...

+0

무엇이 좋습니다? 안내해주십시오. –

+0

이 솔루션을 기반으로 설정하고 설정하는 방법은 무엇입니까? 이것은 Android Studio가 나를 위해 자동 생성하는 것입니다. 그러나 localArrayList를이 전역 ArrayList로 전송하는 방법을 모르겠습니다. –

+1

나는 내 대답을 업데이 트했습니다, 당신은 데이터베이스, 공유 환경 설정, 파일, 번들 (활동 사이에 작은 데이터를 이동하는 등) 등 .. 응용 프로그램의 모든 부분에서 사용하기 위해 데이터를 저장하는 데 사용해야합니다. – MatPag

관련 문제