0

I'm new with android, and I'm building question's game. Right now, I want to use API to get my question's into my game, the API is return a JSON string, but my app is crash when I'm getting to Intent that using the API Url.

From OnCreate I'm calling function named: get_questions_from_api() That function need to use 'new_questions' ArrayList from class is same to the API, and it crash.

private void get_questions_from_api() {
    String json_str;
    try {
        json_str = new Scanner(new URL("https://opentdb.com/api.php?amount=10").openStream(), "UTF-8").useDelimiter("\\A").next();
        Gson gson = new Gson();
        TypeToken<ArrayList<OpenTDB>> token = new TypeToken<ArrayList<OpenTDB>>(){};
        new_questions  = gson.fromJson(json_str, token.getType());
    }
    catch (Exception e){
        pop_up("error !");
    }
}

I'm looking for all 10 questions will be in my arraylist, but when I start "onCreate" all the app crash. I'm thinking it should be in "asynctask"

XDavidT
  • 147
  • 15
  • 1
    "my app is crash" -- use Logcat to examine the stack trace associated with your crash: https://stackoverflow.com/q/23353173/115145 – CommonsWare Feb 02 '19 at 16:50
  • 2
    You cannot do network request on MainThread. You can use Retrofit/Volley library for network requests. – Ranjan Feb 02 '19 at 16:51

0 Answers0