2016-06-15 4 views
-2

strings.xml 파일에 문자열 값을 가져 오는 데 getResources()을 사용하고 있습니다. 이 같은 유사한 내 수업에서 변수 생성 :android에서 getResources를 사용하여 null 객체에 가상 메소드를 호출하려고 시도했습니다.

public class Example extends Activity { 
    String okhttp_tp = getResources().getString(R.string.okhttp_tp); 
    // The rest of my script. 
} 

을 그리고 나는이 .addHeader("X-Client-Type", okhttp_tp) 같은 OKhttp 요청과 함께 사용 할 때 나는 내 응용 프로그램 실행 할 때 직접 나에게 오류를 제공합니다

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference 

나는 다음과 같은 규칙을 시도 :

:

1. String okhttp_tp = getResources().getString(R.string.okhttp_tp); 
2. String okhttp_tp = (String) getResources().getString(R.string.okhttp_tp); 
3. String okhttp_tp = getResources().getString(R.string.okhttp_tp).toString(); 
4. String okhttp_tp = (String) getResources().getString(R.string.okhttp_tp).toString(); 
5. String okhttp_tp = Example.this.getResources().getString(R.string.okhttp_tp); 

나는 또한이 작업을 수행하려

String doPostRequest(String url, String json[]) throws IOException { 
    Request request = new Request.Builder() 
     .addHeader("X-Client-Type", getResources().getString(R.string.okhttp_tp).toString()) 
     .url(okhttp_login_url) 
     .url(url) 
     .post(body) 
     .build(); 
} 

하지만 이러한 작업과 앱 실행 후 충돌이 발생하지 않습니다. 내가 놓친 게 있니? 내가 잊었던 게 있니?

도움 주셔서 감사합니다.

+1

이 –

답변

0

더 효율적이고 효율적인 방법이 있습니다. strings.xml에 저장하고 검색하는 대신 정적 전역 상수 변수를 만들 수 있습니다.

AppConstants.java

class AppConstants{ 
public static final String ok_http = "value here"; 
} 

사용

String doPostRequest(String url, String json[]) throws IOException { 
    Request request = new Request.Builder() 
     .addHeader("X-Client-Type",AppConstants.ok_http) 
     .url(okhttp_login_url) 
     .url(url) 
     .post(body) 
     .build(); 
} 
+0

고마워, 나는 그것을 시도 할 것이다. (당신이 문법 오류를 가지고 있음을주의하자. 그것은'@ Override'이어야한다. – Jer

+0

하하, IDE 효과가 부족하다. 희망한다. –

+0

당신의 해결책을 시도했지만 이제는 onCreate() 함수 밖의 변수에 접근하고 싶다. 당신이 그걸 어떻게 할 수 있는지 말해 줄 수 있습니까? – Jer

0

활동 수명주기에서 onCreate() 이상의 자원에만 액세스 할 수 있습니다. 인스턴스 초기화 단계가 너무 일 렀습니다.

+0

감사 어떤 방법 내부 대신의 클래스 레벨에서''의 GetResources를 호출해야합니다, 나는 그것을 시도 할 것이다. – Jer

관련 문제