Reputation: 1
I've been working with few widgets but when i run the following Activity
nothing happens.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt =(Button)findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Button is clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
Upvotes: 0
Views: 91
Reputation: 633
Change
Toast.makeText(getBaseContext(), "Button is clicked", Toast.LENGTH_SHORT).show();
To
Toast.makeText(getActivity(), "Button is clicked", Toast.LENGTH_SHORT).show();
Upvotes: 0
Reputation: 16224
You have to get Activity context so replace this:
Toast.makeText(getBaseContext(), "Button is clicked", Toast.LENGTH_SHORT).show();
with this:
Toast.makeText(NameOfYourActivity.this, "Button is clicked", Toast.LENGTH_SHORT).show();
Note that you need to change NameOfYourActivity.this
to have the name of your activity, which isn't shown in your code snippet.
EDIT
You can also use only this
instead of NameOfYourActivity.this
if you are creating toast directly inside Activity context and not in others (e.g. OnClickListener
context)
If you are in fragment use getActivity()
instead of NameOfYourActivity.this
EDIT 2
To complete the answer I'll add also the case in which you need to obtain context in classes that don't extend Activity
or Fragment
(e.g. BaseAdapter
or model classes).
In this case you have to pass context via constructor and use it as global variable. NEVER use a static context if not needed.
public class MyClass {
private Context context;
public MyClass(Context context) {
this.context = context;
}
public void showToastFromHere() {
Toast.makeText(context, "Method in MyClass.class", Toast.LENGTH_SHORT).show();
}
}
and you call the method in your activity creating an instance of that class:
MyClass toastClass = new MyClass(NameOfYourActivity.this);
toastClass.showToastFromHere();
Upvotes: 3
Reputation: 1483
try to change this:
Toast.makeText(getBaseContext(), "Button is clicked", Toast.LENGTH_SHORT).show();
to this:
Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_SHORT).show();
I think you have to use your app context to show Toast, make intents, etc.
Upvotes: 0