user3707644
user3707644

Reputation: 137

Android Calling Method in Activity Class

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

Answers (3)

Sedra Support
Sedra Support

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

Blundell
Blundell

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

Moubeen Farooq Khan
Moubeen Farooq Khan

Reputation: 2885

do it in onCreate Like this

Second second =new Second(this);
second.toast_method();

Upvotes: 2

Related Questions