Reputation: 137
I have java class called Second.java which has a method called toast_method(). My question is, How can i call the toast_method() from the Second.java and then display the toast message in the app?
I tried the following code but it's not working
Second.java
package com.example.callmethod;
import android.content.Context;
import android.widget.Toast;
public class Second {
Context context;
public Second(Context context) {
this.context = context;
}
public void toast_method() {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();
}
}
MainActivity.java
package com.example.callmethod;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
private Second myotherclass;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass.toast_method();
}
}
Thanks
Upvotes: 1
Views: 3391
Reputation: 34
Easy one ^^
you have to extends Activity to use context in the activity
public class operation extends Activity {
// normal toast
//you can change length
public static void toast(String toastText, Context contex) {
Toast.makeText(contex, toastText, Toast.LENGTH_LONG).show();
}
// Empty Toast for Testing
public static void emptyToast(Context contex) {
Toast.makeText(contex, R.string.EmptyText, Toast.LENGTH_LONG).show();
}
}
now ... in your activity only call function
operation.toast("Your Text",currentClass.this);
Example :
public class currentClass extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
operation.toast("Hello",currentClass.this);
}
}
Upvotes: -1
Reputation: 76476
You are nearly there! Only missing the vital instantiation of the second class:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Calling the method from Second Class
myotherclass = new Second(this); // <----- this
myotherclass.toast_method();
}
Upvotes: 3
Reputation: 2885
do it in onCreate Like this
Second second =new Second(this);
second.toast_method();
Upvotes: 2