user3319474
user3319474

Reputation: 113

Close exception in MainActivity gracefully

I newbie to Android development and I have a question. I already look for this question in forum but no luck.

My MainActivity onCreate tries to connect to a sever. In some cases the server can be down, and in this case, my app throw exception. What should I do to finish the Activity gracefully?

I have tried to Toast a message and to finish() the activity but no message appears and the activity still running.

Whats wrong with my code ?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            mSocket = new Socket("127.0.0.1", 6000);
            try {
                conn = new ClientConnection(mSocket.getInputStream(),mSocket.getOutputStream());
                GameSurfaceView gameSurface = (GameSurfaceView)findViewById(R.id.Game);

                conn.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        } catch (UnknownHostException e) {
            Log.e(TAG, "Unknown Host Exception");
            e.printStackTrace();
            Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT);
            finish();

        } catch (IOException e) {
            Log.e(TAG, "IO Exception");
            Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
            finish();

        }
        catch (Exception e) {
            Log.e(TAG, "Exception");
            Toast.makeText(this, "IO Exception", Toast.LENGTH_SHORT);
            finish();
        }

        Log.v(TAG,"Activity created");

    }

Upvotes: 0

Views: 72

Answers (1)

nitzanj
nitzanj

Reputation: 1699

  1. Don't ever run network code in the UI thread. onCreate is the UI thread - You should never do any IO, network or other long processing task there. Read http://developer.android.com/training/best-background.html for more details.
  2. Your toast is in the catch clause of the out try block - however all IOExceptions (including the UnknownHostException) are already caught in the inner try block. In there you only print the stack trace. That's why no message is ever shown. I don't see a need for two nested try blocks, one is probably all you need.
  3. Assuming your app cannot run without server connection, the right approach would be to let the user know somehow that that's the case (AlertDialog, Toast, whatever) and then call Finish() on the activity to close it.

Edit: As pointed out in a deleted answer, calling show() is of course also needed in top of what I already mentioned:

Toast.makeText(this, "Unknown Host Exception", Toast.LENGTH_SHORT).show();

Upvotes: 1

Related Questions