harryjamesuk

MainListActivity.java

Jul 22nd, 2014
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.15 KB | None | 0 0
  1. package com.harryjamesuk.blogreader;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.Reader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12.  
  13. import org.json.JSONArray;
  14. import org.json.JSONException;
  15. import org.json.JSONObject;
  16.  
  17. import android.app.AlertDialog;
  18. import android.app.ListActivity;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.net.ConnectivityManager;
  22. import android.net.NetworkInfo;
  23. import android.net.Uri;
  24. import android.os.AsyncTask;
  25. import android.os.Bundle;
  26. import android.text.Html;
  27. import android.util.Log;
  28. import android.view.View;
  29. import android.widget.ListView;
  30. import android.widget.ProgressBar;
  31. import android.widget.SimpleAdapter;
  32. import android.widget.TextView;
  33. import android.widget.Toast;
  34.  
  35. public class MainListActivity extends ListActivity {
  36.    
  37.     public static final int NUMBER_OF_POSTS = 20;
  38.     public static final String TAG = MainListActivity.class.getSimpleName();
  39.     protected JSONObject mBlogData;
  40.     protected ProgressBar mProgressBar;
  41.    
  42.     private final String KEY_TITLE = "title";
  43.     private final String KEY_AUTHOR = "author";
  44.  
  45.     @Override
  46.     protected void onCreate(Bundle savedInstanceState) {
  47.         super.onCreate(savedInstanceState);
  48.         setContentView(R.layout.activity_main_list);
  49.        
  50.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
  51.        
  52.         if(isNetworkAvailable()) {
  53.             mProgressBar.setVisibility(View.VISIBLE);
  54.             GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
  55.             getBlogPostsTask.execute();
  56.         }
  57.        
  58.         // Toast.makeText(this, getString(R.string.no_items), Toast.LENGTH_LONG).show();
  59.     }
  60.  
  61.     @Override
  62.     protected void onListItemClick(ListView l, View v, int position, long id) {
  63.         super.onListItemClick(l, v, position, id);
  64.        
  65.         try {
  66.             JSONArray jsonPosts = mBlogData.getJSONArray("posts");
  67.             JSONObject jsonPost = jsonPosts.getJSONObject(position);
  68.             String blogUrl = jsonPost.getString("url");
  69.             Intent intent = new Intent(this, BlogWebViewActivity.class);
  70.             intent.setData(Uri.parse(blogUrl));
  71.             startActivity(intent);
  72.         } catch (JSONException e) {
  73.             logException(e);
  74.         }
  75.     }
  76.  
  77.     private void logException(Exception e) {
  78.         Log.e(TAG, "Exception caught!", e);
  79.     }
  80.    
  81.     private boolean isNetworkAvailable() {
  82.         ConnectivityManager manager = (ConnectivityManager)
  83.                  getSystemService(Context.CONNECTIVITY_SERVICE);
  84.         NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  85.        
  86.         boolean isAvailable = false;
  87.         if (networkInfo != null && networkInfo.isConnected()) {
  88.             isAvailable = true;
  89.         }
  90.         else {
  91.             updateDisplayForError();
  92.         }
  93.        
  94.         return isAvailable;
  95.     }
  96.  
  97.     public void handleBlogResponse() {
  98.         mProgressBar.setVisibility(View.INVISIBLE);
  99.         if (mBlogData == null) {
  100.             updateDisplayForError();
  101.         }
  102.         else {
  103.             try {
  104.                
  105.                 JSONArray jsonPosts = mBlogData.getJSONArray("posts");
  106.                 ArrayList<HashMap<String, String>> blogPosts = new
  107.                         ArrayList<HashMap<String, String>>();
  108.                
  109.                 for (int i = 0; i < jsonPosts.length(); i++) {
  110.                     JSONObject post = jsonPosts.getJSONObject(i);
  111.                    
  112.                     String title = post.getString(KEY_TITLE);
  113.                     title = Html.fromHtml(title).toString();
  114.                    
  115.                     String author = post.getString(KEY_AUTHOR);
  116.                     author = Html.fromHtml(author).toString();
  117.                    
  118.                     HashMap<String, String> blogPost = new HashMap<String, String>();
  119.                     blogPost.put(KEY_TITLE, title);
  120.                     blogPost.put(KEY_AUTHOR, author);
  121.                    
  122.                     blogPosts.add(blogPost);
  123.                 }
  124.                 String[] keys = { KEY_TITLE, KEY_AUTHOR };
  125.                 int[] ids = { android.R.id.text1, android.R.id.text2 };
  126.                 SimpleAdapter adapter = new SimpleAdapter(this, blogPosts,
  127.                         android.R.layout.simple_list_item_2, keys, ids);
  128.                 setListAdapter(adapter);
  129.             } catch (JSONException e) {
  130.                 logException(e);
  131.             }
  132.         }
  133.     }
  134.  
  135.     private void updateDisplayForError() {
  136.         mProgressBar.setVisibility(View.INVISIBLE);
  137.         Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
  138.        
  139.         AlertDialog.Builder builder = new AlertDialog.Builder(this);
  140.         builder.setTitle(getString(R.string.error_title));
  141.         builder.setMessage(getString(R.string.error_message));
  142.         builder.setPositiveButton(android.R.string.ok, null);
  143.         AlertDialog dialog = builder.create();
  144.         dialog.show();
  145.        
  146.         TextView emptyTextView = (TextView) getListView().getEmptyView();
  147.         emptyTextView.setText(getString(R.string.no_items));
  148.     }
  149.    
  150.     private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject> {
  151.  
  152.         @Override
  153.         protected JSONObject doInBackground(Object... arg0) {
  154.             int responseCode = -1;
  155.             JSONObject jsonResponse = null;
  156.             mBlogData = null;
  157.            
  158.             try {
  159.                 URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
  160.                 HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
  161.                 connection.connect();
  162.                
  163.                 responseCode = connection.getResponseCode();
  164.                 if (responseCode == HttpURLConnection.HTTP_OK) {
  165.                     InputStream inputStream = connection.getInputStream();
  166.                     Reader reader = new InputStreamReader(inputStream);
  167.                     int nextCharacter; // read() returns an int, we cast it to char later
  168.                     String responseData = "";
  169.                     while(true){ // Infinite loop, can only be stopped by a "break" statement
  170.                         nextCharacter = reader.read(); // read() without parameters returns one character
  171.                         if(nextCharacter == -1) // A return value of -1 means that we reached the end
  172.                             break;
  173.                         responseData += (char) nextCharacter; // The += operator appends the character to the end of the string
  174.                     }
  175.  
  176.                     jsonResponse = new JSONObject(responseData);
  177.                 }
  178.                 else {
  179.                     Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
  180.                 }
  181.             }
  182.             catch (MalformedURLException e) {
  183.                 logException(e);
  184.             }
  185.             catch (IOException e) {
  186.                 logException(e);       
  187.             }
  188.             catch (Exception e) {
  189.                 logException(e);   
  190.             }
  191.             return jsonResponse;
  192.         }
  193.         @Override
  194.         protected void onPostExecute(JSONObject result) {
  195.             mBlogData = result;
  196.             handleBlogResponse();
  197.         }
  198.     }
  199. }
Advertisement
Add Comment
Please, Sign In to add comment