Reputation:
When my code runs to this line:
Context context = new Activity().getApplicationContext();
An exception throwed:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I've tried to create new Handle()
and add Looper.prepare()
before it, however it doesn't work.
Upvotes: 2
Views: 106
Reputation: 6302
If you are running a method that needs a context, and that method is running in a class that is extended from Activity, then you can get the context of that activity by declaring a variable for that activity, and then in your onCreate method do -> activity=this;
i,e
Activity activity;
//this is globally declared
And inside onCreate do activity=this;
void onCreate(Bundle savedInstanceState)
{
....
activity=this;
....
}
Now you are having the context of your current activity in "activity" variable.You can use this inside your method or pass it as a parameter or whatever you want... And if you are having the method that is not in an Activity class, then you should call it by passing this "activity" variable to that method.
Upvotes: 0
Reputation: 4837
Context in android is not an abstract thing. It is the real context (or you can assume it as environment) of the current state of your application and its components.
So you should not create new instances of 'context' just to use the features it provides. The proper way is to use actual existing Context. And here are two ways:
Upvotes: 1
Reputation: 13
Looking at the exception being thrown there is a chance that you are asking for the context within a class that does not extend Activity of some sort.
You might need to pass the context within the constructor of the class. See example below.
public class ExampleClass {
private Context context;
public ExampleClass(Context context) {
this.context = context;
}
}
And in the Activity class you create the class and pass the context in it.
public class mainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
ExampleClass exampleClass = new ExampleClass(getApplicationContext());
}
}
Upvotes: 0