开发者

How do I make a toast from outside of the main activity

I was trying to show a toast outside of the main activity and it crashed.

public class TCPConnection implements NetworkInterface{

    private final static String TAG = "TCPConnection";
    private final static String开发者_运维技巧 IP = "1.1.1.1";
    private final static String PORT = "12001";

    public boolean onDataSend(Work work){

        boolean sent = false;

        if(mRunning){
            try {
                //Log.i(TAG, "onDataSend!");
                mOut.write(work.getbData());
                sent = true;

            } catch (IOException e) {
                sent = false;
                mDelegate.setRun(false);
                e.printStackTrace();

                Toast.makeText(mContext, "Connection has been lost", Toast.LENGTH_LONG).show();             

                try {
                    stop();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }   
        }
    }

I am passing Context using getApplicationContext();

How can you create a toast from outside of the main activity?


Try this:

public boolean onDataSend(Work work, Context mcontext){
    ........
    Toast.makeText(mContext, "Connection has been lost", Toast.LENGTH_LONG).show();
    .......

when you call the method:

    onDataSend(work,MainActivity.this.getApplicationContext())
    ........
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜