Search code examples
androidtry-catchtoast

Where should I put toast statement in the try statement after finish()?


I am facing error when doing toast statement in a try statement. Here is my code. Currently put a toast statement in this way (commented format). May I know what is the correct way of putting? Thanks.

try {
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
    HttpResponse response = httpclient.execute(httppost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String response1 = httpclient.execute(httppost, responseHandler);
    System.out.println("Response : " + response1); 
    if(response1.contains("Duplicated")){
        finish();
    }
    //{Toast.makeText(getBaseContext(), "You have registered this event before.", Toast.LENGTH_LONG).show();}
    {
        jsonResult = inputStreamToString(
        response.getEntity().getContent()).toString();
    }

    catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Solution

  • Thanks for the help guys. I have fixed it myself.

        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
            HttpResponse response = httpclient.execute(httppost);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response1 = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response1); 
            if(response1.contains("Duplicated")){
    
                Register.this.runOnUiThread(new Runnable() {
    
                    public void run() {
                        Toast.makeText(Register.this, "You have registered this event before.", Toast.LENGTH_LONG).show();
    
                    }
                });
    
                finish();
            }
            jsonResult = inputStreamToString(
            response.getEntity().getContent()).toString();
        }
    
        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
    }