Search code examples
androidexceptionjsonexception

My app crashes when trying to do something with a caught exception


Ok

try {

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            }
        } catch (JSONException e) {

//ERROR WHEN INERTING CODE HERE!.

}<code>

Hi guys!, I just want to know why my app crashes when I write code in the indicated place (see above).. If I leave it blank, nothing happens...

The thing is, I want to show a

Toast.makeText(MainActivity.this, "Couldn't reach the server", Toast.LENGTH_LONG).show();

Why do you think that is?. Thanks in advance


Solution

  • I'm assuming because you're error is

    "Couldn't reach the server"

    you are trying to make network calls, which means your code is in a thread of some sort? You cannot touch UI elements from inside the main thread so move:

    Toast.makeText(MainActivity.this, "Couldn't reach the server", Toast.LENGTH_LONG).show();
    

    Into the postExecute() method of an AsyncTask or use a Handler

    From the docs

    Do not access the Android UI toolkit from outside the UI thread.