Showing posts with label apps. Show all posts
Showing posts with label apps. Show all posts

23 December 2013

Android show contact email addresses

So this is something in Android I thought would be really simple but quite frankly, wasn't. I want to get a list of all email addresses in my phone and display them in a list. If one is to use ContactsContract.CommonDataKinds.Email.CONTENT_URI without filter you basically get every email address you've ever emailed. Not ideal. I am (in this case) looking for only our saved Google contacts. We can do this query in the UI thread, which works fine but if you have several hundred contacts that'll kill the app. So we're going to use LoaderManager. First we setup out fragment:

public class FragmentMain extends Fragment implements LoaderManager.LoaderCallbacks{

 ArrayList mFriends = new ArrayList();

...
}

Now we need to setup our createLoader method to get the data and onLoadFinished to put the data into the UI. The selection here is very important as it limits the query to the visible contacts: String my_selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";.
Next step is very simple, in the onLoadFinished we loop through the available data, adding each email address to an ArrayList.


 @Override
 public Loader onCreateLoader(int arg0, Bundle arg1) {
  //Sort by email address no case
  final String my_sort_order = ContactsContract.CommonDataKinds.Email.DATA + " COLLATE NOCASE ASC";
  String my_selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
  String[] eproj = new String[]{
   ContactsContract.Contacts._ID,
   ContactsContract.CommonDataKinds.Email.DATA};
  Uri uri = android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI;
  //Query all emails in contacts
  return new CursorLoader(getActivity(), uri, eproj, my_selection, null, my_sort_order);
 }

 @Override
 public void onLoadFinished(Loader arg0, Cursor data) {
  
  if (data != null && data.moveToFirst()) {
   //Loop through cursor
   while (!data.isAfterLast()) {
    //get Email address
    String myemail = data.getString(data.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
    if(!mFriends.contains(myemail)){
     //Add email to arrayList
     mFriends.add(myemail);
    }
    
    data.moveToNext();
   }
  }
  //load friends into ui
  loadFriends();
 }

 @Override
 public void onLoaderReset(Loader arg0) {
  //Not Used
 }

Last but not least we load the data into our listview. Now you can of course, should you desire, create a custom Adapter and implement your own item view, but that's a blog post for another day.


 private void loadFriends(){
  //load arraylist into adapter.
  ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, mFriends);
  mFriendsList.setAdapter(adapter);
 }

Oh and one more thing, don't forget your permissions :)
<uses-permission android:name="android.permission.READ_CONTACTS" />

24 July 2013

Google Play Game Services


I've previously created my own custom built high scores add on for my Android app, frankly it was pretty rubbish. It was local only, not very pretty and had no public competition element. There are a few third party apps but they cost money. That is until at Google IO Google announced Google Play Game Services. I thought I'd take a look and I was incredibly impressed.

http://developer.android.com/google/play-services/games.html

Game Services allows you to instantly integrate a leaderboard into your app. It does this using Google + which means your users can share their scores with their circles, specific friends or of course with the public. I love this because just thinking about creating a user id for every user and a server side backend to deal with all that makes me shudder. Plus you can add in achievements which is pretty cool too.

So if you want to get started adding play services I very much recommend downloading Google's sample app "Type-a-Number":

https://developers.google.com/games/services/android/quickstart

Then run through the steps to get the API set-up on Google's developer console and of course provides a sample app and code to study. I really recommend you study this and get a good grasp on how it all works. I'm not going to run through all the code here, as Google have already done that. The same applies to the API, you do need to do a bit of setup on Google's developer console. Just make sure you copy the IDs of your game service and your leaderboard into your android project. Preferably in the same way Google suggest with an ids.xml file.

You're going to need to set-up eclipse and your project with Google Play Services Library which I already had for Google Maps anyway. The sample app uses the Base Game Utils library, which isn't totally necessary, but it does make things a little simpler. Again, all steps are covered in the quickstart.

The first thing is to get the Google Plus button working. This is a simple case of adding in the com.google.android.gms.common.SignInButton button to your layout file.
Then add a listener:

//Listener for Sign in
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        beginUserInitiatedSignIn();
    }
});

Now beginUserInitiatedSignIn() is a function in Base Game Utils which deals with the Google + magic. It does have a callback function though which you can utilise, here's mine:

@Override
public void onSignInSucceeded() {
    Toast.makeText(this, "Signed in", Toast.LENGTH_SHORT).show();
    
    mShowSignIn = false;
    updateUi();

}

UpdateUi() handles hiding the sign in button and showing the sign out button.

Last but not least we need to push our scores.

getGamesClient().submitScore(getString(R.string.leaderboard_highscores),intScore);

It's spectacularly easy to do.

There are however a few things I've learnt:
  1. Be very wary of your certificate. You'll need to make sure the SHA1 hash you use is the same you export your Android project as the one you enter on the game services API.
  2. When you come to release this, if you've been using your debug certificate you'll need to delete your game services on the API and start it all over again. I've tried many times to tweak the SHA1 in an active game service but it always breaks. So best to start fresh with a production ready certificate and use it for the API as well.
  3. The IDs you get from play services must be copied exactly to your ids.xml file and your manifest must have a line like this:
    <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />

  4. If you want to delete your scores or change the IDs you use for the game services or leaderboard you need to goto:
    Settings -> Google -> Google + -> Apps With Google + Sign In -> xx_AppName_xx -> Disconnect App
    You'll get the option here to delete your scores. This can be a bit temperamental, so change IDs only if you're really stuck.

One last thing worth mentioning, and its addressed to Google, whom I'm sure study my blog every day! When one looks at the achievements board, you can't expand the achievement to get the full description of what is required. On a phone, this means you'll never know what's required.

Thanks and good luck.