0

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?

Reno
  • 33,594
  • 11
  • 89
  • 102
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • You are probably getting down-votes because you did not post the relevant Log-cat output. – Reno Jul 11 '11 at 01:44

1 Answers1

4

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())
    ........
takrl
  • 6,356
  • 3
  • 60
  • 69
Andrew Young
  • 76
  • 1
  • 6