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?