0
我正在關注在Android中關於Rest API的this教程。我做了本視頻中的所有內容,但沒有收到任何數據,因爲我已經更改了鏈接,但我沒有收到任何數據。這裏是我的代碼:REST API - 不顯示任何內容
public class MainActivity extends AppCompatActivity {
private TextView value;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.textView);
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
// to bedzie wyswietlone
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parrentArray.getJSONObject(0);
String movieName = finalObject.getString("movie");
int movieYear = finalObject.getInt("year");
return movieName;
}catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
value.setText(result);
}
}
}
我是Android的初學者,請不要說我應該從容易開始。我正在爲我的Django項目做這件事,我想爲它創建移動應用程序。非常感謝您的幫助!
我試圖調試您的應用程序,它似乎只要行'connection.connect();'被執行之後降低到'finally'聲明並最終返回'null'。不知道爲什麼它的行爲如此。 – pleft
嗨,儘管我們不鼓勵我們推薦一些「更容易」的東西,但改造是一條可行的路。 – Traabefi