Invoke Toast in an external class - android

I have an external class and I want to use Toast in this class.
I tried to implement this but I get an error.
How can I do this in easy way without any error?
public class ElevenActivity extends AppCompatActivity {
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eleven);
}
public class MyToast {
public MyToast(String message) {
Toast.makeText(ElevenActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
}
public class externalClass extends SQLiteOpenHelper {
public void CreateDB() {
ElevenActivity.MyToast t = new ElevenActivity.MyToast("Here");
}
}

Just make a Toast in the external class using getApplicationContext(). Like,
public class externalClass extends SQLiteOpenHelper {
public void CreateDB() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}

If you want to provide a method which should be valid for different contexts (e.g. activities), pass this context as parameter.
public static void textToast(String textToDisplay, Context context) { ... }
If you want to call this method from nested inner classes (as is often the case), you can use this as context
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(or implement textToast in the outer class and call it via OuterClass.this.textToast from the nested inner class)
..........

Related

Is it a good practice to access the Actvity's Context in the Presenter class? If no then is there any other better way to do it?

I am new to Android MVP Architecture. As far as I have researched the Presenter should be kept free from any android things like for example: Don't use getActivity or Context in the Presenters. I have written the following code where a BasePresenter is the parent class of all the Presenter classes that I will be using.The BaseView interface is the parent interface of all View classes and BaseActivity class is the parent class of all Activity classes. I have more than one activity and it is required to show Toast messages in all of my activity. So I have written the following code as follows. I am not very sure whether using the getactivity from the presenter class is a good practice or not. If it is not then can anyone suggest any better way to do it?
BasePresenter class
public class BasePresenter<V extends BaseView> {
private V mView;
private Context mContext;
public void attachView(V view) {
mView = view;
mContext=mView.getActivity();
}
public void showToast(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
private Context getContext() {
return mContext;
}
public void detachView() {
mView = null;
}
}
BaseView class
public interface BaseView {
AppCompatActivity getActivity();
}
BaseActivity class
public class BaseActivity extends AppCompatActivity {
public AppCompatActivity getActivity() {
return this;
}
}
MainActivity class
public class MainActivity extends BaseActivity implements MainView {
MainPresenter basePresenter;
#Override
protected void onStart() {
super.onStart();
basePresenter = new MainPresenter();
basePresenter.attachView(this);
}
// some more codes here
switch (item.getItemId()) {
case R.id.about:
basePresenter.showToast("About is Clicked");
break;
case R.id.cart:
basePresenter.showToast("Cart is Clicked");
break;
case R.id.favs:
basePresenter.showToast("Favs is Clicked");
break;
case R.id.home:
basePresenter.showToast("Home is Clicked");
break;
}
}
It is not a good idea. You Presenter (base or otherwise) should not know about Context, Activity, Toast or anything else Android based.
View
displays things.
handles user input and passes it to the Presenter.
Presenter
decides what to do with user input.
gathers data from the model.
tells the View what to do.
So for your example of clicking Buttons and showing Toasts you would need a setup something like:
View Interface
This is how your Presenter will talk to your View. It will be implemented by the Activity.
public interface MainView {
void showToast(String message);
}
Presenter (Base & Main)
BasePresenter has almost no tasks at all. Simply there to bind the View interface. Note the method names in the MainPresenter are ambiguous to things like 'click' to seperate them from the View implementation.
public class BasePresenter<V> {
protected V view;
public void attachView(V view) {
this.view = view;
}
}
public class MainPresenter extends BasePresenter<MainView> {
public void about() {
view.showToast("About was clicked");
}
public void cart() {
view.showToast("Cart was clicked");
}
}
Activity
The Activity implements the View interface. It's responsible for passing user events to the Presenter and actioning the Presenter commands.
public class MainActivity extends AppCompatActivity implements MainView {
private MainPresenter presenter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter = new MainPresenter();
presenter.attachView(this);
Button about = findViewById(R.id.button_about);
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.about();
}
});
Button cart = findViewById(R.id.button_cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presenter.cart();
}
});
}
#Override
public void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In this setup the Presenter no longer knows anything about Android (has no imports from the framework at all) and you are able to write unit tests for it which can run directly on the JVM without Android dependencies.
Toast is actually visible on screen. So It should not be in presenter. It should be triggered from the View.

How can I get Context from a common class?

I know I can use getApplicationContext() to get Context from sub class of ListActivity.
but PublicPar is common class, how can I get Context from this class.
public class SMSMain extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Context my=getApplicationContext();
}
}
public class PublicPar {
public static void SetNotification(){
}
}
If you have a common (helper-type) class like your PublicPar class, the best you can do is to pass context as a parameter to each method:
public static void SetNotification(Context context) {
}
Remember to not set this context to any PublicPar class variable to avoid leaking it.
Try this. It should work:
public class SMSMain extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Context my=getApplicationContext();
new PublicPar().SetNotification(SMSMain.this)
}
}
public class PublicPar {
public static void SetNotification(final Context context ){
// You can proceed with using the context here.
}
}
If you don't want to pass the Context around as part of constructor argument, you can expose a static method in the application.
public class MyApplication extends Application {
private static MyApplication myinstance;
public MyApplication() {
myinstance = this;
}
public static Context getAppContext() {
myinstance.getApplicationContext();
}
}

Android: call method of overrided class from library

In this example I have an app which is playing mp3 songs, but there are different license checks by companies.
So in my library I have 3 files:
public interface UserCheckerInterface {
public void appIsEnabled(boolean result);
}
public class UserChecker {
public static void appisEnabled(final UserCheckerInterface userCheckerInterface) {
userCheckerInterface.appIsEnabled(true);
}
}
public class MainActivity extends Activity {
#Override
public void onCreate(final Bundle savedInstanceState) {
....
UserChecker.appisEnabled(new UserCheckerInterface(
#Override
public void appisEnabled(final boolean result) {
Toast.makeText(getApplicationContext(), "" + result, 0).show();
}
));
}
}
I would like override the UserChecker.appisEnabled method in my app which is using this library, but I don't know how.
I am not sure whether I have understood your question, if I did, than you simply have to implement your interface by writing
public class UserChecker implements UserCheckerInterface{
#Override
public static void appisEnabled(final UserCheckerInterface userCheckerInterface) {
userCheckerInterface.appIsEnabled(true);
}
}
Once you do that, then the IDE will show you an error IF you have not implemented the method; which is not the case in this scenario.

Call a public method in the Activity class from another class?

MAIN ACTIVITY
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void Mymethod()
{}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyClass(Context context)
{
}
}
I tried to call Mymethod() from an instance of MyClass.
I would really appreciate any help. Thanks.
Why not just pass the activity to the constructor like
public class MyActivity extends Activity {
onCreate(){
MyClass myobj=new MyClass(MyActivity.this);
}
public void myMethod(){
}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass{
public MyClass(MyActivity act) {
act.myMethod();
}
}
Make that method as static so you can call without creating the class object
public static void Mymethod()
{}
and call like this way
MainActivity.Mymethod();
This is probably the best way to do it. This is how I'm doing it. It's called a Singleton Design Pattern:
public class MyActivity extends Activity {
private static MainActivity instance;
public static MainActivity getInstance() {
if(instance==null){
setInstance(this);
}
return instance;
}
public static void setInstance(MainActivity instance) {
MainActivity.instance = instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setInstance(this);
}
}
If I'm understanding you correctly I believe you can solve your problems using an interface as a callback.
////ACTIVITY/////////////////////////////////
public class MyActivity() extends Activity {
onCreate()
{
MyClass myObj=new MyClass();
//Set the listener on the object. Created as anonymous
myObj.setListener(new MyClass.Listener() {
myMethod();
});
}
}
public void myMethod(){
}
//////Custom Class//////////////////
public class MyClass {
Listener mListener;
public interface Listener {
public void onInterestingEvent();
}
public void setListener(Listener listener) {
mListener = listener;
}
public void someUsefulThingTheClassDoes() {
//Do your code here and when you're ready to call the activity's method do this
mListener.onInterestingEvent();
}
}
I had an inner class that I wanted to pull out into a more general library "Helper" class. I had the same issue you do. I got around it by making the helper class abstract, with a single abstract method. Then in my project package I extended the helper class with a constructor call in the specific class.
public class MyActivity extends Activity {
onCreate() {
MyHelperClass = new MyHelperClass(this, "foobar");
}
public void myMethod() {
// Code...
}
}
// In a different file
public class MyHelperClass extends HelperClass {
private MyActivity mInstance;
public MyHelperClass(MyActivity act, String data) {
super();
this.mInstance = act;
this.mActivity = act; // Useful for calling generic Activity methods in the HelperClass
this.mData = data;
}
protected void callMyActivityMethod() {
mInstance.myMethod();
}
}
// In a different file
public abstract class HelperClass {
protected Activity mActivity;
protected String mData;
public HelperClass() {
// Subclass will set variables
}
protected abstract void callMyActivityMethod();
// More code for all the other stuff the class does
}
In this way, I have a helper class that contains the vast majority of the "work", and all I have to do is make a subclass with the constructor and one method in order to get access to the calling activity's method of interest.
You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Instance of AnotherClass for future use
private AnotherClass anotherClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Create new instance of AnotherClass and
// pass instance of MainActivity by "this"
anotherClass = new AnotherClass(this);
}
// Method you want to call from another class
public void myMethod(){
...
}
}
AnotherClass.java
public class AnotherClass {
// Main class instance
private MainActivity mainActivity;
// Constructor
public AnotherClass(MainActivity activity) {
// Save instance of main class for future use
mainActivity = activity;
// Call method in MainActivity
mainActivity.myMethod();
}
}
In MainActivity.class file
You have to pass MainActivity context from MainActivity Class. Then in MyClass you have to Get MainActivity context. Remember Context and MyActivity are two different reference.
public class MyActivity extends Activity
{
onCreate(){
MyClass myobj=new MyClass(MyActivity context);
}
public void Mymethod(){}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyActivity context;
MyClass(MyActivity context)
{
this.context = context;
this.context.Mymethod();
//Or you can directly use activity context
context.Mymethod();
}
}
I decided to write the HelperClass MyClass as an inner class of MyActivity class. This allows it full access to parent class but the bad thing is now MyClass is restricted to MyActivity class only.
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void myMethod()
{
}
}
//INNER CLASS
public class MyClass
{
public MyClass()
{
}
//I can directly access the MyMethod
myMethod();
}

How to access Activity UI from my class?

I have an activity which creates an object instance of my class:
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
...
Points myPoints new Points();
...
}
--------------------------------------------------------------
file Points.java:
private class Points {
...
HOW TO USE myView HERE ???
...
}
--------------------------------------------------------------
How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?
see you post, i've edited it , to fix the problem
hope it helps :=)
here is the Edit :
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView ;
protected void onCreate(android.os.Bundle savedInstanceState) {
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points(this);
myPoints.displayMsg("Hello World !!!");
}
}
--------------------------------------------------------------
file Points.java:
private class Points {
protected MyActivity context;
//add a constructor with the Context of your activity
public Points(MyActivity _context){
context = _context;
}
public void displayMsg( final String msg){
context.runOnUiThread(new Runnable() {
#Override
public void run() {
context.myView.setText(msg);
}
});
}
}
Your Points can't be a private class without being an inner class. So your code doesn't even compile...
Pass the view as parameter to the constructor of your Points class:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
Points myPoints new Points(myView);
private class Points {
public Points(TextView view) {
// todo
}
}
}
You should do everything and pass back the value to the activity to handle UI instead of doing any UI related stuff in the point stuff.
You can pass the main Activity's context (using Points(getApplicationContext());) to the class as a constructor parameter. You could also pass the specific UI elements you want to manipulate.
A better way to do it, however, may be to have Points not know about the Activity. Have your Activity call Points methods and take the necessary actions based on the method output.
You could just pass the view to your class.
Points myPoints = new Points(myView);
private class Points
{
private TextView mTextView;
Points(TextView textView)
{
this.mTextView = textView;
}
}
i was in same trouble..
i found the simple way..
make a static variable and function ...
call from other class..
TestActivity.java
public class TestActivity extends Activity {
static EditText edit_text1;
public void onCreate(Bundle savedInstanceState)
{
.....
edit_text1 = (EditText) findViewById(R.id.edit_text1);
.....
}
public static void setMSG(String str)
{
edit_text1.setText(str);
}
}
Test2.java
TestActivity.setMSG("this is text");
Could work using an interface
file MyActivity.java:
public class MyActivity extends Activity implements Points.MyListener {
TextView myView;
... onCreate(...){
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points();
//pass in MyActivity's instance of the listener
myPoints.addListener(this);
}
#Override
public void updateTextView(String message){
myView.setMessage(message);
}
}
file Points.java:
public class Points {
public Points(){
}
public interface MyListener{
void updateTextView(String message);
}
MyListener myListener;
public void addListener(MyListener listener){
myListener = listener;
}
public void updatePoints(){
//do some operations in calculatePoints()
String points = calculatePoints();
//update views using MyActivity's implementation of updateTextView()
myListener.updateTextView(points);
}
}
Doing it this way, events can be fired / messages sent, for lack of better terms, from the external class to update the Activity UI. This might be overkill if all sb need is to call a method in the Points class that returns something

Categories

Resources