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

Android

why don't i get any data?

in the blog reader app i am constantly getting the no data message even though my device's wifi is on and connected?

my code for main list activity. java is:

package james.blogreader;

import android.app.AlertDialog;
import android.app.ListActivity;
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.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
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;
import java.util.ArrayList;
import java.util.HashMap;


public class MainListActivity extends ListActivity {


    public static final int NUMBER_OF_POSTS = 20;
    protected NetworkInfo networkInfo;
    public static final String TAG = MainListActivity.class.getSimpleName();
    protected JSONObject mBlogData;
    protected ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_list);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (isNetworkAvailable()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.no_net_title));
            builder.setMessage(getString(R.string.no_net_message));
            builder.setPositiveButton(R.string.no_net_button,null);
            AlertDialog dialog = builder.create();
            dialog.show();
            Toast.makeText(this,"No network detected.",Toast.LENGTH_LONG).show();
        } else {
            mProgressBar.setVisibility(View.VISIBLE);
            GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
            getBlogPostsTask.execute();
        }

    }

    @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, BlogReaderWebView.class);
            intent.setData(Uri.parse(blogUrl));
            startActivity(intent);
        }
        catch (JSONException e) {
            logException(e);
        }

    }

    private void logException(Exception e) {
        Log.e(TAG, "Exception caught", e);
    }

    public boolean isNetworkAvailable()
    {


            ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            networkInfo = manager.getActiveNetworkInfo();
            return false;


    }




    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>>();
                String KEY_TITLE = "title";
                String KEY_AUTHOR = "author";
                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 author = post.getString(KEY_AUTHOR);
                    author = Html.fromHtml(author).toString();

                    HashMap<String, String> blogPost = new HashMap<String, String>();
                    blogPost.put(KEY_TITLE, title);
                    blogPost.put(KEY_AUTHOR, author);

                    blogPosts.add(blogPost);

                }

                String[] keys = {KEY_TITLE, KEY_AUTHOR};
                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.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;
            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 HTTP Responce Code : " + responseCode);
                }

            }
            catch (MalformedURLException e) {
                logException(e);
            }
            catch (IOException e) {
                logException(e);
            }
            catch(Exception e){
                logException(e);
            }
            return  jsonResponse;
        }
        @Override
        protected void onPostExecute(JSONObject result){
            mBlogData = result;
            handleBlogResponse();
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return id == R.id.action_share || super.onOptionsItemSelected(item);
    }
}

my code for android manifest. xml is:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="james.blogreader" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainListActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".BlogReaderWebView"
            android:label="@string/title_activity_blog_reader_web_view" >
        </activity>
    </application>

</manifest>

my code for strings. xml is:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Blog Reader</string>
    <string name="action_settings">Settings</string>
    <string name="no_items">No items to display</string>
    <string name="title">Error</string>
    <string name="no_net_title">Cannot connect to the Internet</string>
    <string name="no_net_message">Cannot connect to the Internet, please check your internet settings.</string>
    <string name="no_net_button">OK,i will do that!</string>
    <string name="error_message">Unable to get data</string>
    <string name="action_share">Share</string>
    <string name="share_chooser_title">How do you want to share?</string>

    <string name="title_activity_blog_reader_web_view">Blog Post</string>

</resources>

my code for blog reader web view. java is:

package james.blogreader;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;


public class BlogReaderWebView extends ActionBarActivity {

    protected String mUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog_reader_web_view);

        Intent intent = getIntent();
        Uri blogUri = intent.getData();
        mUrl = blogUri.toString();

        WebView webView = (WebView)  findViewById(R.id.webView);
        webView.loadUrl(mUrl);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.blog_reader_web_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_share){
            sharePost();
        }
        return super.onOptionsItemSelected(item);
    }

    private void sharePost() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT,mUrl);
        startActivity(Intent.createChooser(shareIntent, getString(R.string.share_chooser_title)));
    }

}

my code for activity main list. xml is:

<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"
    tools:context=".MainListActivity">


    <ExpandableListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@android:id/list"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView android:id= "@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="32sp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerInParent="true" />
</RelativeLayout>

my code for activity blog reader web view. xml is:

<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"
    tools:context="james.blogreader.BlogReaderWebView">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

my code for blog reader web view. xml is:

<menu xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    tools:context="james.blogreader.BlogReaderWebView" >
    <item
        android:id="@+id/action_share"
        android:icon="@drawable/ic_action_share_dark"
        android:title="@string/action_share"
        android:showAsAction="always"
        />
</menu>

and finally, my code for v11\blog reader web view. xml is:

<menu xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    tools:context="james.blogreader.BlogReaderWebView" >
    <item
        android:id="@+id/action_share"
        android:icon="@drawable/ic_action_share"
        android:title="@string/action_share"
        android:showAsAction="always"
        />
</menu>

please help me!!!!! i will be very greatful!!!!

1 Answer

Hey James !!

So for problems like this its time to put on your bug hunting hat (if you have an actual hat that looks like a bug that may be a little far just saying). This is what is referred to as a logic error which means although our code compiles its not giving us what we originally wanted :(. I would start by stepping through your program and seeing where your data is getting lost, for example when the JSON object is returned is it empty?. If it is then you need to check the way your posting it to the server to make sure you will get what you want back. Lastly if your post looks good then the only other thing that would cause your lost data is that there is none on the server, can't get what is not there right. Anyway I hope you found this somewhat entertaining and helpful =D

Your Friendly mod

Doug