0

I tried everything, this Using Application context everywhere? and few things more and nothing works.

I need the application context in my DatabaseException class which extends Exception. I need it because I want to check some sharedpreferences when the exceptions are launched. The code basically is this:

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);

of course this doesn't work. So... please, somebody can help me?

4

3 回答 3

1
public class DatabaseException extends Exception {

private static final long serialVersionUID = 1L;

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

Now if you catch the exception:

try {
    ...
} (catch DatabaseException e) {
    MyContext context = e.context;
}
于 2012-10-23T13:38:53.717 回答
0

It is Simply.. you can not. But when the Execption is raised you can perform

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

the operation you need in the catch clause.

You could pass it as paramter but, please, avoid it.

于 2012-10-23T13:33:57.317 回答
0

Quick answer:
1. Add application context as parameter of the DatabaseException construtor.
2. Put your DatabaseException as other class's inner class. (Other class means Activity...), so you can use fields/method of outer class in the inner class.
3. ...

于 2012-10-23T13:40:24.997 回答