radioactive
radioactive

Reputation: 91

how to call toast from another class in android

i want to call toast from another class's method

i have MainActivity.java

package cZ.example.z;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    public void p(View v){

        newclass  inst = new newclass();
        inst.mmm();


    }

}

where p is button1 (ie. android:onClick)

and newclass.java

package cZ.example.z;

import android.app.Activity;
import android.widget.Toast;


public class newclass extends Activity {

    public void mmm(){
        Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();

    }
}

when i clock button1 (p) my app force close but i want to show toast from another class method when click button

any solution

Upvotes: 1

Views: 9543

Answers (1)

Ravi Bhandari
Ravi Bhandari

Reputation: 4698

See below code:

public class Utils{

         public static void showToast(Context mContext,String message){
             Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
         }
}

and call this method from when ever you want like -

Utils.showToast(activity, "hello");

hope i m hellpfull to you.

Upvotes: 12

Related Questions