1
我試圖下載JSON數據使用豆形軟糖API的Android應用程序17的Android傑利貝恩失敗JSON下載上HttpURLConnection的
我已經添加了清單文件還內互聯網的使用許可。
這是活動中獲取JSON數據的代碼:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//final Button btnLoad = (Button) findViewById(R.id.btnLoad);
tvResult = (TextView) findViewById(R.id.txtView);
//
}
public void onClick(View v) {
final LoadData data = new LoadData();
Log.d("TAG","Button Pressed!");
data.execute();
tvResult.setText(data.get());
}
public static String getJSON(String url) throws IOException {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
try {
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.connect();
//int status = c.getResponseCode();
BufferedReader br = new BufferedReader(new InputStreamReader(
c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line ="";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}finally{
c.disconnect();
}
}
// Inner class for making an asyncTask
public class LoadData extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
final TMDb tmdb = new TMDb();
String data = "";
try {
data = getJSON("http://api.themoviedb.org/3/genre/list?api_key=#");
tvResult.setText(data);
Log.d("TAG-DATA", data);
Log.d("TAG", "RUN STARTED!");
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
e.printStackTrace();
}
return data;
}
}
這工作得很好了常規Java應用程序。但是在android應用程序中往往會殺死該活動。它生產了以下錯誤:
D/TAG(13771): Button Pressed!
W/dalvikvm(13771): threadid=11: thread exiting with uncaught exception (group=0x40bce930)
E/AndroidRuntime(13771): FATAL EXCEPTION: Thread-6603
E/AndroidRuntime(13771): java.lang.NullPointerException: println needs a message
E/AndroidRuntime(13771): at android.util.Log.println_native(Native Method)
E/AndroidRuntime(13771): at android.util.Log.d(Log.java:138)
E/AndroidRuntime(13771): at com.mjavacam.tmdb.MainActivity$1.run(MainActivity.java:88)
E/AndroidRuntime(13771): at java.lang.Thread.run(Thread.java:856)
任何人都可以協助通過展示我在下面:
如何正確地使從Android應用程序中的http請求?
確定我可能做錯了什麼?
非常感謝你,它的作品很棒! – 2013-03-05 18:30:32