Android ListView → Android RSS – ListView – Headlines With Images and Text – Camposha

Android ListView

Android ListView

Android ListView

Android RSS – ListView – Headlines With Images and Text

 

Android RSS Listview images and text example. This is an android RSS images listview example with XmlPullParser,AsyncTask ,HttpURLConnection and ListView..We shall download RSS Feeds from a local website and then parse the feed.We then show parsed images and text news in our ListView.

What we do :

  • Connect to Internet and make a HTTP GET request using HtttpURLConnection.
  • Download our data in the background thread.
  • WE use AsyncTask for our threading.
  • WE parse the downloaded xml feeds.
  • We shall be parsing using XmlPullParser.
  • We show our results in a ListView.
  • Our results shall consist of images and text.
  • The website we shall be parsing was hosted locally and it was a dummy wordpress site.

Enough.Let’s now dive to the deep end.

SECTION 1 : Our Dependencies and Manifest.

Build.Gradle [App Level]

  • Studio has added for us dependencies for AppCompat and Design support libraries.
  • Now lets add dependencies for CardView and Picasso library.
  • Our ListView’s ViewItems shall be cardviews.
  • Picasso shall allow us asynchronously download images and cache them.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.tutorials.hp.listviewrssimagestext"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'
   // compile project(':picasso-2.5.2')
   compile 'com.squareup.picasso:picasso:2.5.2'

}

AndroidManifest.xml

  • Remember we are downloading data from a network.
  • Hence we need to add permission to access the internet.
  • Or else Android won’t accept our request for connection.
<?xml version="1.0" encoding="utf-8"?>
<manifest 
    package="com.tutorials.hp.listviewrssimagestext">

    <uses-permission android_name="android.permission.INTERNET"/>

    <application
        android_allowBackup="true"
        android_icon="@mipmap/ic_launcher"
        android_label="@string/app_name"
        android_supportsRtl="true"
        android_theme="@style/AppTheme">
        <activity
            android_name=".MainActivity"
            android_label="@string/app_name"
            android_theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android_name="android.intent.action.MAIN" />

                <category android_name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

SECTION 2 : Our Data Object

Article.java

  • Represents a single article.
  • The article shall have various properties like name,title,date etc.
package com.tutorials.hp.listviewrssimagestext.m_DataObject;

public class Article {

    String title,description,date,imageUrl;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }
}

SECTION 3 : Our Networking and Parsing classes

Connector class

Main Responsibility : ESTABLISH CONNECTION.

  • Establishes connection to our server for us.
  • We then set up connection properties like Request method.
  • In this case we are making a HTTP GET request to our server.
  • We shall use HttpURLConnection so our only method shall return its instance .
package com.tutorials.hp.listviewrssimagestext.m_RSS;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Connector {

    public static Object connect(String urlAddress)
    {
        try
        {
            URL url=new URL(urlAddress);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            //PROPERTIES
            con.setRequestMethod("GET");
            con.setConnectTimeout(15000);
            con.setReadTimeout(15000);
            con.setDoInput(true);

            return con;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return ErrorTracker.WRONG_URL_FORMAT;

        } catch (IOException e) {
            e.printStackTrace();
            return ErrorTracker.CONNECTION_ERROR;
        }
    }

}

Downloader class

Main Responsibility : DOWNLOAD XML FEEDS.

  • We use our Connector class above to establish a connection.
  • If we have a connection then we download data XML feeds from server.
  • We download in background using AsyncTask to avoid freezing our user interface.
  • Meanwhile we show progress dialog while downloading.
  • We dismiss our progress dialog on completion.
  • Then we send this downloaded xml feeds to our Data Parser class for it to be processed.
package com.tutorials.hp.listviewrssimagestext.m_RSS;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

public class Downloader extends AsyncTask<Void,Void,Object> {

    Context c;
    String urlAddress;
    ListView lv;

    ProgressDialog pd;

    public Downloader(Context c, String urlAddress, ListView lv) {
        this.c = c;
        this.urlAddress = urlAddress;
        this.lv = lv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(c);
        pd.setTitle("Fetch Articles");
        pd.setMessage("Fetching...Please wait");
        pd.show();
    }

    @Override
    protected Object doInBackground(Void... params) {
        return this.downloadData();
    }

    @Override
    protected void onPostExecute(Object data) {
        super.onPostExecute(data);
        pd.dismiss();
        if(data.toString().startsWith("Error"))
        {
            Toast.makeText(c,data.toString(),Toast.LENGTH_SHORT).show();
        }else {
            //PARSE RSS
            new RSSParser(c, (InputStream) data,lv).execute();
        }

    }

    private Object downloadData()
    {
        Object connection=Connector.connect(urlAddress);
        if(connection.toString().startsWith("Error"))
        {
            return connection.toString();
        }

        try
        {
            HttpURLConnection con= (HttpURLConnection) connection;
            int responseCode=con.getResponseCode();
            if(responseCode==con.HTTP_OK)
            {
                InputStream is=new BufferedInputStream(con.getInputStream());
                return is;
            }

            return ErrorTracker.RESPONSE_EROR+con.getResponseMessage();

        } catch (IOException e) {
            e.printStackTrace();
            return ErrorTracker.IO_EROR;
        }
    }
}

RSS Parser class

Main Responsibility : DOWNLOAD XML FEEDS.

  • It receives raw XML feeds from downloader class.
  • It then processes/parses these feeds.
  • We use XmlPullParser to parse the feeds.
  • It then fills an arraylist of Article Objects with our results.
  • It then sends this arraylist to adapter for binding purposes.

Error Tracker class

Main Responsibility : HELP US TRACK CONNECTION EXCEPTIONS AT RUNTIME

  •  Consists of constants that we shall display when we encounter error at runtime.

SECTION 3 : Adapter class

Custom Adapter class

Main Responsibility : HELPS US BIND CUSTOM DATA TO LISTVIEW.

  • You can use one line of code to bind simple data to listview.
  • But for custom data like ours,we need an adapter to adapt it.
  • We shall use BaseAdapter as our Base class.
  • Our BaseAdapter subclass shall receive an arraylist and a context.

Picasso Client class.

Main Responsibility : DOWNLOAD OUR IMAGES AND CACHE THEM.

  • Picasso library shall help us download images when supplied with a URL.

SECTION 4 : Our Activity

MainActivity class.

Main Responsibility : LAUNCH OUR APP.

  • We shall reference the views like ListView and Floating action button here,from our XML Layouts.
  • We then execute our Downloader class when Floating action button is clicked.
  • We shall also define here our feeds url and parse the data.

SECTION 5 : Our Layouts

ActivityMain.xml Layout.

  • Inflated as our activity’s view.
  • Includes our content main.

ContentMain.xml Layout.

  • Defines our view hierarchy.

Model.xml Layout.

  • Inflated as our AdapterView’s viewitems.

LAST SECTION

  • Lets share more tips in OUR FB PAGE.
  • To see the XML  we were parsing and the website itself please have look at the tutorial at our youtbe channel : ProgramminWizards.
  • You’ll also find the demo for this example and step by step explanations.

Cheers.

Leave a Reply

Your email address will not be published. Required fields are marked *

Join Us
X