Thursday, June 23, 2011

XML parsing using SAX with Listview

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/name" />
    <ListView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/list" />
</LinearLayout>

listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/text"/>
</LinearLayout>



XMLParsindSAXParser.java

package com.parsingbySAX;

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

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

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class XMLParsindSAXParser extends Activity {

    SiteList siteList = null;
    static ArrayList<String> h1visa = new ArrayList<String>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView name;
        ListView k;

        name = (TextView) findViewById(R.id.name);
        k = (ListView) findViewById(R.id.list);

        try {

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            URL sourceUrl = new URL(
                    "http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");

            MyXMLHandler myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            // TODO: handle exception

            System.out.println("XML Parsing Exception : " + e);
        }
        siteList = MyXMLHandler.siteList;
        int h = siteList.getName().size();
        for (int i = 0; i < siteList.getName().size(); i++) {

            h1visa.add(siteList.getName().get(i));
            Log.v("log_tag", "new data  " + h1visa);

        }
        k.setAdapter(new EfficientAdapter(this, h1visa));

        k.setTextFilterEnabled(true);

        // setContentView(layout);
    }

    public static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private List<String> data;

        public EfficientAdapter(Context context, List<String> data) {
            mInflater = LayoutInflater.from(context);
            data = this.data;
        }

        public int getCount() {
            return h1visa.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listitem, null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);

                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.text.setText(h1visa.get(position));
            return convertView;
        }

        static class ViewHolder {
            TextView text;

        }
    }

}



SiteList.java

package com.parsingbySAX;

import java.util.ArrayList;

public class SiteList {
   
    private ArrayList<String> name=new ArrayList<String>();
    private ArrayList<String> website=new ArrayList<String>();
    private ArrayList<String> category=new ArrayList<String>();
   
   
    public ArrayList<String> getName(){
        return name;
    }
    public void setName(String name){
        this.name.add(name);
    }
    public ArrayList<String> getWebsite(){
        return website;
    }
    public void setWebsite(String website){
        this.website.add(website);
    }
    public ArrayList<String> getCategory(){
        return category;
    }
    public void setCategory(String category){
        this.category.add(category);
    }

}

MyXMLHandler.java

package com.parsingbySAX;

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

public class MyXMLHandler extends DefaultHandler{
   
    boolean currentElement = false;
    String currentValue = null;

    public static SiteList siteList=null;
   
    public static SiteList getSiteList(){
        return siteList;
    }
   
    public static void setSiteList(SiteList siteList){
       
        MyXMLHandler.siteList=siteList;
    }
   
    public void startElement(String uri,String localName,String qName,Attributes attrubutes) throws SAXException{
        currentElement=true;
       
        if(localName.equals("maintag")){
            siteList=new SiteList();
        }
        else if(localName.equals("website")){
            String attr=attrubutes.getValue("category");
            siteList.setCategory(attr);
        }
    }
   
    public void endElement(String uri,String localName,String qName) throws SAXException{
       
        currentElement=false;
       
        if(localName.equalsIgnoreCase("name")){
            siteList.setName(currentValue);
           
        }
        else if(localName.equalsIgnoreCase("website")){
            siteList.setWebsite(currentValue);
        }
       
    }
    public void characters(char[] ch,int start,int length) throws SAXException{
       
        if(currentElement){
            currentValue=new String(ch, start, length);
            currentElement=false;
        }
    }
}

Wednesday, June 22, 2011

How to integrate facebook in Android


private static final String FACEBOOK_APPID = "152426674829331";//219680308049221

private static final String FACEBOOK_PERMISSION = "publish_stream";

private static final String MSG = " Testing TalkUsage Application ";

private final Handler mFacebookHandler = new Handler();

private FacebookConnector mFacebookConnector;

final Runnable mUpdateFacebookNotification = new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), getString(R.string.facebookposted), TOASTTIME).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
this.mFacebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
mFaceBook = (ImageView)findViewById(R.id.Facebook);
mFaceBook.setOnClickListener(mFaceBookListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.mFacebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
}

@Override
protected void onResume()
{
super.onResume();
clearCredentials();
}

private String getFacebookMsg()
{
return new Date().toLocaleString() + MSG;
}
public void postMessage()
{
if (mFacebookConnector.getFacebook().isSessionValid())
{
postMessageInThread();
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
@Override
public void onAuthSucceed()
{
postMessageInThread();
}

@Override
public void onAuthFail(String error)
{
Log.e(TAG, error);
}
};
SessionEvents.addAuthListener(listener);
mFacebookConnector.login();
}
}

private void postMessageInThread()
{
Thread mThread = new Thread()
{
public void run()
{
mFacebookConnector.postMessageOnWall(getFacebookMsg());
mFacebookHandler.post(mUpdateFacebookNotification);
clearCredentials();
}
};
mThread.start();
}

private void clearCredentials()
{
try
{
mFacebookConnector.getFacebook().logout(getApplicationContext());
}
catch (MalformedURLException mMalformedURLException)
{
Log.e(TAG, getString(R.string.malformedurlexceptionerror) + mMalformedURLException.toString());
}
catch (IOException mIOException)
{
Log.e(TAG, getString(R.string.ioexceptionerror) + mIOException.toString());
}
}
private OnClickListener mFaceBookListener = new OnClickListener()
{
public void onClick(View v)
{
postMessage();
}
};

How to integrate facebook in Android


private static final String FACEBOOK_APPID = "152426674829331";//219680308049221

private static final String FACEBOOK_PERMISSION = "publish_stream";

private static final String MSG = " Testing TalkUsage Application ";

private final Handler mFacebookHandler = new Handler();

private FacebookConnector mFacebookConnector;

final Runnable mUpdateFacebookNotification = new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), getString(R.string.facebookposted), TOASTTIME).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
this.mFacebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
mFaceBook = (ImageView)findViewById(R.id.Facebook);
mFaceBook.setOnClickListener(mFaceBookListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.mFacebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
}

@Override
protected void onResume()
{
super.onResume();
clearCredentials();
}

private String getFacebookMsg()
{
return new Date().toLocaleString() + MSG;
}
public void postMessage()
{
if (mFacebookConnector.getFacebook().isSessionValid())
{
postMessageInThread();
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
@Override
public void onAuthSucceed()
{
postMessageInThread();
}

@Override
public void onAuthFail(String error)
{
Log.e(TAG, error);
}
};
SessionEvents.addAuthListener(listener);
mFacebookConnector.login();
}
}

private void postMessageInThread()
{
Thread mThread = new Thread()
{
public void run()
{
mFacebookConnector.postMessageOnWall(getFacebookMsg());
mFacebookHandler.post(mUpdateFacebookNotification);
clearCredentials();
}
};
mThread.start();
}

private void clearCredentials()
{
try
{
mFacebookConnector.getFacebook().logout(getApplicationContext());
}
catch (MalformedURLException mMalformedURLException)
{
Log.e(TAG, getString(R.string.malformedurlexceptionerror) + mMalformedURLException.toString());
}
catch (IOException mIOException)
{
Log.e(TAG, getString(R.string.ioexceptionerror) + mIOException.toString());
}
}
private OnClickListener mFaceBookListener = new OnClickListener()
{
public void onClick(View v)
{
postMessage();
}
};

How to integrate facebook in Android


private static final String FACEBOOK_APPID = "152426674829331";//219680308049221

private static final String FACEBOOK_PERMISSION = "publish_stream";

private static final String MSG = " Testing TalkUsage Application ";

private final Handler mFacebookHandler = new Handler();

private FacebookConnector mFacebookConnector;

final Runnable mUpdateFacebookNotification = new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), getString(R.string.facebookposted), TOASTTIME).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
this.mFacebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});
mFaceBook = (ImageView)findViewById(R.id.Facebook);
mFaceBook.setOnClickListener(mFaceBookListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.mFacebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
}

@Override
protected void onResume()
{
super.onResume();
clearCredentials();
}

private String getFacebookMsg()
{
return new Date().toLocaleString() + MSG;
}
public void postMessage()
{
if (mFacebookConnector.getFacebook().isSessionValid())
{
postMessageInThread();
}
else
{
SessionEvents.AuthListener listener = new SessionEvents.AuthListener()
{
@Override
public void onAuthSucceed()
{
postMessageInThread();
}

@Override
public void onAuthFail(String error)
{
Log.e(TAG, error);
}
};
SessionEvents.addAuthListener(listener);
mFacebookConnector.login();
}
}

private void postMessageInThread()
{
Thread mThread = new Thread()
{
public void run()
{
mFacebookConnector.postMessageOnWall(getFacebookMsg());
mFacebookHandler.post(mUpdateFacebookNotification);
clearCredentials();
}
};
mThread.start();
}

private void clearCredentials()
{
try
{
mFacebookConnector.getFacebook().logout(getApplicationContext());
}
catch (MalformedURLException mMalformedURLException)
{
Log.e(TAG, getString(R.string.malformedurlexceptionerror) + mMalformedURLException.toString());
}
catch (IOException mIOException)
{
Log.e(TAG, getString(R.string.ioexceptionerror) + mIOException.toString());
}
}
private OnClickListener mFaceBookListener = new OnClickListener()
{
public void onClick(View v)
{
postMessage();
}
};

Wednesday, June 15, 2011

XML parsing using SAX and retrive images

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ListView android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_weight="1"
        android:fadingEdge="none" android:id="@+id/view">
    </ListView>
</LinearLayout>

List.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">
    <LinearLayout android:id="@+id/linearLayout1"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:orientation="vertical" android:padding="10px"
        android:background="#FFFFFF">
        <TextView android:text="TextView" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/textView1"
            android:gravity="center_horizontal" android:textStyle="bold" />
        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/linearLayout2">
            <ImageView android:id="@+id/imageView1" android:src="@drawable/icon"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
            <TextView android:text="TextView" android:id="@+id/textView2"
                android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

mainActivity.java

package com.hb.Passing;

import java.net.URL;
import java.util.ArrayList;

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

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {
    private ArrayList<String> title = new ArrayList<String>();
    private ArrayList<String> image = new ArrayList<String>();
    private ArrayList<String> text = new ArrayList<String>();

    private LazyAdapter lad;
    private ListView list;
    Message_set message;
    private String ss = " ";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list = (ListView) findViewById(R.id.view);

        try {
            ss = "pass the url";
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            XMLHandler handler = new XMLHandler();
            URL sourceUrl = new URL(ss);
            xr.setContentHandler(handler);
            xr.parse(new InputSource(sourceUrl.openStream()));
        } catch (Exception e) {
            e.getMessage();
        }
        message = XMLHandler.getMessage_set();

        title = message.gettitle();
        image = message.getimage();
        text = message.gettext();

        lad = new LazyAdapter(MainActivity.this, title, image, text);
        try {
            list.setAdapter(lad);
        } catch (Exception e) {
            e.getMessage();
        }

    }
}

Message_set.java

package com.hb.Passing;

import java.util.ArrayList;

public class Message_set
{
    private ArrayList<String> title = new ArrayList<String>();
    private ArrayList<String> image = new ArrayList<String>();
    private ArrayList<String> text = new ArrayList<String>();
   
    public ArrayList<String> gettitle()
    {
        return title;
    }
    public void settitle(String title)
    {
        this.title.add(title);
    }
    public ArrayList<String> getimage()
    {
        return image;
    }
    public void setimage(String image)
    {
        this.image.add(image);
    }
    public ArrayList<String> gettext()
    {
        return text;
    }
    public void settext(String text)
    {
        this.text.add(text);
    }
}


XMLHandler.java

package com.hb.Passing;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;


public class XMLHandler implements ContentHandler
{
    public static Message_set message = null;
    Boolean currentElement = false;
    String currentValue = null;
   
    public static Message_set getMessage_set()
    {
        return message;
    }
    public static void setSitesList(Message_set message)
    {
        XMLHandler.message = message;
    }

    @Override
    public void startElement(String uri, String localName, String qName,Attributes atts) throws SAXException
    {
        currentElement = true;
        if(localName.equals("channel"))
        {
            message = new Message_set();
        }
       
    }
   
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        if (currentElement)
        {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }
    }
   
    @Override
    public void endElement(String uri, String localName, String qName)throws SAXException
    {
        currentElement = false;
        if (localName.equalsIgnoreCase("title"))
        {
            message.settitle(currentValue);
        }
        else if(localName.equalsIgnoreCase("image"))
        {
            message.setimage(currentValue);
        }
        else if (localName.equalsIgnoreCase("description"))
        {
            message.settext(currentValue);
        }
    }

    @Override
    public void endDocument() throws SAXException
    {
       
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException
    {
       
    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)throws SAXException
    {
       
    }

    @Override
    public void processingInstruction(String target, String data)throws SAXException
    {
       
    }

    @Override
    public void setDocumentLocator(Locator locator)
    {
       
    }

    @Override
    public void skippedEntity(String name) throws SAXException
    {
       
    }

    @Override
    public void startDocument() throws SAXException
    {
       
    }

    @Override
    public void startPrefixMapping(String prefix, String uri)throws SAXException
    {
       
    }

}

LazyAdapter.java

package com.hb.Passing;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter
{
    private Activity activity;
    private ArrayList<String> title1 = new ArrayList<String>();
    private ArrayList<String> image1 = new ArrayList<String>();
    private ArrayList<String> text1 = new ArrayList<String>();
    int size = 0;
    private static LayoutInflater inflater=null;
   
    public LazyAdapter(MainActivity mainActivity, ArrayList<String> title,ArrayList<String> image, ArrayList<String> text)
    {
        activity = mainActivity;
        title1 = title;
        image1 = image;
        text1 = text;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        size = title.size();
    }

    public class  ViewHolder 
    {
        public TextView title_txt;
        public TextView dis_txt;
        public ImageView img;
    }
   
    @Override
    public int getCount()
    {
        return size;
    }

    @Override
    public Object getItem(int position)
    {
        return position;
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }
   
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View v=convertView;
        ViewHolder holder;
       
        if(convertView==null)
        {
            try
            {
                v =inflater.inflate(R.layout.listview,null);
            }
            catch(Exception e)
            {
                e.getMessage();
            }
           
            holder=new ViewHolder();
           
            try
            {
                holder.title_txt=(TextView)v.findViewById(R.id.textView1);
                holder.dis_txt=(TextView)v.findViewById(R.id.textView2);
                holder.img=(ImageView) v.findViewById(R.id.imageView1);
            }
            catch(Exception e)
            {
                e.getMessage();
            }
           
            v.setTag(holder);
        }
        else
        {  
             holder=(ViewHolder)v.getTag();
        }
       
        // title       
        if(title1.get(position).toString().equals(""))
        {
            holder.title_txt.setText("");
        }
        else
        {
            String s = title1.get(position).toString();
            holder.title_txt.setText(s);
           
        }
       
        // Image
        if(image1.get(position).toString().equalsIgnoreCase("noimage.png"))
        {
            holder.img.setImageResource(R.drawable.icon);   
        }
        else
        {   
            try
            {
                String s = image1.get(position).toString();
                URL url = new URL(s);
                InputStream is = (InputStream) url.getContent();
                Drawable d = Drawable.createFromStream(is, "src");
                holder.img.setImageDrawable(d);
            }
            catch (Exception e)
            {
                e.getMessage();   
            }
        }
   
       
        // Distance
        if(text1.get(position).toString().equals(""))
        {
            holder.dis_txt.setText("");
           
        }
        else
        {
            String ss = text1.get(position).toString();
            Spanned span1 = Html.fromHtml(ss);
            holder.dis_txt.setText(span1);
           
        }

       
        return v;
    }
}