4. On create
import android.app.Activity;
public class MainActivity extends Activity{
TextView mTextView; // Member variable for text view in the layout
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the user interface layout for this Activity
// The layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
mTextView = (TextView) findViewById(R.id.text_message);
mTextView.setText(“Hello World”);
}
}
15. ListView (ArrayAdapter)
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
public class MainActivity extends Activity {
private ListView listView1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Weather weather_data[] = new Weather[]
{
new Weather(R.drawable.weather_cloudy, "Cloudy"),
new Weather(R.drawable.weather_showers, "Showers"),
new Weather(R.drawable.weather_snow, "Snow"),
new Weather(R.drawable.weather_storm, "Storm"),
new Weather(R.drawable.weather_sunny, "Sunny")
};
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row,
null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
}
public class Weather {
public int icon;
public String title;
public Weather(){
super();
}
public Weather(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}
16. Intent
Intents are used as a message-passing mechanism
that works both within your application and
between applications. You can use Intents to do
the following:
• Explicitly start a particular Service or Activity
using its class name
• Start an Activity or Service to perform an action
with (or on) a particular piece of data
• Broadcast that an event has occurred
17. Intent Examples
Explicitly Starting New Activities
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
Passing Parameter from one activity to another
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
data.putExtra("data", "test data");
startActivity(intent);
Retrieving data from previous activity
Bundle b = intent.getExtras();
String data = b.getString("data");
Selecting a Contact Example
public class ContactPickerTester extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactpickertester);
Button button = (Button)findViewById(R.id.pick_contact_button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));
startActivityForResult(intent, PICK_CONTACT);
}
});
}
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
super.onActivityResult(reqCode, resCode, data);
switch(reqCode) {
case (PICK_CONTACT) : {
if (resCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, null, null, null,
null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
c.close();
TextView tv =
(TextView)findViewById(R.id.selected_contact_textview);
tv.setText(name);
}
break;
}
default: break;
}
}
18. Fragment
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which
has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news. ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news. ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
19. Fragment
import android.support.v4.app.ListFragment; android.app.Fragment (for version 3.0+)
import android.support.v4.app.Fragment; android.app.ListFragment (for version 3.0)
public class ArticleListFragment extends ListFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int layout = android.R.layout.simple_list_item_1;
setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.ArticleList));
}
}
public class ArticleFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
return inflater.inflate(R.layout.article_view, container, false);
}
}
20. Action Bar (android 3.0+)
• Provide a dedicated space for identifying the application brand and user location.
• This is accomplished with the app icon or logo on the left side and the activity title. You might choose
to remove the activity title, however, if the current view is identified by a navigation label, such as the
currently selected tab.
• The action bar provides built-in tab navigation for switching between fragments. It also offers a drop-
down list you can use as an alternative navigation mode or to refine the current view (such as to sort a
list by different criteria).
• Make key actions for the activity (such as "search", "create", "share", etc.) prominent and accessible to
the user in a predictable way.
<manifest ... >
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="11" /> ActionBar actionBar = getActionBar();
actionBar.hide();
...
</manifest>
21. Action Bar and Fragments
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setDisplayOptions((int) Window.FEATURE_NO_TITLE);
Tab tab = getActionBar().newTab().setText("Category")
.setTabListener(new SurveyTabListener<CategoryFragment>(this, "", CategoryFragment.class));
Tab tab1 = getActionBar().newTab().setText("Create")
.setTabListener(new SurveyTabListener<CreatePollFragement>(this, "", CreatePollFragement.class));
Tab tab2 = getActionBar().newTab().setText("Results")
.setTabListener(new SurveyTabListener<MyPollFragement>(this, "", MyPollFragement.class));
public class SurveyTabListener<T extends Fragment> implements TabListener{
private Fragment mFragment;
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
public SurveyTabListener(FragmentActivity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ignoreft) {
FragmentManager fragMgr ((FragmentActivity)mActivity).getSupportFragmentManager();
FragmentTransaction ft = fragMgr.beginTransaction();
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
ft.commit();
}
public void onTabReselected(Tab tab, FragmentTransaction ignoreft) {}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
}
22. Service
Services are started, stopped, and controlled from other
application components, including Activities
public class MyService extends Service {
public void onCreate() {
super.onCreate();
}
public IBinder onBind(Intent intent) {
}
<service android:enabled="true" android:name=".MyService"/>
private void startService() {
Intent intent = new Intent(this, MyService.class
startService(intent);
}
23. AsyncTask
• The AsyncTask class implements a best practice pattern for moving your time-consuming operations onto
a background Thread and synchronizing with the UI Thread for updates and when the processing is
complete. It offers the convenience of event handlers synchronized with the GUI Thread to let you update
Views and other UI elements to report progress or publish results when your task is complete.
• AsyncTask handles all the Thread creation, management, and synchronization, enabling you to create an
asynchronous task consisting of processing to be done in the background and UI updates to be performed
both during the processing, and once it's complete.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
24. Android DB
public class DBTest {
private DatabaseHelper helper;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into insertTest (text) values (?)";
public DBTest(Context context){
helper = new DatabaseHelper(context);
db = helper.getWritableDatabase();
insertStmt = db.compileStatement(INSERT);
}
public void close(){ helper.close();}
public void insert(String test){
insertStmt.bindString(1, test);
insertStmt.executeInsert();
}
public Set<String> getText(){
Cursor cursor = db.query("upload", new String[] {“text"}, null, null, null, null, "path desc");
Set<String> texts = new HashSet<String>();
if (cursor != null && cursor.moveToFirst()){
do{
texts.add(cursor.getString(0));
}while(cursor.moveToNext());
}
return texts;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE insertTest (test TEXT)");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS insertTest");
onCreate(db);
}
}
25. SAVING SIMPLE APPLICATION DATA
The data-persistence techniques in Android provide options for balancing speed, efficiency, and
robustness.
Shared Preferences — When storing UI state, user preferences, or application settings, you
want a lightweight mechanism to store a known set of values. Shared Preferences let you
save groups of name/value pairs of primitive data as named preferences.
Saved application UI state — Activities and Fragments include specialized event handlers to
record the current UI state when your application is moved to the background.
Files — It's not pretty, but sometimes writing to and reading from files is the only way to go.
Android lets you create and load files on the device's internal or external media, providing
support for temporary caches and storing files in publicly accessible folders.
27. Saving and Restoring Activity Instance State Using the Lifecycle Handlers
private static final String TEXTVIEW_STATE_KEY = "TEXTVIEW_STATE_KEY";
public void onSaveInstanceState(Bundle saveInstanceState) {
TextView myTextView = (TextView)findViewById(R.id.myTextView);
saveInstanceState.putString(TEXTVIEW_STATE_KEY, myTextView.getText().toString());
super.onSaveInstanceState(saveInstanceState);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.myTextView);
String text = "";
if (savedInstanceState != null && savedInstanceState.containsKey(TEXTVIEW_STATE_KEY))
text = savedInstanceState.getString(TEXTVIEW_STATE_KEY);
myTextView.setText(text);
}
28. WORKING WITH THE FILE SYSTEM
Android offers the openFileInput and openFileOutput methods to simplify reading and writing streams from
and to files stored in the application's sandbox.
String FILE_NAME = "tempfile.tmp";
Create a new output file stream that's private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
FileInputStream fis = openFileInput(FILE_NAME);
Using the Application File Cache
Should your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level
8) an unmanaged external cache. You can access them by calling the getCacheDir and getExternalCacheDir methods,
respectively, from the current Context.
Storing Publicly Readable Files
• DIRECTORY_ALARMS — Audio files that should be available as user-selectable alarm sounds
• DIRECTORY_DCIM — Pictures and videos taken by the device
• DIRECTORY_DOWNLOADS — Files downloaded by the user
• DIRECTORY_MOVIES — Movies
• DIRECTORY_MUSIC — Audio files that represent music
• DIRECTORY_NOTIFICATIONS — Audio files that should be available as user-selectable notification sounds
• DIRECTORY_PICTURES — Pictures
• DIRECTORY_PODCASTS — Audio files that represent podcasts
• DIRECTORY_RINGTONES — Audio files that should be available as user-selectable ringtones
29. Android Networking and Mobile Cloud Service Provider
StackMob
https://www.stackmob.com/
kinvey
http://www.kinvey.com/
Appcelerator
http://www.appcelerator.com/
Kii
http://www.kii.com/en/technology
Stream SDK
http://streamsdk.com