Advertisement
Guest User

Untitled

a guest
May 8th, 2016
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package com.example.rikirikmen.newsapps;
  2.  
  3. import android.app.Activity;
  4. import android.os.AsyncTask;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. import android.view.MenuItem;
  9.  
  10. import org.json.JSONArray;
  11. import org.json.JSONObject;
  12.  
  13. import java.io.InputStream;
  14. import java.io.InputStreamReader;
  15. import java.net.HttpURLConnection;
  16. import java.net.URL;
  17. import java.util.concurrent.ExecutionException;
  18.  
  19. public class MainActivity extends Activity {
  20.  
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25.  
  26. DownloadTask task = new DownloadTask();
  27. try {
  28. String result = task.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
  29. Log.i("Result", result);
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. } catch (ExecutionException e) {
  33. e.printStackTrace();
  34. }
  35.  
  36.  
  37. }
  38.  
  39. public class DownloadTask extends AsyncTask<String, Void, String> {
  40.  
  41.  
  42. @Override
  43. protected String doInBackground(String... urls) {
  44.  
  45. String result = "";
  46. URL url;
  47. HttpURLConnection urlConnection = null;
  48.  
  49. try {
  50.  
  51. url = new URL(urls[0]);
  52.  
  53. urlConnection = (HttpURLConnection) url.openConnection();
  54.  
  55. InputStream in = urlConnection.getInputStream();
  56.  
  57. InputStreamReader reader = new InputStreamReader(in);
  58.  
  59. int data = reader.read();
  60.  
  61. while (data!= -1){
  62.  
  63. char current = (char) data;
  64.  
  65. result += current;
  66.  
  67. data = reader.read();
  68.  
  69. }
  70.  
  71. }catch (Exception e){
  72. e.printStackTrace();
  73.  
  74. }
  75.  
  76. return null;
  77. }
  78. }
  79.  
  80.  
  81. @Override
  82. public boolean onOptionsItemSelected(MenuItem item) {
  83. return super.onOptionsItemSelected(item);
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement