Wednesday, February 27, 2013

Android ListViewWithSearch


Android Adding Search Functionality to ListView

Adding search functionality to listview will filters the list data with a matching string, hence provides user an easy way to find the information he needs.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <!-- Editext for Search -->
    <EditText android:id="@+id/inputSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Search products.."
    android:inputType="textVisiblePassword"/>

<!-- List View -->
    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <!-- Single ListItem -->
    
    <!-- Product Name -->
    <TextView android:id="@+id/product_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold"/>    

</LinearLayout>

MainActivity.java 

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Listview Data
        String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
        "iPhone 4S", "Samsung Galaxy Note 800",
        "Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
        
        lv = (ListView) findViewById(R.id.list_view);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        
        // Adding items to listview
        adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
        lv.setAdapter(adapter);
        
        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
    }
    
}






Android Library Project


The Android development tools does not require that everything is included into one project.
Android library projects allow to store source code and resources which are used by several other Android projects. Library projects cannot be compiled to Android applications directly.
Using library projects help us to structure your application code. Also more and more important Open Source libraries are available for Android. Understanding library projects is therefore important for every Android programmer.



Create a new Android project called com.jitesh.rssfeed.library. Do not need to create an activity.

Create a class with the name XmlHandler.java inside the com.jitesh.rssfeed.library and have a following code

package com.jitesh.rssfeed.library;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class XmlHandler extends DefaultHandler {
private RssFeedStructure feedStr = new RssFeedStructure();
private List<RssFeedStructure> rssList = new ArrayList<RssFeedStructure>();

private int articlesAdded = 0;

// Number of articles to download
private static final int ARTICLES_LIMIT = 25;

StringBuffer chars = new StringBuffer();

public void startElement(String uri, String localName, String qName,
Attributes atts) {
chars = new StringBuffer();

if (qName.equalsIgnoreCase("media:thumbnail"))

{
if (!atts.getValue("url").toString().equalsIgnoreCase("null")) {
feedStr.setImgLink(atts.getValue("url").toString());
} else {
feedStr.setImgLink("");
}
}

}

public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("title")) {
feedStr.setTitle(chars.toString());
} else if (localName.equalsIgnoreCase("description")) {

feedStr.setDescription(chars.toString());


} else if (localName.equalsIgnoreCase("pubDate")) {

feedStr.setPubDate(chars.toString());
} else if (localName.equalsIgnoreCase("encoded")) {

feedStr.setEncodedContent(chars.toString());
} else if (qName.equalsIgnoreCase("media:content"))

{

} else if (localName.equalsIgnoreCase("link")) {

}
if (localName.equalsIgnoreCase("item")) {
rssList.add(feedStr);

feedStr = new RssFeedStructure();
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT) {
throw new SAXException();
}
}
}

public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}

public List<RssFeedStructure> getLatestArticles(String feedUrl) {
URL url = null;
try {

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
} catch (SAXException e) {

} catch (ParserConfigurationException e) {

}

return rssList;
}

}


now Create a class with the name RssFeedStructure .java inside the com.jitesh.rssfeed.library and have a following code

package com.jitesh.rssfeed.library;

import java.net.URL;


public class RssFeedStructure {

private long articleId;
private long feedId;
private String title;
private String description;
private String imgLink;
private String pubDate;
private URL url;
private String encodedContent;

public long getArticleId() {
return articleId;
}

public void setArticleId(long articleId) {
this.articleId = articleId;
}

public long getFeedId() {
return feedId;
}
/**
* @param feedId the feedId to set
*/
public void setFeedId(long feedId) {
this.feedId = feedId;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the url
*/
public URL getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(URL url) {
this.url = url;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;


if (description.contains("<img ")){
String img = description.substring(description.indexOf("<img "));
String cleanUp = img.substring(0, img.indexOf(">")+1);
img = img.substring(img.indexOf("src=") + 5);
int indexOf = img.indexOf("'");
if (indexOf==-1){
indexOf = img.indexOf("\"");
}
img = img.substring(0, indexOf);

//setImgLink(img);

this.description = this.description.replace(cleanUp, "");
}
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param pubDate the pubDate to set
*/
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
/**
* @return the pubDate
*/
public String getPubDate() {
return pubDate;
}
/**
* @param encodedContent the encodedContent to set
*/
public void setEncodedContent(String encodedContent) {
this.encodedContent = encodedContent;
}
/**
* @return the encodedContent
*/
public String getEncodedContent() {
return encodedContent;
}
/**
* @param imgLink the imgLink to set
*/
public void setImgLink(String imgLink) {
this.imgLink = imgLink;
}
/**
* @return the imgLink
*/
public String getImgLink() {
return imgLink;
}

}


find the library code to parse the rss feeds at LibraryForRSSreader

use the following library as follows 

String feed = "http://www.ddinews.gov.in/rssCMS/";

XmlHandler rh = new XmlHandler();

List<RssFeedStructure> rssStr=null;

rssStr = rh.getLatestArticles(feed);



Use library project

In your application project defines that you want to use the library project via the project properties.

go to

your's project-->properties-->android-->add--(choose library)-->ok




Tuesday, February 26, 2013

Android HTML Viewer


This example shows how you can show HTML files into your application.
1.) Create a new project by File-> New -> Android Project name it suitably.
2.) Put a .html file into your assets folder, name it “example.htm” and write following code into it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
    <title>HTML viewer</title>
    <style type="text/css">
        body
        {
            padding: 0px;
            font-size: 11pt;
            color: white;
            font-family: Arial;
            background-color: #0000FF;
        }
         
        .style1
        {
            color: #FFFFFF;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="Help" id="Help" style="Z-INDEX: 1000; LEFT: 5%; OVERFLOW: visible; WIDTH: 90%; POSITION: absolute; TOP: 20px; HEIGHT: 500px">
        <h3>HTMLViewerExample: </h3>
        <p>
            You can place your information in this HTML document.
        </p>
    </div>
</body>
</html>



The code for the mainactivity class




import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
 
public class HTMLViewerExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView wb = new WebView(this);
        wb.loadUrl("file:///android_asset/example.htm");
        setContentView(wb);
    }
}

the output is as shown below