Monday, May 6, 2013

Android Pinterest Listview Example

Android Pinterest Listview Example

This post about Pinterest Listview in Android.
What is Pinterest Listview?
Display the items in multiple columns using multiple Listview on single screen.
Below i added the code for pinterest view.

Check Out This LINK  : Click here
Displaying data from two different rss feed using two listview in single screen



Activity Source Code
package com.androidbunch.pinterest.listview;

import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;


/**
 *
 * @author VIJAYAKUMAR M
 *
 */
public class MainActivity extends Activity  {
     
      private ListView listViewLeft;
      private ListView listViewRight;
      private RssReaderListAdapter leftAdapter;
      private RssReaderListAdapter rightAdapter;

      int[] leftViewsHeights;
      int[] rightViewsHeights;
      List<RssFeedStructure> rssStr ;
      List<RssFeedStructure> tam ;
      private RssReaderListAdapter _adapter;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.items_list);     
           
            listViewLeft = (ListView) findViewById(R.id.list_view_left);
            listViewRight = (ListView) findViewById(R.id.list_view_right);
            RssFeedTask rss = new RssFeedTask();
            rss.execute();
            listViewLeft.setOnTouchListener(touchListener);
            listViewRight.setOnTouchListener(touchListener);           
            listViewLeft.setOnScrollListener(scrollListener);
            listViewRight.setOnScrollListener(scrollListener);
      }
     
      // Passing the touch event to the opposite list
      OnTouchListener touchListener = new OnTouchListener() {                            
            boolean dispatched = false;
           
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                  if (v.equals(listViewLeft) && !dispatched) {
                        dispatched = true;
                        listViewRight.dispatchTouchEvent(event);
                  } else if (v.equals(listViewRight) && !dispatched) {
                        dispatched = true;
                        listViewLeft.dispatchTouchEvent(event);
                  }
                 
                  dispatched = false;
                  return false;
            }
      };
     
      /**
       * Synchronizing scrolling
       * Distance from the top of the first visible element opposite list:
       * sum_heights(opposite invisible screens) - sum_heights(invisible screens) + distance from top of the first visible child
       */
      OnScrollListener scrollListener = new OnScrollListener() {
           
            @Override
            public void onScrollStateChanged(AbsListView v, int scrollState) {     
            }
           
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {
                 
                  if (view.getChildAt(0) != null) {
                        if (view.equals(listViewLeft) ){
                              leftViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();
                             
                              int h = 0;
                              for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
                                    h += rightViewsHeights[i];
                              }
                             
                              int hi = 0;
                              for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
                                    hi += leftViewsHeights[i];
                              }
                             
                              int top = h - hi + view.getChildAt(0).getTop();
                              listViewRight.setSelectionFromTop(listViewRight.getFirstVisiblePosition(), top);
                        } else if (view.equals(listViewRight)) {
                              rightViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();
                             
                              int h = 0;
                              for (int i = 0; i < listViewLeft.getFirstVisiblePosition(); i++) {
                                    h += leftViewsHeights[i];
                              }
                             
                              int hi = 0;
                              for (int i = 0; i < listViewRight.getFirstVisiblePosition(); i++) {
                                    hi += rightViewsHeights[i];
                              }
                             
                              int top = h - hi + view.getChildAt(0).getTop();
                              listViewLeft.setSelectionFromTop(listViewLeft.getFirstVisiblePosition(), top);
                        }
                       
                  }
                 
            }
      };
     
       private class RssFeedTask extends AsyncTask<String, Void, String> {
                  // private String Content;
                  private ProgressDialog Dialog;
                  String response = "";

                  @Override
                  protected void onPreExecute() {
                        Dialog = new ProgressDialog(MainActivity.this);
                        Dialog.setMessage("Rss Loading...");
                       Dialog.show();
                  }
                  @Override
                  protected String doInBackground(String... urls) {
                          try {
                             
                                String feed = "http://timesofindia.feedsportal.com/c/33039/f/533965/index.rss";
                                String tamil = "http://www.dinakaran.com/rss_Latest.asp";
                                XmlHandler rh = new XmlHandler();
                                XmlHandler rh1 = new XmlHandler();
                                rssStr = rh.getLatestArticles(feed);
                                tam = rh1.getLatestArticles(tamil);
                                response = "in";
                                } catch (Exception e) {
                              response = "out";
                                }
                        return response;
                  }

                  @Override
                  protected void onPostExecute(String result) {
                            leftAdapter = new RssReaderListAdapter(MainActivity.this,rssStr);
                              rightAdapter =new RssReaderListAdapter(MainActivity.this,tam);
                              listViewLeft.setAdapter(leftAdapter);
                              listViewRight.setAdapter(rightAdapter);
                              leftViewsHeights = new int[rssStr.size()];
                              rightViewsHeights = new int[tam.size()]; 
                          Dialog.dismiss();
                  }
            }

}

Adapter Source Code




package com.androidbunch.pinterest.listview;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.app.Activity;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 *
 * @author VIJAYAKUMAR M
 *
 */

public class RssReaderListAdapter extends ArrayAdapter<RssFeedStructure> {
      List<RssFeedStructure> imageAndTexts1 =null;
       public ImageLoader imageLoader;
      // float imageWidth;
       Activity act;
public RssReaderListAdapter(Activity activity, List<RssFeedStructure> imageAndTexts) {
super(activity, 0, imageAndTexts);
imageAndTexts1 = imageAndTexts;
act = activity;
imageLoader=new ImageLoader(activity.getApplicationContext());

}


@Override
public View getView(final int position, View convertView, ViewGroup parent) {

Activity activity = (Activity) getContext();
LayoutInflater inflater = activity.getLayoutInflater();


View rowView = inflater.inflate(R.layout.rssfeedadapter_layout, null);
TextView textView = (TextView) rowView.findViewById(R.id.feed_text);
TextView timeFeedText = (TextView) rowView.findViewById(R.id.feed_updatetime);
Button btn = (Button) rowView.findViewById(R.id.button1);

btn.setOnClickListener(new OnClickListener() {
     
      @Override
      public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(act, imageAndTexts1.get(position).getTitle(), Toast.LENGTH_LONG).show();
      }
});
ImageView imageView = (ImageView) rowView.findViewById(R.id.feed_image);
        try {
           
            Log.d("rssfeed", "imageAndTexts1.get(position).getImgLink() :: " +imageAndTexts1.get(position).getImgLink() +" :: " +imageAndTexts1.get(position).getTitle());
            textView.setText(imageAndTexts1.get(position).getTitle());
            SpannableString content = new SpannableString(imageAndTexts1.get(position).getPubDate());
            timeFeedText.setText(content);
            if(imageAndTexts1.get(position).getImgLink() !=null){
            URL feedImage= new URL(imageAndTexts1.get(position).getImgLink().toString());
            if(!feedImage.toString().equalsIgnoreCase("null")){
                  
            }
             else{
                
             }
                  }
      
           
        } catch (MalformedURLException e) {
      
        }
        catch (IOException e) {
       
        }

return rowView;

}


}
 


XmlHandler Source Code




package com.androidbunch.pinterest.listview;


import java.io.IOException;
import java.net.MalformedURLException;
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;

import android.util.Log;


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 = 50;

StringBuffer chars = new StringBuffer();

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

 if (qName.equalsIgnoreCase("enclosure"))
     
{
       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"))
{
      feedStr.setUrl(chars.toString());

}
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;
}

}
  

items_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"
    android:orientation="vertical"
    android:background="#FFFFFF"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >


<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="#FFFFFF"
  
  >
    <ListView
        android:id="@+id/list_view_left"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:paddingRight="5dp"
        android:scrollbars="none" >
    </ListView>
<View android:layout_height="fill_parent" android:layout_width="1dip" android:background="#E4E4E4" />
    <ListView
        android:id="@+id/list_view_right"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:paddingLeft="5dp"
        android:scrollbars="none" >
    </ListView>
</LinearLayout>
</LinearLayout>
  

rssfeedadapter_layout.xml

 


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:padding="2dip" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dip" >

        <ImageView
            android:id="@+id/feed_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
          
            android:paddingRight="3dip"
            android:paddingTop="15dip" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:id="@+id/feed_updatetime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/feed_text"
        android:layout_below="@+id/linearLayout1"
        android:paddingBottom="3dip"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
        android:paddingTop="3dip"
        android:text="afsdfd"
        android:textColor="#A4A4A4"
        android:textSize="8dip" />

    <TextView
        android:id="@+id/feed_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_below="@+id/feed_updatetime"
        android:maxLines="5"
        android:paddingBottom="15dip"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
        android:text="afsdfd"
        android:textColor="#000000" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/feed_text"
        android:text="Full News" />

</RelativeLayout>






15 comments:

  1. Howdy! I know this is kinda off topic but I was wondering if you
    knew where I could find a captcha plugin for my comment form?

    I'm using the same blog platform as yours and I'm having
    trouble finding one? Thanks a lot!

    Also visit my weblog; Michael Kors Outlet

    ReplyDelete
  2. hi i am ganesh u r blog is awesome .........am a fresher in android development,i have learnt so many things from u r blog...
    i am developing smschat App,,it contains list of messages,i want to set the date & time to each message,the date & time shoud update every time....in textview but am unable get set the date & time
    so plz could u help me in this app....
    my mail id is:ganeshmudhiraj12@gmail.com
    my code is as follows......


    GregorianCalendar calCreationDate = new GregorianCalendar();
    int intMilli = calCreationDate.get(Calendar.MILLISECOND);
    int intSeconds = calCreationDate.get(Calendar.SECOND);
    calCreationDate.add(Calendar.MILLISECOND, (-1*intMilli));
    calCreationDate.add(Calendar.SECOND, -1*intSeconds);
    calCreationDate.add(Calendar.MINUTE, 1);
    Date dateStartDate = calCreationDate.getTime();

    String time =dateStartDate.toString();




    Thanks.....

    ReplyDelete
  3. Wonderful work! That is the type of info that are supposed to be shared around the net.
    Disgrace on Google for no longer positioning this post upper!
    Come on over and consult with my site . Thank you =)

    My web-site :: novoline automaten spielen

    ReplyDelete
  4. ωhoah this weblоg іѕ wondеrful i love reаding уour postѕ.
    Ѕtaу uρ the good work! You already know, lotѕ of indіvidualѕ аre
    searсhing around for this informatіοn, yоu can help them gгeаtly.


    Fеel free to visit my web-sitе: www.Ukinsurancewise.co.Uk

    ReplyDelete
  5. Hey There. I found your blog using msn. This is a very well written article.
    I'll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I'll certainly comeback.



    Look into my webpage - Jordan Femme

    ReplyDelete
  6. Does yоur blog hаvе a сοntаct рage?
    I'm having problems locating it but, I'd lіke
    tο shoot уоu an email.
    I've got some suggestions for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

    My site :: 1 Day Car insurance

    ReplyDelete
  7. Nice post. I used to be checking constantly this weblog and I
    am inspired! Extremely useful info specifically the final section :) I take care of such information a lot.
    I was looking for this particular information for a very long time.
    Thank you and best of luck.

    Also visit my web page :: book of ra apk

    ReplyDelete
  8. I'll immediately clutch your rss as I can't in finding your e-mail subscription link or
    newsletter service. Do you have any? Please allow me know so that I may subscribe.
    Thanks.

    Take a look at my web-site ... Air Jordan Pas Cher

    ReplyDelete
  9. Hi there! Do you know if they make any plugins to assist with Search Engine Optimization?
    I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good gains.
    If you know of any please share. Thank you!

    My web blog; book of ra apk downloaden

    ReplyDelete
  10. I got this web page from my friend who shared with me
    about this website and at the moment this time I am
    visiting this web site and reading very informative content
    at this time.

    Visit my web blog ... ヴィトン財布

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hi
    I wonder what is ImageLoader in Adapter Source Code

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. what the "rssfeedstructure"?!?!
    i'm following this source exactly, but the red line under the structure make me a shit.

    ReplyDelete

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...