1

I'm new to Android Studio and I want to fetch some data using an API from omdb.com, Here is how I do it:

I have created a class:

package com.example.emad.apidemo;

import android.os.AsyncTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class fetchData extends AsyncTask<Void,Void,Void> {

public String data = "";
public String Title ="";

@Override
protected Void doInBackground(Void... voids) {



    try {

        URL url = new URL("http://www.omdbapi.com/?t=the+generation&apikey=42ae84fb");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";

        while(line != null){

            line = bufferedReader.readLine();
            data = data + line;
        }

        JSONArray JA = new JSONArray(data);
        JSONObject JO = JA.getJSONObject(0);
        Title = JO.getString("Title");

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);

    MainActivity.txtResponse.setText(this.Title);
}
}

I want to get the Title value from the following JSON:

{

"Title": "The Generation Game",
"Year": "1971–2001",
}

and this is my mainActivity code:

public void btnFetchData_CLick(View v){

    fetchData process = new fetchData();
    process.execute();

}

When I click on the button, nothing happens!

Why I cannot access any value?

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • if you println(data) do you get what you expect? also i don't get an array back from that URL. i get an object. maybe try new JSONObject(data) and try and read title from that. – mavriksc Sep 11 '18 at 21:13
  • Also check you while loop, the first read should be ouside the loop and then repeat it before closing it. As it is if the first read returns null your data will contain literaly a "null" – Juan Sep 11 '18 at 21:21

1 Answers1

1

Your JSON is a JsonObject not a JsonArray, so you should do this :

JSONObject JO = new JSONObject(data);

And then if you want to get the title do this :

title = JO.getString("Title");

The only JSONArray you have is this one :

"Ratings": [{
        "Source": "Internet Movie Database",
        "Value": "6.6/10"
    }],
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148