Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Neil Quinn
768 PointsReturning thumbnail image in imageview using JSON for a list
Hi I'm having a problem with loading thumbnail images from this JSON url:
http://www.ilovelimerick.ie/?json=1&count=10
I can't seem to pinpoint the problem because it seems to work for posts, date & title. So why not for thumbnail?
public class NewsFragment extends ListFragment{
public static final int NUMBER_OF_POSTS = 10;
public static final String TAG = NewsFragment.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private final String KEY_TITLE = "title";
private final String KEY_DATE = "date";
private final String KEY_THUMBNAIL = "thumbnail";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_list,
container, false);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1);
if(NetworkIsAvailable()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
else {
Toast.makeText(getActivity(), "Network is unavailable!", Toast.LENGTH_LONG).show();
}
//String message = getString(R.string.no_items);
//Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return rootView;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
JSONObject jsonPost = jsonPosts.getJSONObject(position);
String blogUrl = jsonPost.getString("url");
Intent intent = new Intent(getActivity(),BlogWebViewActivity.class);
intent.setData(Uri.parse(blogUrl));
startActivity(intent);
}
catch (JSONException e) {
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG, "Exception caught!", e);
}
private boolean NetworkIsAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData == null) {
updateDisplayForError();
}
else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String date = post.getString(KEY_DATE);
date = Html.fromHtml(date).toString();
String thumbnail = post.getString(KEY_THUMBNAIL);
thumbnail = Html.fromHtml(thumbnail).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_DATE, date);
blogPost.put(KEY_THUMBNAIL, thumbnail);
blogPosts.add(blogPost);
}
String[] keys = { KEY_TITLE, KEY_DATE, KEY_THUMBNAIL };
int[] ids = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(getActivity(), blogPosts, android.R.layout.simple_list_item_2, keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
logException(e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Object... params) {
int responseCode = -1;
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.ilovelimerick.ie/?json=1&count=10");
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
}
else {
Log.i(TAG, String.format("Unsuccessful HTTP response code: %d", responseCode));
}
}
catch (JSONException e) {
logException(e);
}
catch (Exception e) {
logException(e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
mBlogData = result;
handleBlogResponse();
}
}
}
and also from my .xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity$DummySectionFragment" >
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ListView
android:id="@android:id/list"
android:layout_width="235dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignTop="@android:id/empty" >
</ListView>
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="@android:id/empty"
android:layout_toLeftOf="@android:id/list"/>
</RelativeLayout>
2 Answers
Neil Quinn
768 Pointshttps://github.com/neilquinn91/MyApp there you go...Thanks for the suggestion!
Neil Quinn
768 Pointscool I'll do it now and post the link!
Ernest Grzybowski
Treehouse Project ReviewerErnest Grzybowski
Treehouse Project ReviewerJust as a suggestion. Try uploading your project to github so that others users (like me) can fork off of your branch, and debug ourselves. It makes it a lot easier than trying to set up a test project for every time users have an error.