package com.example.hello.android.account_manager_get;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity
{

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

		AccountListAdapter listAdapter = new AccountListAdapter();
		setListAdapter(listAdapter);
	}

	class AccountListAdapter extends BaseAdapter
	{

		private Account[] accounts;
		private LayoutInflater inflater;

		public AccountListAdapter()
		{
			inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		}

		private Account[] getAccounts()
		{
			if (accounts == null)
			{
				AccountManager accountManager = AccountManager.get(MainActivity.this);
				accounts = accountManager.getAccounts();
			}
			return accounts;
		}

		public int getCount()
		{
			return getAccounts().length;
		}

		public Object getItem(int i)
		{
			Object result = null;
			if (i >= 0 && i < getCount())
			{
				result = getAccounts()[i];
			}
			return result;
		}

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

		public View getView(int i, View view, ViewGroup vg)
		{

			View itemView;

			if (view == null)
			{
				itemView = inflater.inflate(R.layout.account_list_item, null);
			}
			else
			{
				itemView = view;
			}

			// bind name
			Account account = (Account) getItem(i);
			TextView accountNameTextView = (TextView) itemView.findViewById(R.id.account_name_text);
			accountNameTextView.setText(account.name);

			// bind type
			TextView accountTypeTextView = (TextView) itemView.findViewById(R.id.account_type_text);
			accountTypeTextView.setText(account.type);

			return itemView;
		}
	}
}
