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 trialTimmy Yong
Courses Plus Student 2,254 PointsPlease help! It keeps saying your blog reader has stopped
I have watched the videos again and again thinking that I have made a mistake, but still occurring.! I dont know what to do ?
Daniel Hartin
18,106 PointsHi Timmy
It is impossible to identify the problem without some more input from you unfortunately. Can you please post your Logcat entries here so we can see where the code cause an error and fails. Hopefully then we can direct you by looking at some source code of yours which would also need to be posted here.
Thanks Daniel
Timmy Yong
Courses Plus Student 2,254 Points <p>package mydsigncommunityblog.blogreader;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
//import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainListActivity extends ListActivity {
protected String[] mBlogPostTitles;
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar2);
if(isNetworkAvailable()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
else
{
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
// TextView emptyTextView = (TextView) getListView().getEmptyView();
// emptyTextView.setText(getString(R.string.no_items));
}
// String message = getString(R.string.no_items);
//Toast.makeText(this,message,Toast.LENGTH_LONG).show()
}
private boolean isNetworkAvailable() {
ConnectivityManager manger = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manger.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected())
{
isAvailable = true;
}
else
{
try {
Log.d(TAG, mBlogData.toString(2));
} catch (JSONException e) {
Log.e(TAG, "Exception caught", e);
}
}
return isAvailable;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_list, menu);
return true;
}
private void handleBlogResponse()
{
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData == null)
{
updateDisplayForError();
}
else
{
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for(int i=0; i < jsonPosts.length(); i++)
{
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
mBlogPostTitles);
setListAdapter(adapter);
} catch (JSONException e)
{
Log.e(TAG, "Exception caught!", 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... arg0) {
int responseCode =-1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char [] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONObject(responseData);
}
else
{
Log.i(TAG, "Unsuccessful code response! " + responseCode);
}
}
catch (MalformedURLException e)
{
Log.e(TAG, "Exception caught", e);
} catch (IOException e)
{
Log.e(TAG, "Exception caught", e);
} catch (Exception e)
{
Log.e(TAG, "Exception caught", e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
mBlogData = result;
handleBlogResponse();
}
}
}</p>
```
Timmy Yong
Courses Plus Student 2,254 PointsDaniel Hartin Thank you for the quick response and sorry for the late reply
I have put the code and the log if you could help me Rally appreciate it
Timmy Yong
Courses Plus Student 2,254 Points <p>10-10 12:26:01.571 1232-1232/mydsigncommunityblog.blogreader D/AndroidRuntime﹕ Shutting down VM
10-10 12:26:01.571 1232-1232/mydsigncommunityblog.blogreader W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4c3c648)
10-10 12:26:01.575 1232-1232/mydsigncommunityblog.blogreader E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{mydsigncommunityblog.blogreader/mydsigncommunityblog.blogreader.MainListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at mydsigncommunityblog.blogreader.MainListActivity.onCreate(MainListActivity.java:46)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
</p>
```
Timmy Yong
Courses Plus Student 2,254 PointsThank you for your response. I tried doing clean project and same thing still occurring .
Timmy Yong
Courses Plus Student 2,254 PointsDaniel Hartin Thanks a lot Sorry for late reply I had midterm exams.
3 Answers
Daniel Hartin
18,106 PointsHi Timmy
Sorry I haven't got back sooner, I've been busy over the weekend.
It looks to me as if in your onCreate() method you haven't called the method setcontentView() (You may have accidentally deleted this). Without this call to setContentView your code is breaking when it tries to assign the mProgressBar variable as there is no XML for it to look at so it results in a nullPointerException.
Add the line in as the code below shows simply replacing the xml layout name for your own layout.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_xml_layout_filename_here);
Hope this helps
Daniel
Timmy Yong
Courses Plus Student 2,254 PointsThanks a lot . It really helps and works directly after i did that. But i still get an empty list i mean i dont get the data from the JSON as it used to do before. It might be my mistake because I honestly dont know what is the xml layout name i should choose. I selected main_activity _list Sorry for such a question
P.S. I also dont know why the progress bar keeps loading for ever, I tried to look over the code again and i couldnt figure it out. it's ok for this ...More importantly i need to understand the things i got above
Thanks million
here is my xml file
<p><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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainListActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="@string/no_items"
android:id="@android:id/empty" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar2"
android:layout_centerInParent="true" />
</RelativeLayout>
</p>
```
Daniel Hartin
18,106 PointsHi Timmy
It looks as if your XML file is okay. If it is not showing an error now then the problem is not with your code as such.
I have posted the URL address into a browser and get the response JSON data back so that is correct.
When you say the progressBar loads forever, do you mean it loads forever (never ends) or does it just take a long time?.
Are you testing this on an emulator or on an actual device?
Thanks Daniel
Timmy Yong
Courses Plus Student 2,254 PointsIt loads forever never ends
even when I try to delete the progress bar just to see if the information will load or not i got that message i have typed which says 'Empty' and please for setContentView(R.layout.your_xml_layout_filename_here); I dont know with what I should replace it
thanks again
Daniel Hartin
18,106 PointsHi Timmy
The line below needs changing to the name of the XML file you pasted above. In the project explorer inside Eclipse open up your app, then go into the res folder, then open up layout folder, all your layouts should be in here! where you click on the file to open it the name will be displayed simply replace the name with the name of your file. I have changed the name in the lines below so you can see which code needs changing.
Sorry I can't help you anymore than that without physically seeing your screen.
setContentView(R.layout.your_xml_layout_filename_here);
//You only need to change the last part
//The line below changes the XML file name
//You will need to find your own using the path explained above
setContentView(R.layout.main_layout);
As for the ASyncTask i'm not sure your code looks okay to me. Have you tried looking in the log? You have various calls to the log setup for an incorrect response from the URL address. I would run the app. It must be breaking before the call to handleBlogResponse() as the mProgressBar is not being set to Invisible, so the ASynctask class has the problem. All the lines below are calls to the log I assume the code is catching an exception but because there is only a call to your log file nothing happens. Look in your log file and paste here what happens (note it may be worth changing the strings to the values below just to see a bit easier).
else
{
Log.i(TAG, "Unsuccessful code response! " + responseCode);
}
}
catch (MalformedURLException e)
{
Log.e(TAG, "MALFORMED Exception caught", e);
} catch (IOException e)
{
Log.e(TAG, "IO Exception caught", e);
} catch (Exception e)
{
Log.e(TAG, "ANOTHER Exception caught", e);
Leroy Sibisi
20,619 PointsI'm having a problem answering this challenge.
The challenge is, Create a new variable jsonObject and then use the native JSON object to parse the jsonString and assign it to jsonObject.
Here is the code provided; var jsonString = '{"name": "Andrew", "languages": ["javascript", "swift", "java", "ruby", "html", "css", "qbasic"]}';
My answer was; var jsonObject = JSON.parse("jsonString");
But I get an error.
Daniel Hartin
18,106 PointsHi Leroy
You really need to ask this in another new question to get the best response as this question is over a year old and has been answered already.
I can try and help in a new question.
Thanks Daniel
Gonzalo Calderon
21,653 Pointsvar jsonObject = JSON.parse(jsonString);
That is the answer that works.............................
ogechi1
14,455 Pointsogechi1
14,455 PointsTry doing a clean build (Project > Clean).