White iPhone delay partly due to UV protection

white iphone

In an interview with Ina Fried at AllThingsD, Phil Schiller and Steve Jobs gave a little insight into what made the white iPhone 4 so tough to produce. Actually, it wasn’t really the manufacturing itself, but the materials science needed to make sure the white iPhone was in every way as capable and durable as the black-painted iPhone 4.

Schiller told Fried, “…There’s a lot more that goes into both the material science of it-how it holds up over time…but also in how it all works with the sensors.” There’s also a reference to how the white iPhone needs more “UV protection” than the black one, which I would guess comes from the light that is not absorbed by the black paint passing through the white paint instead.

There’s a lot of tech that goes into the iPhone, and I’m really not surprised that something like a coating of white paint turned out to be tricky, but I think everyone (including Apple, it sounds like) was surprised at how long it took to sort this out. Still, the white iPhone goes on sale tomorrow. Will you get one? Will you apply sunscreen to it?

White iPhone delay partly due to UV protection originally appeared on TUAW on Wed, 27 Apr 2011 14:45:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Square gets the backing of credit card giant Visa

Mobile payment startup Square confirmed it received a strategic investment from Visa. Square produces a credit card reader that connects to the headphone jack of an iPhone, iPad or other mobile platform. The Square application on the device accepts the credit card information from the reader and processes the payment on the fly. It’s an easy way for small businesses to accept credit card payments with minimal hardware requirements and a small 2.75% per transaction fee. [Past TUAW coverage of Square is here. -Ed.]

The company is growing — in the first quarter of 2011 alone, Square processed US$66 million in payments and predicts it will triple that figure to an astounding $198 million in Q2. Square also expanded its retail footprint and is now available online from Apple and in Apple retail stores in the US.

This endorsement by a major credit card company boosts the startup’s reputation and could help the company exceed its lofty goals. The amount of money invested by Visa was not disclosed but Square confirmed Visa will become an advisor to the company. Visa and Square are excellent partners, as over two-thirds of Square’s payment are made using Visa-backed credit cards. Though it enjoys a cozy relationship with Visa, the mobile payment service will still accept payments from MasterCard, American Express and Discover.

Square gets the backing of credit card giant Visa originally appeared on TUAW on Wed, 27 Apr 2011 14:30:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Apple building ‘crowd-sourced traffic’ service for iPhone users

An interesting bit of information has come out from Apple’s announcement today addressing the location-tracking controversy. Apparently Apple is working on a crowd-sourced traffic service for iPhone users. From the press release:

What other location data is Apple collecting from the iPhone besides crowd-sourced Wi-Fi hotspot and cell tower data?

Apple is now collecting anonymous traffic data to build a crowd-sourced traffic database with the goal of providing iPhone users an improved traffic service in the next couple of years.

For a few years now Apple has been rumored to be beefing up its maps offerings in iOS. In 2009 and 2010 Apple bought both Placebase and Poly9, two companies with map and navigation-oriented products. Then in December of last year Apple posting job placement openings looking for engineers with “experience developing navigation software” to “deliver the next generation of Apple products.”

While today’s news of a crowd-sourced traffic database tells us nothing too concrete about Apple’s maps plans, it does appear that Apple is gearing up to add turn-by-turn direction and increased real-time accuracy to its future map offerings on iOS. The third-party market for navigation apps is certainly hopping, so it makes sense for Apple to match up with Google’s turn-by-turn support that’s baked in on Android. (Apple can’t do turn-by-turn directions on the existing Maps app, because it uses Google’s data and the licensing agreements covering that data don’t permit it.)

Apple building ‘crowd-sourced traffic’ service for iPhone users originally appeared on TUAW on Wed, 27 Apr 2011 14:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

White iPhone proximity sensor, death grip tested on video

You don’t have to watch the two videos after the break if you don’t want to — we’ll just tell you that Italy’s iSpazio blog tested the white iPhone’s proximity sensor and “death grip” antenna seam issue, and that, surprise, they’re both fine. The proximity sensor seems to work a little better than that on my black iPhone 4 (based on observations of this video), and while the “death grip” on the iPhone 4’s antenna does make it lose a bar, reception is unaffected. So don’t worry.

The bigger question is why the white iPhone 4 took so long to arrive. We’ve heard Apple was working to improve the proximity sensor and antenna. Also, there may have been issues with the camera, or perhaps Apple had trouble nailing the perfect shade of white. There are a few improvements here, but (without having actually seen one myself) there’s nothing that would conceivably cause a ten-month delay. Maybe it really was that shade of white — was that worth ten extra months?

[via 9to5Mac]

Continue reading White iPhone proximity sensor, death grip tested on video

White iPhone proximity sensor, death grip tested on video originally appeared on TUAW on Wed, 27 Apr 2011 13:30:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

TUAW TV Live at 5 PM EDT: iPad app deep dives

What a great day!

Apple has responded to the “locationgate” controversy in a nice, logical PR blast; the mythical white iPhone 4 will be available starting tomorrow, and here in the Northern Hemisphere it’s really starting to look like Spring.

It’s also Wednesday, which means that later this afternoon you can join me for an hour of fun, tech talk, and technical blunderings on TUAW TV Live. On today’s show, I’m going to take a deep dive into a handful of iPad apps. I’m not going to tell you what those apps are, but let’s just say that they’re fascinating and take advantage of the iPad hardware and user interface in very good ways.

As usual, I’ll be starting the show at 5 PM EDT (2 PM PDT / 10 PM BST) sharp, and we’ll take a few minutes to chat before the demos start. To join in on the chat and watch the live streaming video, drop by TUAW about five minutes before the start time to get your instructions on how to participate. If you’re unable to join us for the show, remember that you can always subscribe to the video podcast and watch the show at your leisure in your iTunes or your other favorite podcatching app.

TUAW TV Live at 5 PM EDT: iPad app deep dives originally appeared on TUAW on Wed, 27 Apr 2011 13:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Ask TUAW: AppleScripting coolness

ask tuaw videoIt’s Tuesday Wednesday, which means it’s time for Ask TUAW Video Edition. We’ve gotten great comments and questions coming in, and we have been trying to get to them all. Some of them are just too hard to show in a video format such as Ask TUAW, so today I have decided to do a little AppleScript “tutorial.”

Here are 4 scripts that I use:

  • iTunes – this script will automatically play/pause my music
  • I’m back – will automatically make Adium go available, and start my music
  • Mail Announce – will announce who incoming mail is from (works with mail.app only)
  • Tell me a joke – tells a random joke

You can download the scripts here. Updated the download link at 5:30pm EST

As always leave us comments below or email us here.

Continue reading Ask TUAW: AppleScripting coolness

Ask TUAW: AppleScripting coolness originally appeared on TUAW on Wed, 27 Apr 2011 12:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Dear Aunt TUAW: How can I edit my EXIF data?

Dear Aunt TUAW,

Help a guy out. How do I edit EXIF data on my Macintosh? I need to know, like, yesterday — so thanks in advance for a quick answer.

Love and hugs,

Dave

Continue reading Dear Aunt TUAW: How can I edit my EXIF data?

Dear Aunt TUAW: How can I edit my EXIF data? originally appeared on TUAW on Wed, 27 Apr 2011 11:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Four Android myths lazy analysts love

The more I read about the tech sector, the more it becomes clear that “analyst” is synonymous with “stand-up philosopher,” which Mel Brooks fans will know is the same thing as an artist who works in a decidedly unsavory medium. This is never more clear than when an outlet like Nielsen releases numbers on the US smartphone market, because immediately afterward legions of “analysts” will leap to the dumbest conclusion possible: Android is ascendant, and Apple is doomed! Dead in the water! DOOOOOMED!

In support of that entirely boneheaded thesis, I’ve noticed a pattern: these “analysts” keep using the same four myopic arguments. All four of these myths dance around a central point, that the smartphone market will only have one “winner,” and it sure won’t be Apple.

The worst part of these analysts’ outlandish claims isn’t that the arguments are so easily dismantled, it’s that so many otherwise intelligent people completely fall for them. Ever since the HTC Dream came out I’ve seen people jumping up and down and saying, “That’s it for Apple, they’re done! Android is going to eat your lunch, sorry fanboys!”

The fact that it’s two and a half years later and that still hasn’t happened is no deterrent to the Android faithful, or the lazy analysts who egg them on in the first place. It’s honestly getting kind of painful to watch this happen every month, especially since the analysts keep saying the exact same things every time.

Read on for the four Android myths that contribute to these analysts’ narrow views.

Continue reading Four Android myths lazy analysts love

Four Android myths lazy analysts love originally appeared on TUAW on Wed, 27 Apr 2011 10:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

iPad 2 will land in 12 new countries starting with Japan on April 28

Apple confirmed the iPad 2 will land in Japan starting tomorrow, April 28. Sales begin at Apple retail stores at 9 am local time. Select authorized resellers will also carry the tablet device and prospective iPad 2 owners should call ahead to confirm availability. If you prefer to shop online and avoid the hubbub of a crowd, you can also order the iPad 2 online from Apple’s website starting at 1 am.

Despite facing the “mother of all backlogs“, Apple is determined to continue the rollout of this popular tablet device. The second generation iPad will be also debut in Hong Kong, India, Israel, Korea, Macau, Malaysia, Philippines, Singapore, South Africa, Turkey and UAE starting April 29. China will score the WiFi version of the iPad 2 starting May 6.

iPad 2 will land in 12 new countries starting with Japan on April 28 originally appeared on TUAW on Wed, 27 Apr 2011 09:45:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

TenFourFox brings Firefox 4 to PPC Macs

TenFourFox

Firefox 4 received quite a bit of fanfare when it finally rolled out of beta. Unfortunately for some Mac users, Mozilla decided to drop support for PowerPC processors and therefore Mac OS X 10.4 Tiger from FF4, meaning that G3, G4 and G5 users were left out in the cold. If you’re one of these users lovingly still using PPC Macs, the folks behind the Mac Classic browser, Classilla, have come to your rescue and brought Firefox 4, with nearly all the trimmings, to the now discarded Mac architecture.

TenFourFox takes code from Firefox 4 and tunes it for OS X 10.4 (compatible with 10.5) and the PPC-architecture. In fact, TenFourFox is offered in hand-tuned builds for each PPC processor: the G3, the G4/7400 and /7450 and, of course, the G5. With the upgrade from Firefox 3.6, you get all the JavaScript speed improvements that Mozilla rolled into Firefox 4, making it by far the fastest browser available for the PPC-Mac. You’ll also get WebM video support, access to most of the Firefox 4 add-ons and, of course, HTML5 and CSS3 support.

If you’re using a perfectly decent and still loved PPC Mac, now is the time to furnish it with a modern browser and extend its life on the Web for years to come.

[via MacStories]

TenFourFox brings Firefox 4 to PPC Macs originally appeared on TUAW on Wed, 27 Apr 2011 09:15:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Apple responds to location tracking controversy

This morning, Apple officially responded to the location tracking controversy that has plagued the Cupertino company. [Apple executives, including Steve Jobs, spoke on the record with AllThingsD about the issue.]

In a press release, Apple asserted that it is not tracking user locations (despite suggestions to the contrary). The ‘configuration.db’ file stored on the handset includes a database of local cell towers and WiFi hotspots; this cache is used to assist in location services and speed up the device’s ‘fix’ in identifying where it is; a GPS-only fix without any hints from other information could date several minutes.

The locations in the file don’t represent the phone’s actual location, according to Apple; the points recorded may be up to 100 miles away from the phone’s true location. The fact that the location data is kept for so long? That’s a bug, according to Apple.

To ameliorate any further problems, Apple will issue a software update to:

  1. reduce the size of the crowd-sourced Wi-Fi hotspot and cell tower database cached on the iPhone
  2. cease backing up this cache
  3. delete this cache entirely when Location Services is turned off

This update will land on handsets in the upcoming weeks. A future update will also encrypt this information and make it less readily available to spying eyes.

The ‘locationgate’ tempest blew up last week when a pair of researchers published a report that revealed Apple was storing months worth of location data on the iPhone and 3G iPad. This information was originally discovered last year and flew under the radar until the iPhone Tracker app let users see the stored location data.

This data moves from the phone to the user’s computer when the iOS device syncs via iTunes. The iPhone Tracker app grabs the data from the user’s computer and displays it in a map that was an eye-opener for most people.

This revelation spurned an angry letter from Minnesota senator Al Franken and at least one lawsuit.

Show full PR text
April 27, 2011 08:30 AM Eastern Daylight Time
Apple Q&A on Location Data

CUPERTINO, Calif.–(BUSINESS WIRE)–Apple would like to respond to the questions we have recently received about the gathering and use of location information by our devices.

1. Why is Apple tracking the location of my iPhone?
Apple is not tracking the location of your iPhone. Apple has never done so and has no plans to ever do so.

2. Then why is everyone so concerned about this?
Providing mobile users with fast and accurate location information while preserving their security and privacy has raised some very complex technical issues which are hard to communicate in a soundbite. Users are confused, partly because the creators of this new technology (including Apple) have not provided enough education about these issues to date.

3. Why is my iPhone logging my location?
The iPhone is not logging your location. Rather, it’s maintaining a database of Wi-Fi hotspots and cell towers around your current location, some of which may be located more than one hundred miles away from your iPhone, to help your iPhone rapidly and accurately calculate its location when requested. Calculating a phone’s location using just GPS satellite data can take up to several minutes. iPhone can reduce this time to just a few seconds by using Wi-Fi hotspot and cell tower data to quickly find GPS satellites, and even triangulate its location using just Wi-Fi hotspot and cell tower data when GPS is not available (such as indoors or in basements). These calculations are performed live on the iPhone using a crowd-sourced database of Wi-Fi hotspot and cell tower data that is generated by tens of millions of iPhones sending the geo-tagged locations of nearby Wi-Fi hotspots and cell towers in an anonymous and encrypted form to Apple.

4. Is this crowd-sourced database stored on the iPhone?
The entire crowd-sourced database is too big to store on an iPhone, so we download an appropriate subset (cache) onto each iPhone. This cache is protected but not encrypted, and is backed up in iTunes whenever you back up your iPhone. The backup is encrypted or not, depending on the user settings in iTunes. The location data that researchers are seeing on the iPhone is not the past or present location of the iPhone, but rather the locations of Wi-Fi hotspots and cell towers surrounding the iPhone’s location, which can be more than one hundred miles away from the iPhone. We plan to cease backing up this cache in a software update coming soon (see Software Update section below).

5. Can Apple locate me based on my geo-tagged Wi-Fi hotspot and cell tower data?
No. This data is sent to Apple in an anonymous and encrypted form. Apple cannot identify the source of this data.

6. People have identified up to a year’s worth of location data being stored on the iPhone. Why does my iPhone need so much data in order to assist it in finding my location today?
This data is not the iPhone’s location data-it is a subset (cache) of the crowd-sourced Wi-Fi hotspot and cell tower database which is downloaded from Apple into the iPhone to assist the iPhone in rapidly and accurately calculating location. The reason the iPhone stores so much data is a bug we uncovered and plan to fix shortly (see Software Update section below). We don’t think the iPhone needs to store more than seven days of this data.

7. When I turn off Location Services, why does my iPhone sometimes continue updating its Wi-Fi and cell tower data from Apple’s crowd-sourced database?
It shouldn’t. This is a bug, which we plan to fix shortly (see Software Update section below).

8. What other location data is Apple collecting from the iPhone besides crowd-sourced Wi-Fi hotspot and cell tower data?
Apple is now collecting anonymous traffic data to build a crowd-sourced traffic database with the goal of providing iPhone users an improved traffic service in the next couple of years.

9. Does Apple currently provide any data collected from iPhones to third parties?
We provide anonymous crash logs from users that have opted in to third-party developers to help them debug their apps. Our iAds advertising system can use location as a factor in targeting ads. Location is not shared with any third party or ad unless the user explicitly approves giving the current location to the current ad (for example, to request the ad locate the Target store nearest them).

10. Does Apple believe that personal information security and privacy are important?
Yes, we strongly do. For example, iPhone was the first to ask users to give their permission for each and every app that wanted to use location. Apple will continue to be one of the leaders in strengthening personal information security and privacy.

Software Update

Sometime in the next few weeks Apple will release a free iOS software update that:

reduces the size of the crowd-sourced Wi-Fi hotspot and cell tower database cached on the iPhone,
ceases backing up this cache, and
deletes this cache entirely when Location Services is turned off.
In the next major iOS software release the cache will also be encrypted on the iPhone.

NOTE TO EDITORS: For additional information visit Apple’s PR website (www.apple.com/pr), or call Apple’s Media Helpline at (408) 974-2042.

(C) 2011 Apple Inc. All rights reserved. Apple, the Apple logo, Mac, Mac OS, Macintosh, iPhone and iTunes are trademarks of Apple. Other company and product names may be trademarks of their respective owners.

Apple responds to location tracking controversy originally appeared on TUAW on Wed, 27 Apr 2011 09:06:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

White iPhone to arrive tomorrow (4/28) says Apple

Apple has announced that the white iPhone 4 will be available tomorrow, April 28th. You’ll be able to find it at Apple’s online store, Apple retail stores, AT&T and Verizon Wireless stores and some Apple Authorized Resellers (call to confirm). The white iPhone will go on sale in 28 countries tomorrow, including Austria, Australia, Belgium, Canada, China, Czech Republic, Denmark, Finland, France, Germany, Hong Kong, the U.S. and the UK.

“The white iPhone 4 has finally arrived and it’s beautiful,” said Apple’s Phil Schiller. “We appreciate everyone who has waited patiently while we’ve worked to get every detail right.”

As of this writing, the white iPhone has commandeered Apple’s homepage.

At last, the wait is over! Rumors suggested we’d see it this week, and here it is. If you pick up one of the snowy beauties tomorrow, please share your photos and stories. We’d love to hear all about it.

White iPhone to arrive tomorrow (4/28) says Apple originally appeared on TUAW on Wed, 27 Apr 2011 08:51:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

TUAW’s Daily App: Third Blade

Com2Us is a Korean publisher that’s produced some quality iPhone titles, and its latest release, Third Blade, keeps that trend going. Unfortunately, there’s not a lot of original iPhone gameplay here (it’s a traditional beat-em-up, though there are some nice RPG elements as you go), but while the actual game style is pretty well traveled, the action is well-done anyway. With an on-screen analog control and three different blade types that you can use to hack and slash through the well-rendered enemies, there’s plenty of fun to be had, especially if you’re up for a relatively hardcore action experience.

Each of the three blades that you can use (a faster dual wield, a stronger one-hand sword and a huge, but slow, two-hand “buster sword”) also levels up, and as the game goes along, there are also abilities to uncover and use against the enemies you meet. The enemies themselves are kind of repetitive (though I find most action games repetitive in this way — it’s more about the moves you can pull off rather than the variety of bad guys you come across, I think), but the graphics look great, and the hack-and-slash action is satisfying.

There are a few modes to play with, Game Center is integrated, and Com2Us says that more content will be available in the app soon. Third Blade is a more hardcore experience than your standard casual iOS action game, but for those looking for a little bit tougher action experience, it’s worth the US$2.99 to download and play.

TUAW’s Daily App: Third Blade originally appeared on TUAW on Wed, 27 Apr 2011 08:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

iPhone 101: Location data and GPS

gps data in a photoUpdate: Look here for official word on the iPhone location data controversy from Apple.

Recently, the Apple community has become interested in location data as gathered by iPhones. Specifically, The Guardian has reported that researcher and former Apple employee Pete Wardensome and data visualization scientist Alasdair Allan believe that your iPhone’s travel history is backed up to a file on your Mac, eliciting questions and concerns about iOS location services.

With that in mind, TUAW offers this brief primer so that you can better understand what’s going on under the hood of your iOS device when it comes to location matters.

What are location services and how do they work?

Location services allow certain apps to determine your iPhone’s approximate location and make use of that information. This is done through a combination of cellular network triangulation, Wi-Fi triangulation and the Global Positioning System, or GPS.

Here’s how it works. Your iPhone will first attempt to communicate with GPS satellites to determine its approximate location. This is a series of medium Earth orbit satellites deployed by the US Department of Defense several years ago. For a more in-depth explanation, look here.

When a solid GPS connection is unavailable (the iPhone is indoors, amid many tall trees outside, etc.), the iPhone tries Wi-Fi triangulation. As our own Auntie TUAW recently explained, this works because Wi-Fi hotspots rarely move. Apple has amassed a database of known hotspots and, when your iPhone is connected to one of those, can use them to determine an iPhone’s approximate place on the Earth. Of course, this method is less accurate than GPS.

Finally, determining location via cellular towers works in a similar fashion. Nearly every cell tower is built in a known, constant location (except for COWs). These fixed positions allow your iPhone to determine an approximate location by triangulating its distance from the nearest towers. Cell towers are less accurate because there are fewer of them than there are Wi-Fi hot spots. Therefore, you’re dealing with larger distances.

The first time an app tries to access location data, it asks for permission. A dialog box asks to use your current location. If you’re OK with that, tap Allow. Otherwise, tapping Don’t Allow prevents the app from accessing your location data until you turn it back on as described below.

Continue reading iPhone 101: Location data and GPS

iPhone 101: Location data and GPS originally appeared on TUAW on Wed, 27 Apr 2011 07:00:00 EST. Please see our terms for use of feeds.

Source | Permalink | Email this | Comments

Android App Development:Building Android Content Providers

In this tutorial I will cover building Android content providers. Content providers are the way that Android applications can share info between each other. an application can ask for info from another application using content providers.

In this post we’re going to create a content provider to access data from our previous Employees simple application from the SQLite post.

To remind you the database has two tables Employees and Dept:

Remember that any content provider must provide the following:

  1. A URi from which we can run queries.
  2. MIME type corresponding to the content.
  3. Insert() method.
  4. Update() methd.
  5. Delete() method.

Creating the content type:

First we will create a new class, I will call it EmployeesContentProvider and choose its super class to be ContentProvider. the class initially will be like this:

package mina.android.DatabaseDemo;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class EmployeesContentProvider extends ContentProvider {
DatabaseHelper db;
public static final Uri CONTENT_URI=Uri.parse("content://employees");
 @Override
 public int delete(Uri arg0, String arg1, String[] arg2) {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public String getType(Uri uri) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public Uri insert(Uri uri, ContentValues values) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public boolean onCreate() {
  // TODO Auto-generated method stub
  return false;
 }

 @Override
 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sortOrder) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  // TODO Auto-generated method stub
  return 0;
 }

}

We added a member of type DatabaseHelper db to hold a reference to our database.

Also we added a static URi object that represents the URi of our content provider.

It has all the abstract methods implementations of the ContentProvider class. so let’s check each method

onCreate() method:

The onCreate() method is the first method invoked when the content provider is created (similar to the Activity’s onCreate() method). here you can load your database or check for files you may read/write to them.

The method return a Boolean. it should be true if everything is ok, otherwise it should be false.

In our case we will just reference our SQLite database:

@Override
 public boolean onCreate() {
  // TODO Auto-generated method stub
  db=new DatabaseHelper(this.getContext());
  if(db==null)
   return false;
  else
   return true;
 }

query() method:

the query() method is the method that gets invoked when a content provider data is requested by a URi.

First let’s talk a little about content providers URI.

The content provider URi has the following format:

content://Authority/[(n) path]/[instance indentifier]

explanation:

  • The URI starts with content:// scheme.
  • The authority is a unique identifier for the content provider.
  • The authority can be followed by one or more paths (optional) refer to data paths within the content.
  • There can be an instance identifier that refers to a specific data instance.

For example we can have a URi like this:

content://Employees/Marketing//11.
this URi has Employees as the authority, Marketing as a data path and 11 as an instance (employee) identifier.

Back to our query method, we have the following parameters:

  1. Uri: the URi requested.
  2. String [] projection: representing the columns (projection) to be retrieved.
  3. String[] selection: the columns to be included in the WHERE clause.
  4. String[] selectionArgs: the values of the selection columns.
  5. String sortOrder: the ORDER BY statement.

the first step in our query method is to parse the client URi.
we expect the URi to be in one of the following forms:

  1. content://employees/: retrieves all employees.
  2. content://employees/id: retrieves a certain employee by ID.
  3. content://employess/IT: retreives employees of IT Dept.
  4. content://employess/HR: retrieves employees of HR Dept.
  5. content://employees/Sales: retreives employees of sales Dept.

So we will add some constatnt values to our class to refer to the above URis:

//authority and paths
 public static final String AUTHORITY="employees";
 public static final String ITPATH="IT";
 public static final String HRPATH="HR";
 public static final String SALESPATH="Sales";

 //URiMatcher to match client URis
 public static final int ALLEMPLOYEES=1;
 public static final int SINGLEEMPLOYEE=2;
 public static final int IT=3;
 public static final int HR=4;
 public static final int SALES=5;

Then we’re going to define a URiMatcher object that matches the client URI

static final UriMatcher matcher=new UriMatcher(UriMatcher.NO_MATCH);
 static{
  matcher.addURI(AUTHORITY,null,ALLEMPLOYEES);
  matcher.addURI(AUTHORITY, ITPATH, IT);
  matcher.addURI(AUTHORITY, HRPATH, HR);
  matcher.addURI(AUTHORITY, SALESPATH, SALES);
  //you can use '*' as a wild card for any text
  matcher.addURI(AUTHORITY, "#", SINGLEEMPLOYEE);
 }

The static initializer block loads the URimatcher objects with the values to match when the class initializes.

So let’s write our query method:

@Override
 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sortOrder) {
  SQLiteQueryBuilder builder=new SQLiteQueryBuilder();

  builder.setTables(DatabaseHelper.viewEmps);

  String order=null;
  Cursor result=null;
  if(sortOrder!=null)
   order=sortOrder;
  int match=matcher.match(uri);
  switch(match)
  {
  case ALLEMPLOYEES:
   //content://employees//id
   result=builder.query(db.getWritableDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
   break;
  case SINGLEEMPLOYEE:
   //content://employees//id
   Listsegments=uri.getPathSegments();
   String empID=segments.get(0);
   result=db.getEmpByID(empID);

   break;
  case IT:
   //content://employees//IT
   result=db.getEmpByDept("IT");
   result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"IT"}, null, null, sortOrder);
   break;
  case HR:
   //content://employees//HR
   result=db.getEmpByDept("HR");
   result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"HR"}, null, null, sortOrder);
   break;
  case SALES:
   //content://employees//Sales
   result=db.getEmpByDept("Sales");
   result=builder.query(db.getReadableDatabase(), projection, db.colDeptName+"=?", new String[]{"Sales"}, null, null, sortOrder);

   break;

  }

  return result;
 }

the function just parses the URi and returns the data in a cursor.

Insert() method:

the insert methods inserts a new record to the db;
the insert method has the following form:

public Uri insert(Uri uri, ContentValues values) {

  return null;
 }

The method has two parameters:

  1. URi uri: the URi of the content provider, we need to check it’s correct.
  2. ContentValues values: object holding the info of the new item to be inserted.

The method returns the URi of the newly inserted item to be used for further manipulations.
so here’s the implentation:

@Override
 public Uri insert(Uri uri, ContentValues values) {
  int match=matcher.match(uri);
  //not the Uri we're expecting
  long newID=0;
  if(match!=1)
   throw new IllegalArgumentException("Wrong URi "+uri.toString());
  if(values!=null)
  {
   newID=db.getWritableDatabase().insert(DatabaseHelper.employeeTable, DatabaseHelper.colName, values);
   return Uri.withAppendedPath(uri, String.valueOf(newID));

  }
  else
   return null;
 }

We first check the Uri if it is not correct, throw an exception.
then check the content values object, if null return null otherwise insert the new item and return the URi with the id of the new item.

The Update() method:

The update method updates existing record(s) and returns the number of updated rows.

A trick rises from the fact that you need to specify whether to update a collection of records or a single record, based on the URi.

The method has the following parameters:

  1. URi uri: the URi of the content provider, we need to check it’s correct.
  2. ContentValues values: object holding the info of the new item to be inserted.
  3. String Selection : the filter to match the rows to update
  4. String [] selectionArgs : the values of the filter parameters

Here’s the implementation of the update method:

@Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  int match=matcher.match(uri);
  //not the Uri we're expecting
  int rows=0;
  //update single instance
  if(match==2)
  {
   if(values!=null)
   {
    Listsegments=uri.getPathSegments();
    String empID=segments.get(0);
    rows=db.getWritableDatabase().update(DatabaseHelper.employeeTable, values,DatabaseHelper.colID+"=?", new String []{empID});

   }

  }
  //update all emps in a certain dept
  else if(match==3 ||match==4||match==5)
  {
   Listsegments=uri.getPathSegments();
   String deptName=segments.get(0);
   int DeptID=db.GetDeptID(deptName);
   rows=db.getWritableDatabase().update(db.employeeTable, values,db.colDept+"=?", new String []{String.valueOf(DeptID)});

  }
   return rows;
 }

The Delete() method:

The delete method has the following parameters:

  1. Uri uri: the URi of the content provider.
  2. String Condition: the condition of the delete statement.
  3. String[] args: the delete condition arguments

So here’s the implementation:

@Override
 public int delete(Uri uri, String where, String[] args) {

  int match=matcher.match(uri);
  //expecting the URi to be in the form of
  if(match==1)
  {
   SQLiteDatabase dataBase=db.getWritableDatabase();
   return dataBase.delete(db.employeeTable, where, args);
  }
  else
  return 0;
 }

We just check for the URi and perform a delete command.

The getType() method:

The last mthod to implement is getType() method which returns the

MIME type associated with the URi passed to it.

If the URi is of a group of employees, then the MIME type is a collection type, otherwise it’s of an instance type

@Override
 public String getType(Uri uri) {
  int match=matcher.match(uri);
  // single employee
  if(match==2)
  {
   return "mina.android.Employee";
  }
  //collection of employees
  else
  {
   return "mina.android.Employees";
  }
 }

Modifying the Manifest.xml file:

The last thing we need to do is to add an entry in our application’s manifest.xml file to register our class as a content provider class.
So add this entry just below the <application>

<provider android:name="mina.android.DatabaseDemo.EmployeesContentProvider"
    android:authorities="employees"/>

When an application requests data through our content provider, Android system will search all the manifest files of all aplications on the device and when it finds such an entry, it will process the request.

Testing the content provider:

Now suppose you are in another activity and you want to use our activity.
Testing queries:
To make a query to retrieve all employees:

Uri empsUri=Uri.parse("content://employees");
Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);

The cursor should have all the records.

To retrieve a certain employee by ID or all employees in a certain department:

Uri empUri=Uri.parse("content://employees//5");
Uri empDeptUri=Uri.parse("content://employees//Sales");

Inserting:

Uri empsUri=Uri.parse("content://employees");
ContentValues cvs=new ContentValues();
        cvs.put("EmployeeName", "Mark Anderson");
        cvs.put("Age", 35);
        cvs.put("Dept", 1);
        // URi of the new inserted item
        Uri newEmp=getContentResolver().insert(empsUri, cvs);

Updating:
To update a single employee:

//Uri with the id of the employee
Uri empsUri=Uri.parse("content://employees/8");

        Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
        txt.setText(String.valueOf(cursor.getCount()));

        ContentValues cvs=new ContentValues();
        cvs.put("EmployeeName", "Mina Samy mod");
        cvs.put("Age", 35);
        cvs.put("Dept", 1);
// number of rows modified
int rowsNumber=getContentResolver().update(empsUri, cvs, "EmployeeID=?", new String[]{"8"});

To update all employees in a certain department

Uri empsUri=Uri.parse("content://employees/Sales");

        Cursor cursor=getContentResolver().query(empsUri, null, null, null, null);
        txt.setText(String.valueOf(cursor.getCount()));

        ContentValues cvs=new ContentValues();
        cvs.put("EmployeeName", "mod");
        cvs.put("Age", 35);
        cvs.put("Dept", 1);
        int rowsNumber=getContentResolver().update(empsUri, cvs, "colDept=?", new String[]{"1"});

As a matter of fact, in both cases we don’t need to specify the wher clause and the where parameters as they are implicitly specified in the URi. so we just can replace the update statement to be like this:

int rowsNumber=getContentResolver().update(empsUri, cvs, null,null);

Deleting:
I left the delete operation open to any criteria, you can delete a single employee or employees of a certain department or even all employees

Uri empsUri=Uri.parse("content://employees");
// delete employee of id 8
int rowsNumber=getContentResolver().delete(empsUri,"EmployeeID=?",new String[]{"8"});

Final Word:

Creating a content provider for a certain type of data can be done in many ways, this example can be implemented in several variations.

Another thing is that you need to create a strongly typed class for you data model to be used by clients accessing your content. in this example when I tested the query i wrote the column names of the database as strings like this: “EmployeeID” and “EmployeeName”.
this is not ideal in a production release of an application. I should created a class library that holds all the info about the database to be used by other client applications.

Today you learned about creating content providers, stay tuned next week for another Android tutorial.