2012-10-23 3 views
0

나는이 모든 것을 시도했다.이 Using Application context everywhere? 그리고 몇 가지 더 효과가있는 것은 아무것도 없다.예외를 확장하는 클래스에서 컨텍스트를 얻는 방법

Exception을 확장하는 DatabaseException 클래스에 응용 프로그램 컨텍스트가 필요합니다. 예외가 시작될 때 sharedpreferences을 확인하고 싶기 때문에 필요합니다.

public class DatabaseException extends Exception { 

private static final long serialVersionUID = 1L; 

DatabaseException(){ 
    super(); 
} 

DatabaseException(String s){ 
    super(s); 
} 

public DatabaseException (String s, Throwable t){ 
    super (s,t); 
    kindOfException(t.getCause(), s); 
} 

DatabaseException (Throwable t){ 
    super (t); 
    kindOfException(t.getCause(), null); 
} 

...

private void createLog() { 
    Log.d("Database Exception","On Create Log"); 
    String listLogs; 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DatabaseException.class.context); 

물론이 작동하지 않습니다 코드는 기본적으로이입니다. 그래서 ... 제발, 누군가 나를 도울 수 있니?

+2

클래스 및 컨텍스트 매개 변수에 컨텍스트 필드를 생성자에 추가하십시오. – Yahor10

답변

0

간단히 말할 수는 없습니다. Execption가 발생할 때 그러나 당신은

private void createLog() { 
    this.getContext(); 
    Log.d("Database Exception","On Create Log"); 
    String listLogs; 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DatabaseException.. 
} 

당신이 catch 절에 필요한 작업을 수행 할 수 있습니다.

매개 변수로 전달할 수 있지만 제발 피하십시오.

try { 
    ... 
} (catch DatabaseException e) { 
    MyContext context = e.context; 
} 
+0

시도 할 것이지만, 왜 매개 변수로 컨텍스트를 전달하지 않는 것이 좋을지 말해 줄 수 있습니까? – Alberto

+0

메모리 누수가 발생할 수 있습니다. – Blackbelt

+0

고맙습니다. 다른 사람들은 작품에 답변하고 처음에는 원했던 것이 더 가깝습니다. 그러나 그들은 좋은 연습이되어야하는 것보다 패치와 비슷합니다. – Alberto

1
public class DatabaseException extends Exception { 

private static final long serialVersionUID = 1L; 

public YourContext context; 
public DatabaseException(YourContext context){ 
    this.context = context; 
} 
} 

이제 예외를 catch합니다.
2. DatabaseException을 다른 클래스의 내부 클래스로 두십시오. (다른 클래스는 Activity ...를 의미하므로, 내부 클래스에서 외부 클래스의 필드/메소드를 사용할 수 있습니다.
3. ...

0

빠른 대답 : 다음 DatabaseException의 생성자의 매개 변수로
1. 추가 애플리케이션 컨텍스트

+0

다른 클래스의 내부 클래스가 될 수 없습니다. – Alberto

+0

사용 방법에 따라 방법 2가 작동하지 않으며 방법 1을 다른 방법으로 시도하십시오. :) –

관련 문제