SlideShare a Scribd company logo
Android Development
Overview
Android architecture
Android Application Lifecycle
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”);
}
}
AndroidManifest.xml
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Fundamental Android UI Design
Frame Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/ImageView01"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:src="@drawable/lake"
android:scaleType="matrix"></ImageView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="40dp"
android:text="@string/top_text" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/bottom_text"
android:layout_gravity="bottom"
android:gravity="right"
android:textColor="#fff"
android:textSize="50dp" />
</FrameLayout>
Liner Layout 1
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:orientation="vertical"
android:background="@drawable/blue"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:background="@drawable/box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/linear_layout_1_top"/>
<TextView
android:background="@drawable/box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/linear_layout_1_middle"/>
<TextView
android:background="@drawable/box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/linear_layout_1_bottom"/>
</LinearLayout>
Liner layout 2
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:background="@drawable/red"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:background="@drawable/green"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:background="@drawable/blue"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:background="@drawable/yellow"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"/>
</LinearLayout>
Liner Layout 3
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingRight="0dip"
android:background="@android:drawable/edit_text">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/linear_layout_10_from"
android:textColor="?android:attr/textColorSecondary"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:background="@null"
/>
<ImageButton
android:src="@android:drawable/star_big_on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
Relativity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/blue"
android:padding="10dip">
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/relative_layout_2_instructions"/>
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="@string/relative_layout_2_ok" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="@string/relative_layout_2_cancel" />
</RelativeLayout>
ListView
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/r
es/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
ListView
listview_header_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/
android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/txtHeader"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#FFFFFF"
android:padding="10dp"
android:text="Weather Photos"
android:background="#336699" />
</LinearLayout>
ListView
listview_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="@+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="@+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
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;
}
}
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
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;
}
}
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>
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);
}
}
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>
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) {}
}
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);
}
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");
}
}
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);
}
}
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.
CREATING AND SAVING SHARED PREFERENCES
SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS,
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("wholeNumber", 2);
editor.putLong("aNumber", 3l);
editor.putString("textEntryValue", "Not Empty");
editor.apply();
boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
long aNumber = mySharedPreferences.getLong("aNumber", 0);
String stringPreference = mySharedPreferences.getString("textEntryValue", "");
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);
}
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
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

More Related Content

Similar to Androidppt 1 (20)

PPTX
04 activities - Android
Wingston
 
PPT
Day 3: Getting Active Through Activities
Ahsanul Karim
 
PPT
Day 3: Getting Active Through Activities
Ahsanul Karim
 
PDF
Android UI Development: Tips, Tricks, and Techniques
Edgar Gonzalez
 
PDF
Android UI Tips, Tricks and Techniques
Marakana Inc.
 
PPT
MD-IV-CH-ppt.ppt
bharatt7
 
PPTX
Android apps development
Monir Zzaman
 
PDF
[PBO] Pertemuan 12 - Pemrograman Android
rizki adam kurniawan
 
PPT
Android | Busy Java Developers Guide to Android: UI | Ted Neward
JAX London
 
PDF
Hello android
vasily.romanikhin
 
PPTX
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
MugiiiReee
 
PPT
Android classes in mumbai
Vibrant Technologies & Computers
 
PPT
Android 2
San Bunna
 
PDF
Android Development
mclougm4
 
PPT
Android activity, service, and broadcast recievers
Utkarsh Mankad
 
KEY
Android Workshop
Junda Ong
 
PDF
Android tutorial
Abid Khan
 
PDF
Android activities & views
ma-polimi
 
PDF
Android application development workshop day1
Borhan Otour
 
DOCX
Activity
roopa_slide
 
04 activities - Android
Wingston
 
Day 3: Getting Active Through Activities
Ahsanul Karim
 
Day 3: Getting Active Through Activities
Ahsanul Karim
 
Android UI Development: Tips, Tricks, and Techniques
Edgar Gonzalez
 
Android UI Tips, Tricks and Techniques
Marakana Inc.
 
MD-IV-CH-ppt.ppt
bharatt7
 
Android apps development
Monir Zzaman
 
[PBO] Pertemuan 12 - Pemrograman Android
rizki adam kurniawan
 
Android | Busy Java Developers Guide to Android: UI | Ted Neward
JAX London
 
Hello android
vasily.romanikhin
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
MugiiiReee
 
Android classes in mumbai
Vibrant Technologies & Computers
 
Android 2
San Bunna
 
Android Development
mclougm4
 
Android activity, service, and broadcast recievers
Utkarsh Mankad
 
Android Workshop
Junda Ong
 
Android tutorial
Abid Khan
 
Android activities & views
ma-polimi
 
Android application development workshop day1
Borhan Otour
 
Activity
roopa_slide
 

Androidppt 1

  • 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”); } }
  • 5. AndroidManifest.xml <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  • 7. Frame Layout <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/an droid" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/ImageView01" android:layout_height="fill_parent" android:layout_width="fill_parent" android:src="@drawable/lake" android:scaleType="matrix"></ImageView> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#000" android:textSize="40dp" android:text="@string/top_text" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/bottom_text" android:layout_gravity="bottom" android:gravity="right" android:textColor="#fff" android:textSize="50dp" /> </FrameLayout>
  • 9. Liner layout 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:background="@drawable/red" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:background="@drawable/green" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:background="@drawable/blue" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:background="@drawable/yellow" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1"/> </LinearLayout>
  • 10. Liner Layout 3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:paddingRight="0dip" android:background="@android:drawable/edit_text"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/linear_layout_10_from" android:textColor="?android:attr/textColorSecondary" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:background="@null" /> <ImageButton android:src="@android:drawable/star_big_on" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>
  • 11. Relativity Layout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue" android:padding="10dip"> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/relative_layout_2_instructions"/> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:drawable/editbox_background" android:layout_below="@id/label"/> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/entry" android:layout_alignParentRight="true" android:layout_marginLeft="10dip" android:text="@string/relative_layout_2_ok" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@id/ok" android:text="@string/relative_layout_2_cancel" /> </RelativeLayout>
  • 13. ListView listview_header_row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/ android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/txtHeader" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:textStyle="bold" android:textSize="22dp" android:textColor="#FFFFFF" android:padding="10dp" android:text="Weather Photos" android:background="#336699" /> </LinearLayout>
  • 14. ListView listview_item_row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp"> <ImageView android:id="@+id/imgIcon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_marginRight="15dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" /> <TextView android:id="@+id/txtTitle" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:textStyle="bold" android:textSize="22dp" android:textColor="#000000" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" /> </LinearLayout>
  • 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.
  • 26. CREATING AND SAVING SHARED PREFERENCES SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("isTrue", true); editor.putFloat("lastFloat", 1f); editor.putInt("wholeNumber", 2); editor.putLong("aNumber", 3l); editor.putString("textEntryValue", "Not Empty"); editor.apply(); boolean isTrue = mySharedPreferences.getBoolean("isTrue", false); float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f); int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1); long aNumber = mySharedPreferences.getLong("aNumber", 0); String stringPreference = mySharedPreferences.getString("textEntryValue", "");
  • 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