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 PointsIntegrating BlogReader App into Tab's using Fragments
Hi, So I've started making an app and a portion of it gets news from my blog. I am using fragments for tabs. So I've followed the "self destructing photo app" until the end of the fragments and tab stage. I have a fragment called "NewsFragment" which basically contains the main activity of the blogreader app. I've also copied over all the various xml files and other .java classes that the blogreader app had and they have no errors and seem to be fine. I'm really stuck on resolving these errors in NewsFragment.java:
Cannot reduce the visibility of the inherited method from ListFragment line 86
Cannot reduce the visibility of the inherited method from Fragment line 65
The constructor Intent(NewsFragment, Class<BlogWebViewActivity>) is undefined line 93
activity_main_list cannot be resolved or is not a field line 67
The method findViewById(int) is undefined for the type NewsFragment line 69
The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (NewsFragment, String, int) line 77
The type com.teamtreehouse.ribbit.NewsFragment.GetBlogPostsTask is not visible line 22
The constructor AlertDialog.Builder(NewsFragment) is undefined line 153
The method getSystemService(String) is undefined for the type NewsFragment line 108
The constructor SimpleAdapter(NewsFragment, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined line 142
Here is my code for NewsFragment:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashMap;
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
import com.teamtreehouse.ribbit.BlogWebViewActivity; import com.teamtreehouse.ribbit.R; import com.teamtreehouse.ribbit.NewsFragment.GetBlogPostsTask; import com.teamtreehouse.ribbit.NewsFragment;
import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast;
public class NewsFragment extends ListFragment{
public static final int NUMBER_OF_POSTS = 20;
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";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
return rootView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
if(NetworkIsAvailable()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
else {
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
//String message = getString(R.string.no_items);
//Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
@Override
protected 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(this,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)
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();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_DATE, date);
blogPosts.add(blogPost);
}
String[] keys = { KEY_TITLE, KEY_DATE };
int[] ids = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, 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(this);
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=");
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();
}
}
}
I know this quite long, but I hope I have provided enough info on what I'm trying to do. Any help would be appreciated!
2 Answers
Ben Jakuben
Treehouse TeacherHi Neil, I'm assuming you got past this based on your other posts. Is that correct?
Neil Quinn
768 Pointsyes :) thanks for everything! major help