我是 Android Studio 的新手,我想使用来自 omdb.com 的 API 获取一些数据,这是我的操作方法:
我创建了一个类:
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);
}
}
我想Title从以下 JSON 中获取值:
{
"Title": "The Generation Game",
"Year": "1971–2001",
}
这是我的 mainActivity 代码:
public void btnFetchData_CLick(View v){
fetchData process = new fetchData();
process.execute();
}
当我点击按钮时,没有任何反应!
为什么我无法访问任何值?
犯罪嫌疑人X
相关分类