Thursday, March 17, 2011

jQuery File Upload Plugin With Drag ‘n’ Drop Support

jQuery File Upload Plugin With Drag ‘n’ Drop Support: "

jQuery File Upload is a plugin for the popular JavaScript framework that helps handling file uploads.


The plugin is based on open standards like HTML5-JavaScript and doesn't use Flash. For legacy browsers it falls back to an Ajaxed-like iframe-PHP solution.


jQuery Drag Drop File Upload


Multiple files can be selected, they can even be drag 'n' dropped from the desktop and the upload process can start automatically or with an event (like clicking the "upload" button).


A progress bar can display the status and uploads can be canceled anytime.


It is possible to use multiple instances of the plugin in the same page and jQuery File Upload is compatible with any server-side application platform.


Special Downloads:

Ajaxed Add-To-Basket Scenarios With jQuery And PHP

Free Admin Template For Web Applications

jQuery Dynamic Drag’n Drop

ScheduledTweets


Advertisements:

Professional XHTML Admin Template ($15 Discount With The Code: WRD.)

Psd to Xhtml

SSLmatic – Cheap SSL Certificates (from $19.99/year)




"

Thursday, March 10, 2011

The Ultimate 20 Usability Tips for Your Website

The Ultimate 20 Usability Tips for Your Website: "Usability is ridiculously important to your website. It doesn’t matter how cool your website looks or how amazing your content is if visitors can’t quickly, easily, and enjoyably access and use it. Many of them will eventually just give up and look elsewhere."

Ecommerce Fraud Management Systems: The What The Why and The How

Ecommerce Fraud Management Systems: The What The Why and The How: "

Card-not-present credit card fraud cost online merchants 0.9% of revenue in 2010 (down from 1.4% in 2008 and 3.6% in 2000) according to research by Cybersource.


The expense of chargebacks, unrecoverable transfers, unnecessary shipping costs and human resources to investigate disputes add up, and a company’s goodwill can be damaged with banks when fraud rates are higher than average. Chargeback rates higher than your merchant bank’s acceptable threshold may cause you to lose your merchant account, and make it more difficult for you to open one with another bank. And processing fraudulent transactions that a cardholder must dispute tarnishes your brand name in their eyes, and could spark negative word of mouth.


Fraud management systems, both manual and automated, aim to curb fraud losses and protect cardholders from unauthorized use of their accounts. Last post we covered 3D Secure cardholder authentication (e.g. Verified by Visa, MasterCard Secure Code), which is only one tool in your fraud management arsenal, and should not be relied upon alone. Today we examine these tools, and what you should consider when developing your fraud management solution.


Basic automated fraud management tools


AVS


Address Verification Service, or AVS, is a tool that checks a customer’s input name, address and card number details against a database of addresses on file with card issuing banks. AVS is not available for all countries, issuing banks and card types. For example, American Express only supports AVS in the US.


While AVS is effective at preventing fraudsters, it’s also prone to reject good orders, as it requires an exact match of the customer’s billing address. For example, an address #33-1234 Suchandsuch Road may be rejected if the on-file address is 1234 Suchandsuch Rd Apt. 33. If a bona fide customer attempts the address multiple times “incorrectly,” her card may be locked out of use temporarily.


Another problem is an AVS mismatch may not prevent the authorization from appearing on the cardholder’s statement. The issuing bank can hold the authorized amount for 3 to 7 days unless contacted by the customer. But confused and irate customers who find the charges may complain to your customer service.


It’s a good idea to provide error messaging when a mismatch occurs that explains the address must be exactly as on the cardholder’s statements. (Test it in different browsers to make sure it’s readable!)



Because it’s easy to reject good orders and accept fraudulent ones, you don’t want to rely on AVS alone. Mismatches and partial matches do not have to be rejected, they may be flagged for manual review.


CVV


I’ve written about the perils of and workarounds for CVV (aka CSC, CVN, CVC and CVV2) on Get Elastic before. To recap, CVV (card verification value) can create 2 conversion problems. Some customers will not know what CVV is or where to find it. Others fear handing over their security code means it may fall into the wrong hands. Address both these FUDs (fears, uncertainties and doubts) by showing visually where to find the code, and explaining the number will not be stored in your database.



3D Secure


As discussed in detail last post, Verified by Visa, MasterCard Secure Code and their cousins add an extra layer of authentication to the checkout process by means of a personal password/PIN. The main benefit for retailers is the liability shift from the merchant to the issuing bank should the customer file a chargeback. Merchants may also enjoy lower interchange fees for participating in the scheme. However, the extra step in checkout is not always appreciated by customers. Many merchants report a drop in conversion when using 3D Secure.


Again, 3D Secure is not the silver bullet to prevent fraud. Not all card issuing banks participate with Verified by Visa, and not all cardholders have enrolled. Unenrolled cardholders are allowed to opt-out a number of times (variable) before being required to join the program, and identity thieves who are first to use a new card online can set their own passwords.


The decision whether to use 3D Secure depends on a number of things explained last post.


Automated Transactional Risk Scoring


ATRS solutions enable ecommerce systems to identify suspicious behavior, assign a “risk factor” and reject or flag a risky order for manual review. The logic and settings are custom to the online retailer based on past experience and other industry factors. They may be home-grown or third-party (e.g. Cybersource, Ethoca, Accertify). The downside of home-grown solutions is they depend heavily on the trial-and-error experience of your own business. Third-party services that pull data from a large user base are more nimble in detecting fraud trends and can have higher accuracy, but may also come at a much higher cost.


Beyond AVS, CVV, 3D Secure, a variety of other tools may be used by the ATRS including:



  • IP detection Identifies user’s location and checks against known high risk IP and email addresses

  • Device fingerprinting Reads data from and about a device and browser session including true IP address and location (can identify proxies), and whether the device has been involved in previous fraudulent activities. (More features than simple IP detection)

  • Order velocity monitoring Flags orders that have been submitted within a specific time period from one card or IP address

  • Positive lists Records of “good” customers, based on order history

  • Negative lists Known “bad” IPs, card numbers, device IDs, name/address combos, etc. Some banks end up on black lists if they are known to have higher rates of fraud among cards they have issued

  • Shared lists Positive/negative lists shared across companies


Systems are typically tuned to detect suspicious behavior like high dollar value baskets, unusual product mixes (random selection of clothing sizes, for example), large quantities of a single item (especially electronics) and rapid additions to cart.


What one e-tailer considers abnormal may be the norm for other businesses, so automated systems allow rules-based tweaking. For example, a $1,000 order may be suspicious for an electronics store but very common for a furniture shop that sells $5,000 living room sets. A billing and shipping address mismatch is common with gifts and flower delivery sites, but may be more suspicious for others. Some businesses may want to reject orders from certain regions, or flag orders shipping to P.O. boxes, prisons, hotels, schools and hospitals.


Manual Reviews


Despite automation’s virtues, some orders call for manual review. This may involve calling the customer or the customer’s bank, using reverse lookup tools, checking customer records or even using Google Maps and social media to track down a name/address. (Some automated tools have the ability to check email addresses across social networks).


Manual review by humans is obviously more costly and time consuming than automated tools, and using a number of different automated tools *should* reduce costs. However, the more automated tools you use (the average is 7.4 for large ecommerce companies), the more likely an order will be flagged for manual review! Companies that seem to squeak by with a low percentage of manual reviews are likely rejecting good orders, and should understand where the sweet spot lies between resource savings and sales and profits. Ideally, manual reviews should be reserved for orders you want to keep, rather than as a fraud detection method.


What system is right for you?


There’s no one-size-fits-all fraud management solution. Your needs will vary based on your transaction volume, industry, geographic market(s) and rate of fraud, and your options may be limited by staffing or budget (smaller merchants tend to rely solely on manual reviews and the “basic” automated services). The rules you apply to your system will also vary based on the nuances of your individual business. Keep the following in mind when choosing / using a fraud management system:


1. Order rejection rates


Merchants with slimmer margins have more to lose when orders are fraudulent, and tend to have higher order rejection rates. Those with higher margins can absorb more fraud, accepting a higher risk in exchange for faster order processing and shipment, and less false-positives.


2. False-positives


A continual challenge with automated tools is the rejection of legitimate orders (false-positives). Tools should be continually tweaked when false positives are identified. Julie Fergerson of Ethoca recommends you monitor your “order resuscitation” rate, along with customer complaints to your call center on rejected orders. “It should be very low.”


3. System maintenance


In addition to false-positive feedback, tools require continual updating, both with new technologies to combat fraud and with information you gather from day-to-day operations. For example, daily review of declines (both internal rejections and those declined by issuing banks) can help you discover authorization problems that may exist, or commonalities among purchase behavior or other characteristics of declined orders. Fergerson says “even a purchased risk engine needs to be constantly analyzed. Otherwise, they can be worse than just guessing.”


4. Staffing


Insufficient staffing can delay orders, leading to unhappy customers and more WISMO (where is my order) calls to your customer service team. Ill-trained staff can also reject good orders and let bad ones slip through. Some fraud management vendors offer outsourced manual review staff, which may have some efficiencies (scale up and down as needed), and in some cases, better trained staff.


The takeaway


There are many weapons available to help your quest for fighting fraud, but there’s a fine balance between stopping bad orders and preserving good ones. No matter what your fraud management system looks like, it requires continual maintenance to be effective. You should be continually adjusting rules and processes based on the overall online fraud environment and your own learnings to ensure you’re maximizing profits and minimizing losses.


Looking for help with your ecommerce strategy and site optimization? The Elastic Path research and consulting division is available to enterprises selling digital goods and services. For more information, visit us at http://elasticpath.com/ecommerce-consulting/ or contact us at consulting@elasticpath.com.

"

Tuesday, March 8, 2011

7 jQuery plugins you should not miss

7 jQuery plugins you should not miss: "Jquery is a client based application that runs on user side i.e. at your web browser. One of the best things about jQuery is that it allows users to add interactive functionalities to their websites. Interactiveness allows you to increase the functionality of your website by producing robustness and dynamicity in your website. To understand [...]


"

Monday, February 28, 2011

OO Design Principles Compilation

OO Design Principles Compilation: "

This page is a work in progress… a compilation of information about object-oriented design principles and values.


S.O.L.I.D. Class Design Principles


Collected by Robert C. Martin for his book “Applying Principles and Patterns”


Single Responsibility Principle (SRP)


A class should have only one reason to change. For example, if a change to the business rules causes a class to change, then a change to the database schema, GUI, report format, or any other segment of the system should not force that class to change.



Open/Closed Principle (OCP)


Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.



Liskov substitution principle (LSP)


Subtypes must be substitutable for their base types. If class A inherits from class B, then wherever you can use A you should be able to use B. E.g. remember that square is not necessarily a rectangle! When extending: Preconditions cannot be straightened, Postconditions cannot be loosened, visible Invariants cannot be changed (?). Invariants: users depend on this both before and after sending a message. Use a proper set-based inheritance relationship. Not following set semantics is very risky. Subsumption Rule: A reference to a subtype can be used in any context where a reference to a super type is expected. This principle extremely limits what SHOULD be done with the pure extension (inheritance) mechanism. Do not follow at your own risk.



Interface Segregation Principle (ISP)


The dependency of one class to another one should depend on the smallest possible interface.



Dependency Inversion Principle (DIP)


Depend upon abstractions (interfaces), not upon concrete classes.



Other Important Ones


Law of Demeter


aka Principle of Least Knowledge: Only talk to your friends


Any method M of an object O may only invoke the methods of the following kinds of objects:



  • itself

  • its arguments/parameters

  • any objects it creates/instantiates

  • its direct component objects


See



Hollywood Principle


Don’t call us, we’ll call you.



Don’t Repeat Yourself (DRY)


Remove duplication.



Program to an interface, not an implementation


Maybe just another way to say dependency inversion.



You Ain’t Gonna Need It (YAGNI)


Do not add code that you “think will be used later”. Add code only at “Last Responsible Moment”



Keep It Simple, Stupid (KISS)


What is the simplest thing that could possibly work?



And More


Encapsulation and Information Hiding


http://en.wikipedia.org/wiki/Encapsulation_(computer_science) http://en.wikipedia.org/wiki/Information_hiding


Separation of Concerns (SoC)


http://ctrl-shift-b.blogspot.com/2008/01/art-of-separation-of-concerns.html


High Cohesion


http://en.wikipedia.org/wiki/Cohesion_(computer_science)


Low/Loose coupling



Convention over Configuration (CoC)


http://en.wikipedia.org/wiki/Convention_over_Configuration


Command-query separation (CQS)



[edit] Design by Contract (DbC)



Dependency Injection (DI)


Inversion of Control (IoC)


Avoid Fragile Baseclass


http://en.wikipedia.org/wiki/Fragile_base_class


Has-a Is-a


http://en.wikipedia.org/wiki/Has-a http://en.wikipedia.org/wiki/Is-a http://en.wikipedia.org/wiki/Object_composition


What is Identity


http://en.wikipedia.org/wiki/Identity_(object-oriented_programming)


Interchangeability


http://en.wikipedia.org/wiki/Interchangeability_(computer_science)


Option-operand separation


http://en.wikipedia.org/wiki/Option-operand_separation


Intention Revealing Names



Zero Friction Development


http://www.google.com/search?q=Zero+Friction+development


Encapsulate Variation


Separate what varies from what stays the same. Also known as Serenity Principle.



Composition over inheritance



  • Head First Design patterns page 23, 243, 397


Common Closure Principle


Classes that change together must be placed in the same package.






Comments"

Thursday, February 24, 2011

9 Incredible HTML5 Canvas And Javascript Experiments

9 Incredible HTML5 Canvas And Javascript Experiments: "Chrome Experiment has been releasing heaps of incredible HTML5 canvas and javascript experiments. Check out these newest experiments, they are truly unique and jaw dropping."

Tuesday, February 22, 2011

Loading Twitter Data into Android with Lists

Loading Twitter Data into Android with Lists: "

In my previous article, we created your first Android app featuring a basic Hello World function. Well, it seems the real Hello World of the mobile world is a Twitter feed.

This tutorial will guide you through creating a simple Android app to display a list of tweets coming from the JSON based search API provided by Twitter. We will work through:

  • displaying a list of items
  • customizing the look of each list item
  • accessing remote services and parsing data
  • creating responsive user interfaces

For instructions on how to set up an Android development environment, take a look at the previous article, which guides you all the way from installing software and establishing a workspace through to running a skeleton app in the Android Emulator.

Displaying Lists

To get started on our new project, create a new Android project in Eclipse (File -> New -> Other -> Android and select Android Project), entering an appropriate project name, application name, package name, and a name for the single launch activity.

You can see the options I’ve used below:

Android Project Set Up

To check that you have created the project correctly, run the skeleton app in the emulator by highlighting the project name in Eclipse and selecting Run -> Run As -> Android Application.

Currently the Activity you have created will be extending android.app.Activity, and in your onCreate method you will be setting the ContentView of the activity to R.layout.main (linking to the layout as specified in /res/layout/main.xml). The Android SDK provides a convenient way to quickly display a list of data using a superclass called android.app.ListActivity. This Activity already provides a ContentView, configured with a ListView, ready to use and populate with data.

Now change the superclass of TwitterFeedActivity to extend ListActivity, removing the setting of the ContentView from the onCreate method.

The ListView now needs to be given data to display, along with a means to map that data into rows. ListAdaptors provide this mechanism and are set on the underlying ListView of the ListActivity using setListAdaptor.

Create some sample data containing two Strings, and an Android SDK provided adaptor (ArrayAdaptor) that knows how to handle arrays of arbitrary data into ListViews (The Android SDK also comes with several other ListAdaptors, such as Cursor Adaptors, which can assist when connecting local data storage to a ListView). You also need to provide the adaptor with a layout it can use to render the elements onto each row. In the example below we are using the Android SDK provided layout, simple_list_item_1, which is a single text label–perfect for laying our single strings:

public class TwitterFeedActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] elements = {"Line 1", "Line 2"};
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elements));
}
}

Adjust your code as above and confirm the following results in the emulator:

Android Emulator

Customizing List Items

The basic Twitter client needs to display at least two fields per row: the author of the tweet, and the content of the tweet. In order to achieve this you will have to move beyond the inbuilt layout and ArrayAdaptor and implement your own instead.

Start by creating a class called Tweet that can be used to hold both the author and the content as Strings. Then create and populate a Tweet object with some test data to be displayed in the custom list item:

package com.sitepoint.mytwitter;
public class Tweet {
String author;
String content;
}

Create a layout XML file in /res/layout/list_item.xml to define two TextViews to display the content and author on separate rows. In order to display them one above the other, use a LinearLayout, configured to render each element within it vertically (android:orientation='vertical').

<?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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<TextView android:id="@+id/toptext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" android:singleLine="true" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"  android:id="@+id/bottomtext"
android:singleLine="true" />
</LinearLayout>

Once the  XML file has been created, the Android Eclipse plugin will automatically add it as a reference into the generated R file. This R file is kept under the /gen folder of your project and acts as a bridge between your XML elements and your Java code. It allows your Java code to reference XML elements and files created under the /res folders. The file you have just created can now be referenced as R.layout.list_item in the Java code, as you will do next in the custom list adaptor.

Create a private class (inside the Activity) called TweetListAdaptor which subclasses ArrayAdaptor. This class should be used to store an ArrayList of the Tweets being displayed, as well as providing a way to map the Tweet objects to the TextViews you created in the layout above.

This mapping overrides the getView method in ListAdaptor, and should return a View object populated with the contents of the data at the requested position:

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

Furthermore, it should–if possible–reuse any View objects being passed into the method through the convertView parameter. If a new View object has to be created for every element in a list, large lists would stutter when they scroll. Caching Views allows the minimum amount of View objects to be created to populate a large list of data.

The complete implementation of the custom TweetListAdaptor is below. Note the “if statement” checking whether the passed convertView is able to be reused. If the View is null, the ListView has run out of Views to display and requires a new View to be created for this row.

This is achieved using the LayoutService, which is able to inflate (or load) the layout as you specified earlier in XML. You will see here how to reference the layout file using the generated R class through the R.layout.list_item reference.

Once a View is created (or reused), the particular Tweet is extracted from the ArrayList at the position required to be rendered by the ListView. You are then able to obtain references to the two TextView elements using the ids assigned to them in the XML (for example, android:id='@+id/toptext'). Once you have the references, you can set them with the appropriate content and author from the Tweet object.

private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService                         (Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}

Now the onCreate method can be adjusted to use the custom list adaptor with the created test data as shown below:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tweet tweet = new Tweet();
tweet.author = "dbradby";
tweet.content = "Android in space";
ArrayList<Tweet> items = new ArrayList<Tweet>();
items.add(tweet);
TweetListAdaptor adaptor = new TweetListAdaptor(this,R.layout.list_item, items);
setListAdapter(adaptor);
}

which will display the following, when run in the emulator:

Android Emulator Twitter Feed

Accessing remote services and parsing data

The Android SDK contains packages aimed at simplifying access to HTTP-based APIs. The Apache HTTP classes have been included and can be found under the org.apache.http package. You’ll be using these classes, along with the org.json classes to parse the data coming back from a call out the to Twitter search API.

Before any remote services can be accessed from an Android app, a permission has to be declared. This will alert the user (of your app) of what the app might be doing. Permissions could be to monitor incoming SMS, read the address book or, in your case, to simply make a request on the internet. These permissions are displayed to a user in the Android Market place before an app is installed, giving the user the choice of whether they want to give this app the declared permissions.

The permission you need to use is INTERNET and should be inserted outside of the application tag in the AndroidManifest.xml file.

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

With the permission in place, we can create a private method in the Activity that makes a request, parses the result, and returns an ArrayList of Tweet objects. The code listed below makes the request and looks for the resulting JSON array, which is iterated to extract each tweet’s text and from_user elements.

private ArrayList<Tweet> loadTweets(){
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://search.twitter.com/search.json?q=android");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return tweets;
}

Now replace the dummy data you previously used with a call to the loadTweets method when constructing the custom list adaptor in the onCreate method.

TweetListAdaptor adaptor = new TweetListAdaptor(this,R.layout.list_item, loadTweets());

Run this in the emulator and you should now see real data coming back from the API request being displayed in the list view as below:

Android Emulator MyTwitter

Creating responsive user interfaces

The code in its current state has the potential to cause an Application Not Responding (ANR) dialog to appear, prompting the user to quit your app. This can occur due to the long-running work of making a remote request for data being performed within methods such as onCreate.

Long-running tasks should never be performed on the main application thread (which drives the user interface event loop). They should instead be spawned off into child threads to perform the work.

While Java’s Thread class can be used for this task, there is a complication in that once the long-running task is complete, it generally wants to change the user interface to report the results (that is, display a list of tweets loaded from a request).

User interface elements can only have their state altered from the main thread, as the Android UI toolkit is not thread-safe, therefore the background thread needs to message back to the main thread in order to manipulate the UI.

Thankfully, the Android SDK provides a convenient class AsyncTask, which provides an easy mechanism for asynchronous tasks to interact safely with the UI thread. This is achieved by subclassing AsyncTask and overriding the doInBackground method to perform the long-running task, then overriding onPostExecute to perform any manipulations on the UI.

When the AsyncTask is created (it has to be created on the UI thread) and executed, the doInBackground method is invoked on a background thread. On completion, the onPostExecute method is invoked back on the main UI thread.

To use this in your app, you will need to implement a private class within the Activity (like the custom adaptor class) called MyTask, which subclasses AsyncTask. You can override the doInBackground method with the contents of your previous loadTweets method.

Instead of the ArrayList being returned, you maintain an instance variable in the Activity so that the data can be shared across the private classes. Then in the onPostExecute you can set the List Adaptor with the data, as was done previously in onCreate. The onCreate method now simply creates the MyTask object and calls the execute method.

In order to demonstrate the UI responding while the background request is being performed, I have added a ProgressDialog to the AsyncTask as well. The complete listing of the Activity is below:

package com.sitepoint.mytwitter;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TwitterFeedActivity extends ListActivity {
private ArrayList<Tweet> tweets = new ArrayList<Tweet>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TwitterFeedActivity.this,
"", "Loading. Please wait...", true);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://search.twitter.com/search.json?q=android");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.content = session.getString("text");
tweet.author = session.getString("from_user");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new TweetListAdaptor(
TwitterFeedActivity.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context,
int textViewResourceId,
ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.author);
return v;
}
}
}

You should now have a complete app requesting the Twitter data in the background.

The AsyncTask has quite a few more features to explore. You can be sure we will cover those in future articles. In the meantime you should read the excellent Android document covering these classes at http://developer.android.com.






"