Toast does not appear

109 views Asked by At

I'm developing an Android app and I'm a little bit confused why my Toast is not shown in my app.

The toast is not located in an Activity. Therefore, this is my solution. In the MainActivity:

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

    // Init context
    InstanceHandler.setContextOfMainActivity(this);
}

In the class InstanceHandler:

private Activity mActivity;
public Context mContext;

public void setContextOfMainActivity(Activity activity) {
    mActivity = activity;
    mContext = activity.getApplicationContext();
}

and in the affected class Connection.java (NOT extends Activity) I'm calling the toast:

public class Connection{

    public void test(){
        Toast.makeText(InstanceHandler.mContext, "This is a test", Toast.LENGTH_SHORT).show();
    }
}

But nothing happens. The app aborts the following code after the Toast.

2

There are 2 answers

3
Rishi Paul On BEST ANSWER

Use Just This Over There

Toast.makeText(mContext, "This is a test", Toast.LENGTH_SHORT).show();

Use That Class Like This

public class Connection{
    Context mContext;
    public Connection(Context context) {
        // TODO Auto-generated constructor stub

         mContext = context;
    }

    public void test(){
        Toast.makeText(mContext, "This is a test", Toast.LENGTH_SHORT).show();
    }
}
0
sahu On

It seems that your are using Toast.makeText(..).. outside the InstanceHandler class .If your are using inside other Activity then use that activity directly and if you are using inside InstanceHandler class then use

mContext in place of InstanceHandler.mContext

hope this will helpful to you.