Android Tutorial - UI Activity

Backup Activity

     
package app.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

 class BackupTask extends AsyncTask<String,Void,Integer> {
    
    public interface CompletionListener {
        void onBackupComplete();
        void onRestoreComplete();
        void onError(int errorCode);
    }
    
    public static final int BACKUP_SUCCESS = 1;
    public static final int RESTORE_SUCCESS = 2;
    public static final int BACKUP_ERROR = 3;
    public static final int RESTORE_NOFILEERROR = 4;
    
    public static final String COMMAND_BACKUP = "backupDatabase";
    public static final String COMMAND_RESTORE = "restoreDatabase";
    
    private Context mContext;
    private CompletionListener listener;
    
    public BackupTask(Context context) {
        super();
        mContext = context;
    }
    
    public void setCompletionListener(CompletionListener aListener) {
        listener = aListener;
    }
    
    @Override
    protected Integer doInBackground(String... params) {
        File dbFile = mContext.getDatabasePath("mydb");
        File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        String command = params[0];
        if(command.equals(COMMAND_BACKUP)) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return BACKUP_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else if(command.equals(COMMAND_RESTORE)) {
            try {
                if(!backup.exists()) {
                    return RESTORE_NOFILEERROR;
                }
                dbFile.createNewFile();
                fileCopy(backup, dbFile);
                return RESTORE_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else {
            return BACKUP_ERROR;
        }
    }
    
    @Override
    protected void onPostExecute(Integer result) {

        switch(result) {
        case BACKUP_SUCCESS:
            if(listener != null) {
                listener.onBackupComplete();
            }
            break;
        case RESTORE_SUCCESS:
            if(listener != null) {
                listener.onRestoreComplete();
            }
            break;
        case RESTORE_NOFILEERROR:
            if(listener != null) {
                listener.onError(RESTORE_NOFILEERROR);
            }
            break;
        default:
            if(listener != null) {
                listener.onError(BACKUP_ERROR);
            }
        }
    }
    
    private void fileCopy(File source, File dest) throws IOException {
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(dest).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
}

public class Test extends Activity implements BackupTask.CompletionListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        SQLiteDatabase db = openOrCreateDatabase("mydb", Activity.MODE_PRIVATE, null);
        db.close();
    }
    
    @Override
    public void onResume() {
        super.onResume();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.setCompletionListener(this);
            task.execute(BackupTask.COMMAND_RESTORE);
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
            BackupTask task = new BackupTask(this);
            task.execute(BackupTask.COMMAND_BACKUP);
        }
    }

    @Override
    public void onBackupComplete() {
        Toast.makeText(this, "Backup Successful", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(int errorCode) {
        if(errorCode == BackupTask.RESTORE_NOFILEERROR) {
            Toast.makeText(this, "No Backup to Restore", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Error: "+errorCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRestoreComplete() {
        Toast.makeText(this, "Restore Successful", Toast.LENGTH_SHORT).show();
    }
}

Notification Activity

     
package app.test;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Test extends Activity implements View.OnClickListener {
 
    private static final int NOTE_ID = 100;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setText("Post New Notification");
        button.setOnClickListener(this);
        setContentView(button);
    }
    @Override
    public void onClick(View v) {
        handler.postDelayed(task, 10000);
        Toast.makeText(this, "Notification will post in 10 seconds", Toast.LENGTH_SHORT).show();
    }
    
    private Handler handler = new Handler();
    private Runnable task = new Runnable() {
        @Override
        public void run() {
            NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            Intent launchIntent = new Intent(getApplicationContext(), Test.class);
            PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
            
            Notification note = new Notification(R.drawable.icon, "Something Happened", System.currentTimeMillis());
            note.setLatestEventInfo(getApplicationContext(), "Finished!", "Click Here!", contentIntent);
            note.defaults |= Notification.DEFAULT_SOUND;
            note.flags |= Notification.FLAG_AUTO_CANCEL;
            
            manager.notify(NOTE_ID, note);
        }
    };
}

Timing Activity

     
package app.test;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;

public class Test extends Activity {
    
    TextView mClock;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClock = new TextView(this);
        setContentView(mClock);
    }
    
    private Handler mHandler = new Handler();
    private Runnable timerTask = new Runnable() {
        @Override
        public void run() {
            Calendar now = Calendar.getInstance();
            mClock.setText(String.format("%02d:%02d:%02d",
                    now.get(Calendar.HOUR),
                    now.get(Calendar.MINUTE),
                    now.get(Calendar.SECOND)) );
            mHandler.postDelayed(timerTask,1000);
        }
    };
    
    @Override
    public void onResume() {
        super.onResume();
        mHandler.post(timerTask);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(timerTask);
    }
}

Set content view from xml for Activity

     
package app.Test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

public class appTest extends Activity {
  private EditText urlText;
  private Button goButton;

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

    // Get a handle to all user interface elements
    urlText = (EditText) findViewById(R.id.url_field);
    goButton = (Button) findViewById(R.id.go_button);

    // Setup event handlers
    goButton.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        openBrowser();
      }
    });
    urlText.setOnKeyListener(new OnKeyListener() {
      public boolean onKey(View view, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
          openBrowser();
          return true;
        }
        return false;
      }
    });
  }

  /** Open a browser on the URL specified in the text box */
  private void openBrowser() {
    Uri uri = Uri.parse(urlText.getText().toString());
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
  }

}

// main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <EditText
         android:id="@+id/url_field"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="1.0"
         android:lines="1" />
      <Button
         android:id="@+id/go_button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@string/go_button" />
   </LinearLayout>
   <WebView
      android:id="@+id/web_view"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1.0" />
</LinearLayout>

More than one Activity

     


package apt.tutorial;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

public class DetailForm extends Activity {
  EditText name=null;
  EditText address=null;
  EditText notes=null;
  RadioGroup types=null;
  RestaurantHelper helper=null;
  String restaurantId=null;

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

    helper=new RestaurantHelper(this);
    
    name=(EditText)findViewById(R.id.name);
    address=(EditText)findViewById(R.id.addr);
    notes=(EditText)findViewById(R.id.notes);
    types=(RadioGroup)findViewById(R.id.types);
    
    Button save=(Button)findViewById(R.id.save);
    
    save.setOnClickListener(onSave);
    
    restaurantId=getIntent().getStringExtra(LunchList.ID_EXTRA);
    
    if (restaurantId!=null) {
      load();
    }
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
  
    helper.close();
  }
  
  private void load() {
    Cursor c=helper.getById(restaurantId);

    c.moveToFirst();    
    name.setText(helper.getName(c));
    address.setText(helper.getAddress(c));
    notes.setText(helper.getNotes(c));
    
    if (helper.getType(c).equals("sit_down")) {
      types.check(R.id.sit_down);
    }
    else if (helper.getType(c).equals("take_out")) {
      types.check(R.id.take_out);
    }
    else {
      types.check(R.id.delivery);
    }
    
    c.close();
  }
  
  private View.OnClickListener onSave=new View.OnClickListener() {
    public void onClick(View v) {
      String type=null;
      
      switch (types.getCheckedRadioButtonId()) {
        case R.id.sit_down:
          type="sit_down";
          break;
        case R.id.take_out:
          type="take_out";
          break;
        case R.id.delivery:
          type="delivery";
          break;
      }

      if (restaurantId==null) {
        helper.insert(name.getText().toString(),
                      address.getText().toString(), type,
                      notes.getText().toString());
      }
      else {
        helper.update(restaurantId, name.getText().toString(),
                      address.getText().toString(), type,
                      notes.getText().toString());
      }
      
      finish();
    }
  };
}



//12-Activities\LunchList\src\apt\tutorial\LunchList.java
package apt.tutorial;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class LunchList extends ListActivity {
  public final static String ID_EXTRA="apt.tutorial._ID";
  Cursor model=null;
  RestaurantAdapter adapter=null;
  RestaurantHelper helper=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    helper=new RestaurantHelper(this);
    model=helper.getAll();
    startManagingCursor(model);
    adapter=new RestaurantAdapter(model);
    setListAdapter(adapter);
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
    
    helper.close();
  }
  
  @Override
  public void onListItemClick(ListView list, View view,
                              int position, long id) {
    Intent i=new Intent(LunchList.this, DetailForm.class);

    i.putExtra(ID_EXTRA, String.valueOf(id));
    startActivity(i);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.option, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.add) {
      startActivity(new Intent(LunchList.this, DetailForm.class));
      
      return(true);
    }
    
    return(super.onOptionsItemSelected(item));
  }
  
  class RestaurantAdapter extends CursorAdapter {
    RestaurantAdapter(Cursor c) {
      super(LunchList.this, c);
    }
    
    @Override
    public void bindView(View row, Context ctxt,
                         Cursor c) {
      RestaurantHolder holder=(RestaurantHolder)row.getTag();
      
      holder.populateFrom(c, helper);
    }
    
    @Override
    public View newView(Context ctxt, Cursor c,
                         ViewGroup parent) {
      LayoutInflater inflater=getLayoutInflater();
      View row=inflater.inflate(R.layout.row, parent, false);
      RestaurantHolder holder=new RestaurantHolder(row);
      
      row.setTag(holder);
      
      return(row);
    }
  }
  
  static class RestaurantHolder {
    private TextView name=null;
    private TextView address=null;
    private ImageView icon=null;
    
    RestaurantHolder(View row) {
      name=(TextView)row.findViewById(R.id.title);
      address=(TextView)row.findViewById(R.id.address);
      icon=(ImageView)row.findViewById(R.id.icon);
    }
    
    void populateFrom(Cursor c, RestaurantHelper helper) {
      name.setText(helper.getName(c));
      address.setText(helper.getAddress(c));
  
      if (helper.getType(c).equals("sit_down")) {
        icon.setImageResource(R.drawable.ball_red);
      }
      else if (helper.getType(c).equals("take_out")) {
        icon.setImageResource(R.drawable.ball_yellow);
      }
      else {
        icon.setImageResource(R.drawable.ball_green);
      }
    }
  }
}


//12-Activities\LunchList\src\apt\tutorial\RestaurantHelper.java
package apt.tutorial;

import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

class RestaurantHelper extends SQLiteOpenHelper {
  private static final String DATABASE_NAME="lunchlist.db";
  private static final int SCHEMA_VERSION=1;
  
  public RestaurantHelper(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
  }
  
  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // no-op, since will not be called until 2nd schema
    // version exists
  }

  public Cursor getAll() {
    return(getReadableDatabase()
            .rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
                      null));
  }
  
  public Cursor getById(String id) {
    String[] args={id};

    return(getReadableDatabase()
            .rawQuery("SELECT _id, name, address, type, notes FROM restaurants WHERE _ID=?",
                      args));
  }
  
  public void insert(String name, String address,
                     String type, String notes) {
    ContentValues cv=new ContentValues();
          
    cv.put("name", name);
    cv.put("address", address);
    cv.put("type", type);
    cv.put("notes", notes);
    
    getWritableDatabase().insert("restaurants", "name", cv);
  }
  
  public void update(String id, String name, String address,
                     String type, String notes) {
    ContentValues cv=new ContentValues();
    String[] args={id};
    
    cv.put("name", name);
    cv.put("address", address);
    cv.put("type", type);
    cv.put("notes", notes);
    
    getWritableDatabase().update("restaurants", cv, "_ID=?",
                                 args);
  }
  
  public String getName(Cursor c) {
    return(c.getString(1));
  }
  
  public String getAddress(Cursor c) {
    return(c.getString(2));
  }
  
  public String getType(Cursor c) {
    return(c.getString(3));
  }
  
  public String getNotes(Cursor c) {
    return(c.getString(4));
  }
}


//12-Activities\LunchList\res\values\strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LunchList</string>
</resources>



//12-Activities\LunchList\res\menu\option.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add"
    android:title="Add"
    android:icon="@drawable/ic_menu_add"
  />
</menu>


//12-Activities\LunchList\res\layout\detail_form.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:stretchColumns="1"
  >
  <TableRow>
    <TextView android:text="Name:" />
    <EditText android:id="@+id/name" />
  </TableRow>
  <TableRow>
    <TextView android:text="Address:" />
    <EditText android:id="@+id/addr" />
  </TableRow>
  <TableRow>
    <TextView android:text="Type:" />
    <RadioGroup android:id="@+id/types">
      <RadioButton android:id="@+id/take_out"
        android:text="Take-Out"
      />
      <RadioButton android:id="@+id/sit_down"
        android:text="Sit-Down"
      />
      <RadioButton android:id="@+id/delivery"
        android:text="Delivery"
      />
    </RadioGroup>
  </TableRow>
  <TableRow>
    <TextView android:text="Notes:" />
    <EditText android:id="@+id/notes"
      android:singleLine="false"
      android:gravity="top"
      android:lines="2"
      android:scrollHorizontally="false"
      android:maxLines="2"
      android:maxWidth="200sp"
    />
  </TableRow>
  <Button android:id="@+id/save"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save"
  />
</TableLayout>



//12-Activities\LunchList\res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/list"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
/>

//12-Activities\LunchList\res\layout\row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:padding="4dip"
  >
  <ImageView android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="4dip"
  />
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >  
    <TextView android:id="@+id/title"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:textStyle="bold"
      android:singleLine="true"
      android:ellipsize="end"
    />
    <TextView android:id="@+id/address"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:singleLine="true"
      android:ellipsize="end"
    />
  </LinearLayout>
</LinearLayout>

Find user control by using findViewById

     
package app.Test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;

public class appTest extends Activity {
  private EditText urlText;
  private Button goButton;

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

    // Get a handle to all user interface elements
    urlText = (EditText) findViewById(R.id.url_field);
    goButton = (Button) findViewById(R.id.go_button);

    // Setup event handlers
    goButton.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        openBrowser();
      }
    });
    urlText.setOnKeyListener(new OnKeyListener() {
      public boolean onKey(View view, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
          openBrowser();
          return true;
        }
        return false;
      }
    });
  }

  /** Open a browser on the URL specified in the text box */
  private void openBrowser() {
    Uri uri = Uri.parse(urlText.getText().toString());
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
  }

}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <EditText
         android:id="@+id/url_field"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_weight="1.0"
         android:lines="1" />
      <Button
         android:id="@+id/go_button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@string/go_button" />
   </LinearLayout>
   <WebView
      android:id="@+id/web_view"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1.0" />
</LinearLayout>

A Simple Form

     



package app.test;

import android.app.Activity;
import android.os.Bundle;

public class Test extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
   }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
/>
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address:"
/>
<EditText android:id="@+id/addr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</LinearLayout>

Link form with POJO

     
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Test extends Activity {
  Restaurant r = new Restaurant();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button save = (Button) findViewById(R.id.save);
    save.setOnClickListener(onSave);
  }

  private View.OnClickListener onSave = new View.OnClickListener() {
    public void onClick(View v) {
      EditText name = (EditText) findViewById(R.id.name);
      EditText address = (EditText) findViewById(R.id.addr);
      r.setName(name.getText().toString());
      r.setAddress(address.getText().toString());
    }
  };
}

class Restaurant {
  private String name = "";
  private String address = "";

  public String getName() {
    return (name);
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getAddress() {
    return (address);
  }

  public void setAddress(String address) {
    this.address = address;
  }
}


//main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
/>
<EditText android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address:"
/>
<EditText android:id="@+id/addr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</LinearLayout>

Life cycle

package apt.tutorial;

import android.app.TabActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class LunchList extends TabActivity {
  List<Restaurant> model=new ArrayList<Restaurant>();
  RestaurantAdapter adapter=null;
  EditText name=null;
  EditText address=null;
  EditText notes=null;
  RadioGroup types=null;
  Restaurant current=null;
  AtomicBoolean isActive=new AtomicBoolean(true);
  int progress=0;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.main);
    
    name=(EditText)findViewById(R.id.name);
    address=(EditText)findViewById(R.id.addr);
    notes=(EditText)findViewById(R.id.notes);
    types=(RadioGroup)findViewById(R.id.types);
    
    Button save=(Button)findViewById(R.id.save);
    
    save.setOnClickListener(onSave);
    
    ListView list=(ListView)findViewById(R.id.restaurants);
    
    adapter=new RestaurantAdapter();
    list.setAdapter(adapter);
    
    TabHost.TabSpec spec=getTabHost().newTabSpec("tag1");
    
    spec.setContent(R.id.restaurants);
    spec.setIndicator("List", getResources()
                                .getDrawable(R.drawable.list));
    getTabHost().addTab(spec);
    
    spec=getTabHost().newTabSpec("tag2");
    spec.setContent(R.id.details);
    spec.setIndicator("Details", getResources()
                                  .getDrawable(R.drawable.restaurant));
    getTabHost().addTab(spec);
    
    getTabHost().setCurrentTab(0);
    
    list.setOnItemClickListener(onListClick);
  }
  
  @Override
  public void onPause() {
    super.onPause();
    
    isActive.set(false);
  }
  
  @Override
  public void onResume() {
    super.onResume();
    
    isActive.set(true);
    
    if (progress>0) {
      startWork();
    }
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.option, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.toast) {
      String message="No restaurant selected";
      
      if (current!=null) {
        message=current.getNotes();
      }
      
      Toast.makeText(this, message, Toast.LENGTH_LONG).show();
      
      return(true);
    }
    else if (item.getItemId()==R.id.run) {
      startWork();
      
      return(true);
    }
    
    return(super.onOptionsItemSelected(item));
  }
  
  private void startWork() {
    setProgressBarVisibility(true);
    new Thread(longTask).start();      
  }
  
  private void doSomeLongWork(final int incr) {
    runOnUiThread(new Runnable() {
      public void run() {
        progress+=incr;
        setProgress(progress);
      }
    });
    
    SystemClock.sleep(250);  // should be something more useful!
  }
  
  private View.OnClickListener onSave=new View.OnClickListener() {
    public void onClick(View v) {
      current=new Restaurant();
      current.setName(name.getText().toString());
      current.setAddress(address.getText().toString());
      current.setNotes(notes.getText().toString());
      
      switch (types.getCheckedRadioButtonId()) {
        case R.id.sit_down:
          current.setType("sit_down");
          break;
          
        case R.id.take_out:
          current.setType("take_out");
          break;
          
        case R.id.delivery:
          current.setType("delivery");
          break;
      }
      
      adapter.add(current);
    }
  };
  
  private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent,
                             View view, int position,
                             long id) {
      current=model.get(position);
      
      name.setText(current.getName());
      address.setText(current.getAddress());
      notes.setText(current.getNotes());
      
      if (current.getType().equals("sit_down")) {
        types.check(R.id.sit_down);
      }
      else if (current.getType().equals("take_out")) {
        types.check(R.id.take_out);
      }
      else {
        types.check(R.id.delivery);
      }
      
      getTabHost().setCurrentTab(1);
    }
  };
  
  private Runnable longTask=new Runnable() {
    public void run() {
      for (int i=progress;
           i<10000 && isActive.get();
           i+=200) {
        doSomeLongWork(200);
      }
      
      if (isActive.get()) {
        runOnUiThread(new Runnable() {
          public void run() {
            setProgressBarVisibility(false);
            progress=0;
          }
        });
      }
    }
  };
  
  class RestaurantAdapter extends ArrayAdapter<Restaurant> {
    RestaurantAdapter() {
      super(LunchList.this, R.layout.row, model);
    }
    
    public View getView(int position, View convertView,
                        ViewGroup parent) {
      View row=convertView;
      RestaurantHolder holder=null;
      
      if (row==null) {                          
        LayoutInflater inflater=getLayoutInflater();
        
        row=inflater.inflate(R.layout.row, parent, false);
        holder=new RestaurantHolder(row);
        row.setTag(holder);
      }
      else {
        holder=(RestaurantHolder)row.getTag();
      }
      
      holder.populateFrom(model.get(position));
      
      return(row);
    }
  }
  
  static class RestaurantHolder {
    private TextView name=null;
    private TextView address=null;
    private ImageView icon=null;
    
    RestaurantHolder(View row) {
      name=(TextView)row.findViewById(R.id.title);
      address=(TextView)row.findViewById(R.id.address);
      icon=(ImageView)row.findViewById(R.id.icon);
    }
    
    void populateFrom(Restaurant r) {
      name.setText(r.getName());
      address.setText(r.getAddress());
  
      if (r.getType().equals("sit_down")) {
        icon.setImageResource(R.drawable.ball_red);
      }
      else if (r.getType().equals("take_out")) {
        icon.setImageResource(R.drawable.ball_yellow);
      }
      else {
        icon.setImageResource(R.drawable.ball_green);
      }
    }
  }
}


package apt.tutorial;

public class Restaurant {
  private String name="";
  private String address="";
  private String type="";
  private String notes="";
  
  public String getName() {
    return(name);
  }
  
  public void setName(String name) {
    this.name=name;
  }
  
  public String getAddress() {
    return(address);
  }
  
  public void setAddress(String address) {
    this.address=address;
  }
  
  public String getType() {
    return(type);
  }
  
  public void setType(String type) {
    this.type=type;
  }
  
  public String getNotes() {
    return(notes);
  }
  
  public void setNotes(String notes) {
    this.notes=notes;
  }
  
  public String toString() {
    return(getName());
  }
}

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LunchList</string>
</resources>

//option.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/toast"
    android:title="Raise Toast"
    android:icon="@drawable/toast"
  />
  <item android:id="@+id/run"
    android:title="Run Long Task"
    android:icon="@drawable/run"
  />
</menu>

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    />
    <FrameLayout android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      >
      <ListView android:id="@+id/restaurants"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
      />
      <TableLayout android:id="@+id/details"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1"
        android:paddingTop="4dip"
        >
        <TableRow>
          <TextView android:text="Name:" />
          <EditText android:id="@+id/name" />
        </TableRow>
        <TableRow>
          <TextView android:text="Address:" />
          <EditText android:id="@+id/addr" />
        </TableRow>
        <TableRow>
          <TextView android:text="Type:" />
          <RadioGroup android:id="@+id/types">
            <RadioButton android:id="@+id/take_out"
              android:text="Take-Out"
            />
            <RadioButton android:id="@+id/sit_down"
              android:text="Sit-Down"
            />
            <RadioButton android:id="@+id/delivery"
              android:text="Delivery"
            />
          </RadioGroup>
        </TableRow>
        <TableRow>
          <TextView android:text="Notes:" />
          <EditText android:id="@+id/notes"
            android:singleLine="false"
            android:gravity="top"
            android:lines="2"
            android:scrollHorizontally="false"
            android:maxLines="2"
            android:maxWidth="200sp"
          />
        </TableRow>
        <Button android:id="@+id/save"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Save"
        />
      </TableLayout>
    </FrameLayout>
  </LinearLayout>
</TabHost>
//row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:padding="4dip"
  >
  <ImageView android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="4dip"
  />
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >  
    <TextView android:id="@+id/title"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:textStyle="bold"
      android:singleLine="true"
      android:ellipsize="end"
    />
    <TextView android:id="@+id/address"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:singleLine="true"
      android:ellipsize="end"
    />
  </LinearLayout>
</LinearLayout>

add android:background = "#FFFF0000"

     


package app.test;

import android.app.Activity;
import android.os.Bundle;

public class Test extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
   }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background = "#FFFF0000" 
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, FirstApp"
/>
</LinearLayout>

Rotation demo

package apt.tutorial;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

public class DetailForm extends Activity {
  EditText name=null;
  EditText address=null;
  EditText notes=null;
  RadioGroup types=null;
  RestaurantHelper helper=null;
  String restaurantId=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail_form);
    
    helper=new RestaurantHelper(this);
    
    name=(EditText)findViewById(R.id.name);
    address=(EditText)findViewById(R.id.addr);
    notes=(EditText)findViewById(R.id.notes);
    types=(RadioGroup)findViewById(R.id.types);
    
    Button save=(Button)findViewById(R.id.save);
    
    save.setOnClickListener(onSave);
    
    restaurantId=getIntent().getStringExtra(LunchList.ID_EXTRA);
    
    if (restaurantId!=null) {
      load();
    }
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
  
    helper.close();
  }
  
  @Override
  public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    
    state.putString("name", name.getText().toString());
    state.putString("address", address.getText().toString());
    state.putString("notes", notes.getText().toString());
    state.putInt("type", types.getCheckedRadioButtonId());
  }

  @Override
  public void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);
    
    name.setText(state.getString("name"));
    address.setText(state.getString("address"));
    notes.setText(state.getString("notes"));
    types.check(state.getInt("type"));
  }
  
  private void load() {
    Cursor c=helper.getById(restaurantId);

    c.moveToFirst();    
    name.setText(helper.getName(c));
    address.setText(helper.getAddress(c));
    notes.setText(helper.getNotes(c));
    
    if (helper.getType(c).equals("sit_down")) {
      types.check(R.id.sit_down);
    }
    else if (helper.getType(c).equals("take_out")) {
      types.check(R.id.take_out);
    }
    else {
      types.check(R.id.delivery);
    }
    
    c.close();
  }
  
  private View.OnClickListener onSave=new View.OnClickListener() {
    public void onClick(View v) {
      String type=null;
      
      switch (types.getCheckedRadioButtonId()) {
        case R.id.sit_down:
          type="sit_down";
          break;
        case R.id.take_out:
          type="take_out";
          break;
        case R.id.delivery:
          type="delivery";
          break;
      }

      if (restaurantId==null) {
        helper.insert(name.getText().toString(),
                      address.getText().toString(), type,
                      notes.getText().toString());
      }
      else {
        helper.update(restaurantId, name.getText().toString(),
                      address.getText().toString(), type,
                      notes.getText().toString());
      }
      
      finish();
    }
  };
}



package apt.tutorial;

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class EditPreferences extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    addPreferencesFromResource(R.xml.preferences);
  }
}



package apt.tutorial;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class LunchList extends ListActivity {
  public final static String ID_EXTRA="apt.tutorial._ID";
  Cursor model=null;
  RestaurantAdapter adapter=null;
  RestaurantHelper helper=null;
  SharedPreferences prefs=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    helper=new RestaurantHelper(this);
    prefs=PreferenceManager.getDefaultSharedPreferences(this);
    initList();
    prefs.registerOnSharedPreferenceChangeListener(prefListener);
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
    
    helper.close();
  }
  
  @Override
  public void onListItemClick(ListView list, View view,
                              int position, long id) {
    Intent i=new Intent(LunchList.this, DetailForm.class);

    i.putExtra(ID_EXTRA, String.valueOf(id));
    startActivity(i);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.option, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.add) {
      startActivity(new Intent(LunchList.this, DetailForm.class));
      
      return(true);
    }
    else if (item.getItemId()==R.id.prefs) {
      startActivity(new Intent(this, EditPreferences.class));
    
      return(true);
    }

    return(super.onOptionsItemSelected(item));
  }
  
  private void initList() {
    if (model!=null) {
      stopManagingCursor(model);
      model.close();
    }
    
    model=helper.getAll(prefs.getString("sort_order", "name"));
    startManagingCursor(model);
    adapter=new RestaurantAdapter(model);
    setListAdapter(adapter);
  }
  
  private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
   new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences sharedPrefs,
                                          String key) {
      if (key.equals("sort_order")) {
        initList();
      }
    }
  };
  
  class RestaurantAdapter extends CursorAdapter {
    RestaurantAdapter(Cursor c) {
      super(LunchList.this, c);
    }
    
    @Override
    public void bindView(View row, Context ctxt,
                         Cursor c) {
      RestaurantHolder holder=(RestaurantHolder)row.getTag();
      
      holder.populateFrom(c, helper);
    }
    
    @Override
    public View newView(Context ctxt, Cursor c,
                         ViewGroup parent) {
      LayoutInflater inflater=getLayoutInflater();
      View row=inflater.inflate(R.layout.row, parent, false);
      RestaurantHolder holder=new RestaurantHolder(row);
      
      row.setTag(holder);
      
      return(row);
    }
  }
  
  static class RestaurantHolder {
    private TextView name=null;
    private TextView address=null;
    private ImageView icon=null;
    
    RestaurantHolder(View row) {
      name=(TextView)row.findViewById(R.id.title);
      address=(TextView)row.findViewById(R.id.address);
      icon=(ImageView)row.findViewById(R.id.icon);
    }
    
    void populateFrom(Cursor c, RestaurantHelper helper) {
      name.setText(helper.getName(c));
      address.setText(helper.getAddress(c));
  
      if (helper.getType(c).equals("sit_down")) {
        icon.setImageResource(R.drawable.ball_red);
      }
      else if (helper.getType(c).equals("take_out")) {
        icon.setImageResource(R.drawable.ball_yellow);
      }
      else {
        icon.setImageResource(R.drawable.ball_green);
      }
    }
  }
}



package apt.tutorial;

import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

class RestaurantHelper extends SQLiteOpenHelper {
  private static final String DATABASE_NAME="lunchlist.db";
  private static final int SCHEMA_VERSION=1;
  
  public RestaurantHelper(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
  }
  
  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // no-op, since will not be called until 2nd schema
    // version exists
  }

  public Cursor getAll(String orderBy) {
    return(getReadableDatabase()
            .rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY "+orderBy,
                      null));
  }
  
  public Cursor getById(String id) {
    String[] args={id};

    return(getReadableDatabase()
            .rawQuery("SELECT _id, name, address, type, notes FROM restaurants WHERE _ID=?",
                      args));
  }
  
  public void insert(String name, String address,
                     String type, String notes) {
    ContentValues cv=new ContentValues();
          
    cv.put("name", name);
    cv.put("address", address);
    cv.put("type", type);
    cv.put("notes", notes);
    
    getWritableDatabase().insert("restaurants", "name", cv);
  }
  
  public void update(String id, String name, String address,
                     String type, String notes) {
    ContentValues cv=new ContentValues();
    String[] args={id};
    
    cv.put("name", name);
    cv.put("address", address);
    cv.put("type", type);
    cv.put("notes", notes);
    
    getWritableDatabase().update("restaurants", cv, "_ID=?",
                                 args);
  }
  
  public String getName(Cursor c) {
    return(c.getString(1));
  }
  
  public String getAddress(Cursor c) {
    return(c.getString(2));
  }
  
  public String getType(Cursor c) {
    return(c.getString(3));
  }
  
  public String getNotes(Cursor c) {
    return(c.getString(4));
  }
}



//res\xml\preferences.xml
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
  <ListPreference
    android:key="sort_order"
    android:title="Sort Order"
    android:summary="Choose the order the list uses"
    android:entries="@array/sort_names"
    android:entryValues="@array/sort_clauses"
    android:dialogTitle="Choose a sort order" />
</PreferenceScreen>



//res\values\arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string-array name="sort_names">
    <item>By Name, Ascending</item>
    <item>By Name, Descending</item>
    <item>By Type</item>
    <item>By Address, Ascending</item>
    <item>By Address, Descending</item>
  </string-array>
  <string-array name="sort_clauses">
    <item>name ASC</item>
    <item>name DESC</item>
    <item>type, name ASC</item>
    <item>address ASC</item>
    <item>address DESC</item>
  </string-array>
</resources>


//res\values\strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LunchList</string>
</resources>



//res\menu\option.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add"
    android:title="Add"
    android:icon="@drawable/ic_menu_add"
  />
  <item android:id="@+id/prefs"
    android:title="Settings"
    android:icon="@drawable/ic_menu_preferences"
  />
</menu>



//res\layout-land\detail_form.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:stretchColumns="3"
  >
  <TableRow>
    <TextView android:text="Name:" />
    <EditText android:id="@+id/name"
      android:layout_span="3"
    />
  </TableRow>
  <TableRow>
    <TextView android:text="Address:" />
    <EditText android:id="@+id/addr"
      android:layout_span="3"
    />
  </TableRow>
  <TableRow>
    <TextView android:text="Type:" />
    <RadioGroup android:id="@+id/types">
      <RadioButton android:id="@+id/take_out"
        android:text="Take-Out"
      />
      <RadioButton android:id="@+id/sit_down"
        android:text="Sit-Down"
      />
      <RadioButton android:id="@+id/delivery"
        android:text="Delivery"
      />
    </RadioGroup>
    <TextView android:text="Notes:" />
    <LinearLayout android:orientation="vertical">
      <EditText android:id="@+id/notes"
        android:singleLine="false"
        android:gravity="top"
        android:lines="2"
        android:scrollHorizontally="false"
        android:maxLines="2"
        android:maxWidth="140sp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
      />
      <Button android:id="@+id/save"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save"
      />
    </LinearLayout>
  </TableRow>
</TableLayout>



//res\layout\detail_form.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:stretchColumns="1"
  >
  <TableRow>
    <TextView android:text="Name:" />
    <EditText android:id="@+id/name" />
  </TableRow>
  <TableRow>
    <TextView android:text="Address:" />
    <EditText android:id="@+id/addr" />
  </TableRow>
  <TableRow>
    <TextView android:text="Type:" />
    <RadioGroup android:id="@+id/types">
      <RadioButton android:id="@+id/take_out"
        android:text="Take-Out"
      />
      <RadioButton android:id="@+id/sit_down"
        android:text="Sit-Down"
      />
      <RadioButton android:id="@+id/delivery"
        android:text="Delivery"
      />
    </RadioGroup>
  </TableRow>
  <TableRow>
    <TextView android:text="Notes:" />
    <EditText android:id="@+id/notes"
      android:singleLine="false"
      android:gravity="top"
      android:lines="2"
      android:scrollHorizontally="false"
      android:maxLines="2"
      android:maxWidth="200sp"
    />
  </TableRow>
  <Button android:id="@+id/save"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save"
  />
</TableLayout>



//res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/list"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
/>



//res\layout\row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:padding="4dip"
  >
  <ImageView android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="4dip"
  />
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >  
    <TextView android:id="@+id/title"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:textStyle="bold"
      android:singleLine="true"
      android:ellipsize="end"
    />
    <TextView android:id="@+id/address"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:singleLine="true"
      android:ellipsize="end"
    />
  </LinearLayout>
</LinearLayout>

   

Set activity screen Orientation

     

package app.test;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Test extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton);
        if( getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED ) {
            toggle.setChecked(true);
        } else {
            toggle.setChecked(false);
        }
        toggle.setOnCheckedChangeListener(listener);
    }

    OnCheckedChangeListener listener = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int current = getResources().getConfiguration().orientation;
            if(isChecked) {
                switch(current) {
                case Configuration.ORIENTATION_LANDSCAPE:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case Configuration.ORIENTATION_PORTRAIT:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            }
        }
    };
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ToggleButton
    android:id="@+id/toggleButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Lock"
    android:textOn="LOCKED"
  />
</LinearLayout>
Check activity result
package com.commonsware.android.rotation.four;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class RotationFourDemo extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.main);
    
    Button btn=(Button)findViewById(R.id.pick);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                            Contacts.CONTENT_URI);

        startActivityForResult(i, PICK_REQUEST);
      }
    });
    
    viewButton=(Button)findViewById(R.id.view);
    
    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });
    
    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }
}


//res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>

Activity lifecycle event

     

package app.test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Test extends Activity {
  String tag = "Events";
  int request_Code = 1;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // hides the title bar
    // requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.main);
    Log.d(tag, "In the onCreate() event");
  }

  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
      // startActivity(new Intent("net.learn2develop.ACTIVITY2"));
      // startActivity(new Intent(this, Activity2.class));
      /*
       * startActivityForResult(new Intent(
       * "net.learn2develop.ACTIVITY2"), request_Code);
       */
      Intent i = new Intent("app.test.ACTIVITY2");

      Bundle extras = new Bundle();
      extras.putString("Name", "Your name here");
      i.putExtras(extras);
      startActivityForResult(i, 1);
    }
    return false;
  }

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
      if (resultCode == RESULT_OK) {
        Toast.makeText(this, data.getData().toString(),
            Toast.LENGTH_SHORT).show();
      }
    }
  }

  public void onStart() {
    super.onStart();
    Log.d(tag, "In the onStart() event");
  }

  public void onRestart() {
    super.onRestart();
    Log.d(tag, "In the onRestart() event");
  }

  public void onResume() {
    super.onResume();
    Log.d(tag, "In the onResume() event");
  }

  public void onPause() {
    super.onPause();
    Log.d(tag, "In the onPause() event");
  }

  public void onStop() {
    super.onStop();
    Log.d(tag, "In the onStop() event");
  }

  public void onDestroy() {
    super.onDestroy();
    Log.d(tag, "In the onDestroy() event");
  }
}

class Activity2 extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row);

    String defaultName = "";
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      defaultName = extras.getString("Name");
    }
    EditText txt_username = (EditText) findViewById(R.id.txt_username);
    txt_username.setHint(defaultName);
    Button btn = (Button) findViewById(R.id.btn_OK);
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent data = new Intent();
        EditText txt_username = (EditText) findViewById(R.id.txt_username);
        data.setData(Uri.parse(txt_username.getText().toString()));
        setResult(RESULT_OK, data);
        finish();
      }
    });
  }
}
class Activity3 extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row);
    Button btn = (Button) findViewById(R.id.btn_OK);
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent data = new Intent();
        EditText txt_username = (EditText) findViewById(R.id.txt_username);
        data.setData(Uri.parse(txt_username.getText().toString()));
        setResult(RESULT_OK, data);
        finish();
      }
    });
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>
//row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Please enter your name" />    
<EditText
    android:id="@+id/txt_username"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" />    
<Button
    android:id="@+id/btn_OK"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="OK" />
</LinearLayout>

Activity key event

     
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(btnListener);

    Button btn2 = (Button) findViewById(R.id.btn2);
    btn2.setOnClickListener(btnListener);

    EditText txt1 = (EditText) findViewById(R.id.txt1);
    txt1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        Toast.makeText(getBaseContext(),
            ((EditText) v).getId() + " has focus - " + hasFocus,
            Toast.LENGTH_LONG).show();
      }
    });
  }

  private OnClickListener btnListener = new OnClickListener() {
    public void onClick(View v) {
      Toast.makeText(getBaseContext(),
          ((Button) v).getText() + " was clicked", Toast.LENGTH_LONG)
          .show();
    }
  };

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_DPAD_CENTER:
      Toast.makeText(getBaseContext(), "Center was clicked",
          Toast.LENGTH_LONG).show();
      break;
    case KeyEvent.KEYCODE_DPAD_LEFT:
      Toast.makeText(getBaseContext(), "Left arrow was clicked",
          Toast.LENGTH_LONG).show();
      break;
    case KeyEvent.KEYCODE_DPAD_RIGHT:
      Toast.makeText(getBaseContext(), "Right arrow was clicked",
          Toast.LENGTH_LONG).show();
      break;
    case KeyEvent.KEYCODE_DPAD_UP:
      Toast.makeText(getBaseContext(), "Up arrow was clicked",
          Toast.LENGTH_LONG).show();
      break;
    case KeyEvent.KEYCODE_DPAD_DOWN:
      Toast.makeText(getBaseContext(), "Down arrow was clicked",
          Toast.LENGTH_LONG).show();
      break;
    }
    return false;
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/widget28"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"    
    >
    <TextView        
        android:layout_width="214dp"
        android:layout_height="wrap_content"
        android:text="Your Name"        
        />
    <EditText
        android:id="@+id/txt1"
        android:layout_width="214dp"
        android:layout_height="wrap_content"        
        />   
    <Button
        android:id="@+id/btn1"
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:text="OK"
        />
    <Button
        android:id="@+id/btn2"
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:text="Cancel"
        />
</LinearLayout>

Allows the activity to manage the Cursor's lifecyle based on the activity’s lifecycle---

     
        
package app.test;

import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.SimpleCursorAdapter;

public class Test extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Uri allContacts = Uri.parse("content://contacts/people");
        //Uri allContacts = Uri.parse("content://contacts/people/1");        
        Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
        //Uri allContacts = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, 1);
        Cursor c = getContentResolver().query(allContacts, null, null, null, null);
        startManagingCursor(c); 
        String[] columns = new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,};
        int[] views = new int[] {R.id.contactName, R.id.contactID};
        
        SimpleCursorAdapter adapter = 
            new SimpleCursorAdapter(this, R.layout.main, c, columns, views);
        this.setListAdapter(adapter);
        
        PrintContacts(c);  
    }    
    
    private void PrintContacts(Cursor c)
    {
        if (c.moveToFirst()) {
            do{
              String contactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
              String contactDisplayName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));  
                Log.v("Content Providers", contactID + ", " + contactDisplayName);
                int hasPhone = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if (hasPhone == 1) {
                    Cursor phoneCursor = getContentResolver().query(
                      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                      ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactID, null, null);                     
                    while (phoneCursor.moveToNext()) {
                      Log.v("Content Providers",
                            phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));                  
                    } 
                    phoneCursor.close();
                }
            } while (c.moveToNext());
        }
    }
}


//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView 
        android:id="@+id/android:list" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_weight="1" 
        android:stackFromBottom="false" 
        android:transcriptMode="normal" 
        /> 
    <TextView   
        android:id="@+id/contactName"
        android:textStyle="bold"   
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        /> 
    <TextView   
        android:id="@+id/contactID" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
       />   

</LinearLayout>

Activity configuration changed event

     
package app.test;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import android.widget.Toast;

public class Test extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        String rString = "message";
        String fString = String.format(rString, "Collaborate and listen.");
        CharSequence styledString = Html.fromHtml(fString);
        TextView tv = (TextView)findViewById(R.id.myTextView);
        tv.setText(styledString);
        setContentView(R.layout.main);
        Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
    }
    
    @Override 
    public void onConfigurationChanged(Configuration _newConfig) {
      super.onConfigurationChanged(_newConfig);  
      if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
      }

      if (_newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) {
      }
    }
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
    }
    @Override
    public void onRestart(){
      super.onRestart();
    }
    @Override
    public void onStart(){
      super.onStart();
    }
    @Override
    public void onResume(){
      super.onResume();
    }
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {    
      super.onSaveInstanceState(savedInstanceState);
    }
    @Override
    public void onPause(){
      super.onPause();
    }
    @Override
    public void onStop(){    
      super.onStop();
    }
    @Override
    public void onDestroy(){
      super.onDestroy();
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:id="@+id/myTextView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>

Check Activity result and onActivityResult

     


package app.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 class Activity1 extends Activity {
  OnClickListener listener1 = null;
  Button button1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.row);
        listener1 = new OnClickListener() {
      public void onClick(View v) {
        Bundle bundle = new Bundle();
        bundle.putString("store", "Activity1");
        Intent mIntent = new Intent();
        mIntent.putExtras(bundle);
        setResult(RESULT_OK, mIntent);
        finish();
      }
    };
    button1 = (Button) findViewById(R.id.button3);
    button1.setOnClickListener(listener1);
    String data=null;
     Bundle extras = getIntent().getExtras();
          if (extras != null) {
               data = extras.getString("activityMain");
          }
    setTitle("Activity1:"+data);
    }
}

 class Activity2 extends Activity {
  OnClickListener listener = null;
  Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_edit);
        listener = new OnClickListener() {
      public void onClick(View v) {
        finish();
      }
    };
    button = (Button) findViewById(R.id.button4);
    button.setOnClickListener(listener);
    setTitle("Activity2");
    }
}
public class Test extends Activity {
  OnClickListener listener1 = null;
  OnClickListener listener2 = null;
  Button button1;
  Button button2;
  static final int REQUEST_CODE = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    listener1 = new OnClickListener() {
      public void onClick(View v) {
        Intent intent1 = new Intent(Test.this, Activity1.class);
        intent1.putExtra("activityMain", "activityMain");
        startActivityForResult(intent1, REQUEST_CODE);
      }
    };
    listener2 = new OnClickListener() {
      public void onClick(View v) {
        setTitle("ActivityMain");
        Intent intent2 = new Intent(Test.this, Activity2.class);
        startActivity(intent2);

      }
    };
    setContentView(R.layout.main);
    button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(listener1);
    button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(listener2);
    setTitle("ActivityMain");
  }
    
    @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE) {
      if (resultCode == RESULT_CANCELED)
        setTitle("OK");
      else if (resultCode == RESULT_OK) {
        String temp=null;
         Bundle extras = data.getExtras();
              if (extras != null) {
                temp = extras.getString("store");
              }
        setTitle(temp);
      }
    }
  }
}

//  layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="??button1" />
  <Button android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="??button2" />
</LinearLayout>


//  layout/row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  
  <Button android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="??button3" />

</LinearLayout>



//  layout/add_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  
  <Button android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="??button4" />
</LinearLayout>

Phone Call Activity

     

package app.test;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class PhoneCallActivity extends Activity {
    private TextView tv = null;
    private String logText = "";
    private TelephonyManager teleMgr = null;
    private MyPhoneStateListener myListener = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv = (TextView)findViewById(R.id.textView);

        teleMgr = 
                (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        myListener = new MyPhoneStateListener();
    }
    
    @Override
    public void onResume() {
      super.onResume();
        teleMgr.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
    
    @Override
    public void onPause() {
      super.onPause();
        teleMgr.listen(myListener, PhoneStateListener.LISTEN_NONE);
    }
    
    public void doClick(View target) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:1235551212"));
        startActivity(intent);
    }
    
    public class MyPhoneStateListener extends PhoneStateListener
    {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch(state)
            {
                case TelephonyManager.CALL_STATE_IDLE:
                    logText = "call state idle...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                  logText = "call state ringing...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                  logText = "call state Offhook...incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
                default:
                  logText = "call state ["+state+"]incoming number is["+
                                incomingNumber+"]\n" + logText;
                    break;
            }
            tv.setText(logText);
        }
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:id="@+id/callBtn"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/btn"
    android:onClick="doClick"
    />
<TextView
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />    
</LinearLayout>

Using Media Store Activity

     

package app.test;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Test extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.recordBtn);
        btn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
                startRecording();
            }});
    }
    public void startRecording() {
        Intent intt = new Intent("android.provider.MediaStore.RECORD_SOUND");
        startActivityForResult(intt, 0);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri recordedAudioPath = data.getData();
                Log.v("Demo", recordedAudioPath.toString());
            }
        }
    }
}

External Storage Activity

     
package app.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView textView = new TextView(this);
    setContentView(textView);
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
      textView.setText("No external storage mounted");
    } else {
      File externalDir = Environment.getExternalStorageDirectory();
      File textFile = new File(externalDir.getAbsolutePath()
          + File.separator + "text.txt");
      try {
        writeTextFile(textFile, "This is a test.");
        String text = readTextFile(textFile);
        textView.setText(text);
        if (!textFile.delete()) {
          textView.setText("Couldn't remove temporary file");
        }
      } catch (IOException e) {
        textView.setText("something went wrong! " + e.getMessage());
      }
    }
  }

  private void writeTextFile(File file, String text) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(text);
    writer.close();
  }

  private String readTextFile(File file) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    StringBuilder text = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
      text.append(line);
      text.append("\n");
    }
    reader.close();
    return text.toString();
  }
}

Making Activity Go Full-Screen

     
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class Test extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
  }
}

Surface View Test Activity

     
package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

public class Test extends Activity {
  FastRenderView renderView;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    renderView = new FastRenderView(this);
    setContentView(renderView);
  }
  protected void onResume() {
    super.onResume();
    renderView.resume();
  }
  protected void onPause() {
    super.onPause();
    renderView.pause();
  }
}

class FastRenderView extends SurfaceView implements Runnable {
  Thread renderThread = null;
  SurfaceHolder holder;
  volatile boolean running = false;

  public FastRenderView(Context context) {
    super(context);
    holder = getHolder();
  }

  public void resume() {
    running = true;
    renderThread = new Thread(this);
    renderThread.start();
  }
  public void run() {
    while (running) {
      if (!holder.getSurface().isValid())
        continue;
      Canvas canvas = holder.lockCanvas();
      canvas.drawRGB(255, 0, 0);
      holder.unlockCanvasAndPost(canvas);
    }
  }
  public void pause() {
    running = false;
    while (true) {
      try {
        renderThread.join();
      } catch (InterruptedException e) {
        // retry
      }
    }
  }
}

Widget Preview Activity

package app.test;

import android.app.Activity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test extends Activity implements OnClickListener {

    private static final String LOG_TAG = "WidgetPreviewActivity";
    private static final boolean DEBUG = true;
    private static final int APPWIDGET_HOST_ID = 2048;
    private static final int REQUEST_WIDGET = 0;
    private static final int REQUEST_CONFIGURE = 1;

    private AppWidgetHost mAppWidgetHost = null;
    private FrameLayout mAppWidgetFrame = null;
    private AppWidgetHostView mAppWidgetView = null;
    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private String mAppWidgetName;
    private int mPreviewWidth;
    private int mPreviewHeight;

    private Button mSnapshotButton = null;
    private Button mEmailButton = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mAppWidgetFrame = (FrameLayout)findViewById(R.id.main_frame);
        mSnapshotButton = (Button)findViewById(R.id.snapshot_button);
        mSnapshotButton.setOnClickListener(this);
        mEmailButton = (Button)findViewById(R.id.email_button);
        mEmailButton.setOnClickListener(this);

        mAppWidgetHost = new AppWidgetHost(getApplicationContext(), APPWIDGET_HOST_ID);

        final Object retainedObj = getLastNonConfigurationInstance();
        if (retainedObj instanceof AppWidgetProviderInfo) {
            AppWidgetProviderInfo info = (AppWidgetProviderInfo) retainedObj;
            int id = mAppWidgetHost.allocateAppWidgetId();
            AppWidgetManager.getInstance(getBaseContext()).bindAppWidgetId(id, info.provider);
            setAppWidget(id);
        } else {
            startChooseActivity();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mAppWidgetHost.startListening();
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        AppWidgetProviderInfo info = AppWidgetManager.getInstance(
                getBaseContext()).getAppWidgetInfo(mAppWidgetId);
        return info;
    }

    private void startChooseActivity() {
        int id = mAppWidgetHost.allocateAppWidgetId();
        Intent selectIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
        selectIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id);
        startActivityForResult(selectIntent, REQUEST_WIDGET);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_WIDGET) {
            if (data != null) {
                int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
                if (data.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                    appWidgetId = data.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
                }

                if (resultCode == RESULT_OK) {
                    setAppWidget(appWidgetId);
                } else {
                    mAppWidgetHost.deleteAppWidgetId(appWidgetId);
                    finish();
                }
            } else {
                finish();
            }
        } else if (requestCode == REQUEST_CONFIGURE) {
            if (data != null) {
                int appWidgetId = data.getExtras().getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
                if (resultCode == RESULT_OK) {
                    finishSetAppWidget(appWidgetId);
                } else {
                    mAppWidgetHost.deleteAppWidgetId(appWidgetId);
                }
            }
        }
    }

    private void setAppWidget(int appWidgetId) {
        if (mAppWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            mAppWidgetHost.deleteAppWidgetId(mAppWidgetId);
        }

        /* Check for configuration */
        AppWidgetProviderInfo providerInfo =
            AppWidgetManager.getInstance(getBaseContext()).getAppWidgetInfo(appWidgetId);

        if (providerInfo.configure != null) {
            Intent configureIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
            configureIntent.setComponent(providerInfo.configure);
            configureIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

            if (configureIntent != null) {
                try {
                    startActivityForResult(configureIntent, REQUEST_CONFIGURE);
                } catch (ActivityNotFoundException e) {
                    Log.d(LOG_TAG, "Configuration activity not found: " + e);
                    Toast errorToast = Toast.makeText(
                            getBaseContext(), R.string.configure_error, Toast.LENGTH_SHORT);
                    errorToast.show();
                }
            }
        } else {
            finishSetAppWidget(appWidgetId);
        }
    }

    private void finishSetAppWidget(int appWidgetId) {
        AppWidgetProviderInfo providerInfo =
            AppWidgetManager.getInstance(getBaseContext()).getAppWidgetInfo(appWidgetId);
        if (providerInfo != null) {
            mAppWidgetView =
                    mAppWidgetHost.createView(getBaseContext(), appWidgetId, providerInfo);

            int [] dimensions =
                    getLauncherCellDimensions(providerInfo.minWidth, providerInfo.minHeight);

            mPreviewWidth = dimensions[0];
            mPreviewHeight = dimensions[1];

            mAppWidgetName =
                AppWidgetManager.getInstance(getBaseContext()).getAppWidgetInfo(appWidgetId).label;
            mAppWidgetName = mAppWidgetName.replaceAll("[^a-zA-Z0-9]", "_");

            ViewGroup.LayoutParams p = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mAppWidgetView.setLayoutParams(p);
            mAppWidgetFrame.removeAllViews();
            mAppWidgetHost.deleteAppWidgetId(mAppWidgetId);
            mAppWidgetFrame.addView(mAppWidgetView, mPreviewWidth, mPreviewHeight);
            mAppWidgetId = appWidgetId;
        }
    }

    // Taken from CellLayout.java
    public int[] getLauncherCellDimensions(int width, int height) {
        // Always assume we're working with the smallest span to make sure we
        // reserve enough space in both orientations.
        Resources resources = getResources();
        int cellWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
        int cellHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
        int widthGap = resources.getDimensionPixelSize(R.dimen.workspace_width_gap);
        int heightGap = resources.getDimensionPixelSize(R.dimen.workspace_height_gap);
        int previewCellSize = resources.getDimensionPixelSize(R.dimen.preview_cell_size);

        // This logic imitates Launcher's CellLayout.rectToCell.
        // Always round up to next largest cell
        int smallerSize = Math.min(cellWidth, cellHeight);
        int spanX = (width + smallerSize) / smallerSize;
        int spanY = (height + smallerSize) / smallerSize;

        // We use a fixed preview cell size so that you get the same preview image for
        // the same cell-sized widgets across all devices
        width = spanX * previewCellSize + ((spanX - 1) * widthGap);
        height = spanY * previewCellSize + ((spanY - 1) * heightGap);
        return new int[] { width, height };
    }

    private File buildFile(String name) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }

        File path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS);
        int orientationCode = getResources().getConfiguration().orientation;
        String orientation;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            orientation = "landscape";
        } else if (orientationCode == Configuration.ORIENTATION_PORTRAIT) {
            orientation = "portrait";
        } else if (orientationCode == Configuration.ORIENTATION_SQUARE) {
            orientation = "square";
        } else {
            orientation = "undefined";
        }
        return new File(path, name + "_ori_" + orientation + ".png");
    }

    public Bitmap getPreviewBitmap() {
        mAppWidgetView.invalidate();
        Bitmap bmp = Bitmap.createBitmap(
                mAppWidgetView.getWidth(), mAppWidgetView.getHeight(), Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        mAppWidgetView.draw(c);
        return bmp;
    }

    private boolean saveImage(Bitmap bmp, String name) {
        File pic = buildFile(mAppWidgetName);
        if (pic == null) {
            Log.d(LOG_TAG, "External storage not present");
            return false;
        }

        pic.getParentFile().mkdirs();
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pic);
            if (!bmp.compress(CompressFormat.PNG, 100, fout)) {
                Log.d(LOG_TAG, "Failed to compress image");
                return false;
            }
            return true;
        } catch (IOException e) {
            Log.d(LOG_TAG, "Error writing to disk: " + e);
        } finally {
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException e) {
                Log.d(LOG_TAG, "Could not close file: " + e);
            }
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (!getFragmentManager().popBackStackImmediate()) {
            startChooseActivity();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == mSnapshotButton) {
            int textId = R.string.saving_preview;

            Toast preToast = Toast.makeText(getBaseContext(), textId, Toast.LENGTH_SHORT);
            preToast.show();

            Bitmap bmp = getPreviewBitmap();
            if (saveImage(bmp, mAppWidgetName)) {
                textId = R.string.preview_saved;
            } else {
                textId = R.string.preview_save_error;
            }

            Toast postToast = Toast.makeText(getBaseContext(), textId, Toast.LENGTH_SHORT);
            postToast.show();
        } else if (v == mEmailButton) {
            File file = buildFile(mAppWidgetName);
            if (file.exists()) {
                Intent emailIntent = new Intent(Intent.ACTION_SEND);
                emailIntent.setType("image/png");
                emailIntent.putExtra(Intent.EXTRA_SUBJECT,
                        getResources().getString(R.string.email_subject));
                emailIntent.putExtra(Intent.EXTRA_TEXT,
                        getResources().getString(R.string.email_body));
                emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                startActivity(emailIntent);
            } else {
                Toast postToast = Toast.makeText(
                        getBaseContext(), R.string.no_preview, Toast.LENGTH_SHORT);
                postToast.show();
            }
        }
    }
}
//
//res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dp">
    <Button
            android:id="@+id/email_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="@string/email_button" />
    <Button
            android:id="@+id/snapshot_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@id/email_button"
            android:text="@string/snapshot_button" />
    <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_above="@id/snapshot_button"
            android:layout_centerHorizontal="true">
        <FrameLayout
                android:id="@+id/main_frame"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
        </FrameLayout>
    </FrameLayout>
</RelativeLayout>



//
//res\values\dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="preview_cell_size">96dip</dimen>
</resources>



//res\values\strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="application_label">Widget Preview</string>
    <string name="saving_preview">Saving widget preview...</string>
    <string name="preview_saved">Widget preview saved!</string>
    <string name="no_preview">Please take a snapshot first</string>
    <string name="preview_save_error">Error saving preview</string>
    <string name="configure_error">Error configuring, no configuration activity found</string>
    <string name="email_subject">Widget preview</string>
    <string name="email_body">Attached is the preview of your AppWidget</string>

    <string name="snapshot_button">Take Snapshot</string>
    <string name="email_button">Email Preview</string>
</resources>



//
//res\values-land\dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="workspace_cell_width">106dip</dimen>
    <dimen name="workspace_cell_height">74dip</dimen>
    <dimen name="workspace_width_gap">0dp</dimen>
    <dimen name="workspace_height_gap">0dp</dimen>
</resources>



//
//res\values-port\dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="workspace_cell_width">80dip</dimen>
    <dimen name="workspace_cell_height">100dip</dimen>
    <dimen name="workspace_width_gap">0dp</dimen>
    <dimen name="workspace_height_gap">0dp</dimen>
</resources>



//
//res\values-xlarge\dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="workspace_cell_width">96dip</dimen>
    <dimen name="workspace_cell_height">96dip</dimen>
    <dimen name="workspace_width_gap">0dp</dimen>
    <dimen name="workspace_height_gap">0dp</dimen>
</resources>

This class provides a basic demonstration of how to write an Android activity.

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * This class provides a basic demonstration of how to write an Android
 * activity. Inside of its window, it places a single view: an EditText that
 * displays and edits some internal text.
 */
public class Test extends Activity {
    
    static final private int BACK_ID = Menu.FIRST;
    static final private int CLEAR_ID = Menu.FIRST + 1;

    private EditText mEditor;
    
    public Test() {
    }

    /** Called with the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Inflate our UI from its XML layout description.
        setContentView(R.layout.skeleton_activity);

        // Find the text editor view inside the layout, because we
        // want to do various programmatic things with it.
        mEditor = (EditText) findViewById(R.id.editor);

        // Hook up button presses to the appropriate event handler.
        ((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
        ((Button) findViewById(R.id.clear)).setOnClickListener(mClearListener);
        
        mEditor.setText(getText(R.string.main_label));
    }

    /**
     * Called when the activity is about to start interacting with the user.
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * Called when your activity's options menu needs to be created.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // We are going to create two menus. Note that we assign them
        // unique integer IDs, labels from our string resources, and
        // given them shortcuts.
        menu.add(0, BACK_ID, 0, R.string.back).setShortcut('0', 'b');
        menu.add(0, CLEAR_ID, 0, R.string.clear).setShortcut('1', 'c');

        return true;
    }

    /**
     * Called right before your activity's option menu is displayed.
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        // Before showing the menu, we need to decide whether the clear
        // item is enabled depending on whether there is text to clear.
        menu.findItem(CLEAR_ID).setVisible(mEditor.getText().length() > 0);

        return true;
    }

    /**
     * Called when a menu item is selected.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case BACK_ID:
            finish();
            return true;
        case CLEAR_ID:
            mEditor.setText("");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A call-back for when the user presses the back button.
     */
    OnClickListener mBackListener = new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    };

    /**
     * A call-back for when the user presses the clear button.
     */
    OnClickListener mClearListener = new OnClickListener() {
        public void onClick(View v) {
            mEditor.setText("");
        }
    };
}
//
//res\layout\skeleton_activity.xml
<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText android:id="@+id/editor"
        android:layout_width="match_parent" android:layout_height="0dip"
        android:autoText="true"
        android:capitalize="sentences"
        android:layout_weight="1"
        android:freezesText="true" >
        <requestFocus />
    </EditText>


    <LinearLayout
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:background="@drawable/semi_black">

        <Button android:id="@+id/back" style="@style/ActionButton"
            android:text="@string/back" />

        <ImageView android:id="@+id/image"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingLeft="4dip" android_paddingRight="4dip"
            android:src="@drawable/violet" />

        <Button android:id="@+id/clear" style="@style/ActionButton"
            android:text="@string/clear" android:textColor="@color/red" />

    </LinearLayout>

</LinearLayout>





//
//res\values\colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Retrieved via Resources.getColor() and friends. -->
    <color name="red">#f00</color>

    <!-- Retrieved via Resources.getDrawable() and friends. -->
    <drawable name="semi_black">#80000000</drawable>
</resources>



//res\values\strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Simple strings. -->
    <string name="skeleton_app">Skeleton App</string>
    <string name="back">Back</string>
    <string name="clear">Clear</string>

    <!-- This is a complex string containing style runs. -->
    <string name="main_label">Hello <u>th<ignore>e</ignore>re</u>, <i>you</i> <b>Activity</b>!</string>
</resources>




//res\values\styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="ActionButton">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textAppearance">@style/TextAppearance.ActionButton</item>
    </style>

    <style name="TextAppearance" parent="android:TextAppearance">
    </style>

    <style name="TextAppearance.ActionButton">
        <item name="android:textStyle">italic</item>
    </style>

</resources>

This demonstrates the basic code needed to write a Screen activity

package app.test;


import android.app.Activity;
import android.os.Bundle;


/**
 * Simple example of writing an application Activity.
 * Hello World</a></h3>

<p>This demonstrates the basic code needed to write a Screen activity.</p>

<h4>Demo</h4>
App/Activity/Hello World
 
<h4>Source files</h4>
 * <table class="LinkTable">
 *         <tr>
 *             <td >src/com.example.android.apis/app/HelloWorld.java</td>
 *             <td >The Hello World Screen implementation</td>
 *         </tr>
 *         <tr>
 *             <td >/res/any/layout/hello_world.xml</td>
 *             <td >Defines contents of the screen</td>
 *         </tr>
 * </table> 
 */
public class Test extends Activity
{
  
    @Override
  protected void onCreate(Bundle savedInstanceState)
    {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
//layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="hello_world"/>

   

Example of removing yourself from the history stack after forwarding to another activity.

package app.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


/**
 * <p>Example of removing yourself from the history stack after forwarding to
 * another activity. This can be useful, for example, to implement
    a confirmation dialog before the user goes on to another activity -- once the
    user has confirmed this operation, they should not see the dialog again if they
go back from it.</p>

<p>Note that another way to implement a confirmation dialog would be as
an activity that returns a result to its caller.  Either approach can be
useful depending on how it makes sense to structure the application.</p>

<h4>Demo</h4>
App/Activity/Receive Result
 
<h4>Source files</h4>
<table class="LinkTable">
        <tr>
            <td class="LinkColumn">src/com.example.android.apis/app/Forwarding.java</td>
            <td class="DescrColumn">Forwards the user to another activity when its button is pressed</td>
        </tr>
        <tr>
            <td class="LinkColumn">/res/any/layout/forwarding.xml</td>
            <td class="DescrColumn">Defines contents of the Forwarding screen</td>
        </tr>
</table>
 */
public class Test extends Activity
{
    @Override
  protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        // Watch for button clicks.
        Button goButton = (Button)findViewById(R.id.go);
        goButton.setOnClickListener(mGoListener);
    }

    private OnClickListener mGoListener = new OnClickListener()
    {
        public void onClick(View v)
        {
       
            Intent intent = new Intent();
            intent.setClass(Test.this, ForwardTarget.class);
            startActivity(intent);
            finish();
        }
    };
}


class ForwardTarget extends Activity
{
    @Override
  protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.row);
    }
}

//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="forwarding"/>

    <Button android:id="@+id/go"
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:text="go">
        <requestFocus />
    </Button>

</LinearLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="forward_target"/>

</LinearLayout>

Fancy Blur Activity

package app.test;


import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;


/**
 * <h3>Fancy Blur Activity</h3>
 * 
 * <p>This demonstrates the how to write an activity that is translucent,
 * allowing windows underneath to show through, with a fancy blur
 * compositing effect.</p>
 */
public class Test extends Activity {

    @Override
    protected void onCreate(Bundle icicle) {
        // Be sure to call the super class.
        super.onCreate(icicle);

        // Have the system blur any windows behind this one.
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
        
        // See assets/res/any/layout/translucent_background.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.main);
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="translucent_background"/>

Example of receiving a result from another activity.

package com.example.android.apis.app;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


/**
 * Example of receiving a result from another activity.
 */
public class SendResult extends Activity
{
    /**
     * Initialization of the Activity after it is first created.  Must at least
     * call {@link android.app.Activity#setContentView setContentView()} to
     * describe what is to be displayed in the screen.
     */
    @Override
  protected void onCreate(Bundle savedInstanceState)
    {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);

        // See assets/res/any/layout/hello_world.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.send_result);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(mCorkyListener);
        button = (Button)findViewById(R.id.violet);
        button.setOnClickListener(mVioletListener);
    }

    private OnClickListener mCorkyListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished.
            setResult(RESULT_OK, (new Intent()).setAction("Corky!"));
            finish();
        }
    };

    private OnClickListener mVioletListener = new OnClickListener()
    {
        public void onClick(View v)
        {
            // To send a result, simply call setResult() before your
            // activity is finished.
            setResult(RESULT_OK, (new Intent()).setAction("Violet!"));
            finish();
        }
    };
}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent" android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="4dip"
        android:gravity="center_horizontal">

    <TextView
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="0"
            android:paddingBottom="8dip"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/pick_result"/>

    <Button android:id="@+id/corky"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="@string/corky">
            <requestFocus />
    </Button>

    <Button android:id="@+id/violet"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="@string/violet">
    </Button>

</LinearLayout>
Demonstrates required behavior of saving and restoring dynamic activity state
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

/**
 * <p>Demonstrates required behavior of saving and restoring dynamic activity
 * state, so that an activity will restart with the correct state if it is
 * stopped by the system.</p>
 *
 * <p>In general, any activity that has been paused may be stopped by the system
 * at any time if it needs more resources for the currently running activity.
 * To handle this, before being paused the
 * {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} method is called before
 * an activity is paused, allowing it to supply its current state.  If that
 * activity then needs to be stopped, upon restarting it will receive its
 * last saved state in
 * {@link android.app.Activity#onCreate}.</p>
 * <p>In this example we are currently saving and restoring the state of the
 * top text editor, but not of the bottom text editor.  You can see the difference
 * by editing the two text fields, then going to a couple different
 * applications while the demo is running and then returning back to it.  The
 * system takes care of saving a view's state as long as an id has been
 * assigned to the view, so we assign an ID to the view being saved but not
 * one to the view that isn't being saved.</p>
 * <h4>Demo</h4>
 * App/Activity/Save &amp; Restore State
 * <h4>Source files</h4>
 * <table class="LinkTable">
        <tr>
            <td class="LinkColumn">src/com.example.android.apis/app/SaveRestoreState.java</td>
            <td class="DescrColumn">The Save/Restore Screen implementation</td>
        </tr>
        <tr>
            <td class="LinkColumn">/res/any/layout/save_restore_state.xml</td>
            <td class="DescrColumn">Defines contents of the screen</td>
        </tr>
</table>
 */
public class SaveRestoreState extends Activity
{

    @Override
  protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);

        // See assets/res/any/layout/save_restore_state.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.main);

        // Set message to be appropriate for this screen.
        ((TextView)findViewById(R.id.msg)).setText("save_restore_msg");
    }

    /**
     * Retrieve the text that is currently in the "saved" editor.
     */
    CharSequence getSavedText() {
        return ((EditText)findViewById(R.id.saved)).getText();
    }

    /**
     * Change the text that is currently in the "saved" editor.
     */
    void setSavedText(CharSequence text) {
        ((EditText)findViewById(R.id.saved)).setText(text);
    }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <LinearLayout android:orientation="vertical" android:padding="4dip"
        android:layout_width="match_parent" android:layout_height="wrap_content">

        <TextView android:id="@+id/msg"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="0" android:textAppearance="?android:attr/textAppearanceMedium"
            android:paddingBottom="4dip" />

        <TextView
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="0" android:paddingBottom="4dip"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="saves_state"/>

        <EditText android:id="@+id/saved"
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="1" android:background="@drawable/icon"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="initial_text"
            android:freezesText="true">
        </EditText>

        <TextView
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="0" android:paddingTop="8dip" 
            android:paddingBottom="4dip"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="no_saves_state"/>

        <EditText
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:layout_weight="1" android:background="@drawable/icon"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="initial_text">
        </EditText>

    </LinearLayout>
</ScrollView>

Securer Activity

package com.example.android.apis.view;


import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;


import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * This view is part of the {@link SecureView} demonstration activity.
 *
 * This view is constructed in such a way as to obscure the buttons and descriptive
 * text of the activity in a poor attempt to fool the user into clicking on the buttons
 * despite the activity telling the user that they may be harmful.
 */
 class SecureViewOverlay extends ViewGroup {
    private SecureView mActivity;

    public SecureViewOverlay(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setActivityToSpoof(SecureView activity) {
        this.mActivity = activity;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        spoofLayout(findViewById(R.id.secure_view_overlay_description),
                mActivity.findViewById(R.id.secure_view_description));
        spoofLayout(findViewById(R.id.secure_view_overlay_button1),
                mActivity.findViewById(R.id.secure_view_unsecure_button));
        spoofLayout(findViewById(R.id.secure_view_overlay_button2),
                mActivity.findViewById(R.id.secure_view_builtin_secure_button));
        spoofLayout(findViewById(R.id.secure_view_overlay_button3),
                mActivity.findViewById(R.id.secure_view_custom_secure_button));
    }

    private void spoofLayout(View spoof, View original) {
        final int[] globalPos = new int[2];
        getLocationOnScreen(globalPos);
        int x = globalPos[0];
        int y = globalPos[1];

        original.getLocationOnScreen(globalPos);
        x = globalPos[0] - x;
        y = globalPos[1] - y;
        spoof.layout(x, y, x + original.getWidth(), y + original.getHeight());
    }
}

public class SecureView extends Activity {
    private int mClickCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.secure_view);

        Button toastButton = (Button) findViewById(R.id.secure_view_toast_button);
        toastButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showOverlay();
            }
        });

        Button unsecureButton = (Button) findViewById(R.id.secure_view_unsecure_button);
        setClickedAction(unsecureButton);

        Button builtinSecureButton = (Button) findViewById(R.id.secure_view_builtin_secure_button);
        setClickedAction(builtinSecureButton);

        Button customSecureButton = (Button) findViewById(R.id.secure_view_custom_secure_button);
        setClickedAction(customSecureButton);
        setTouchFilter(customSecureButton);
    }

    private void showOverlay() {
        // Generate a toast view with a special layout that will position itself right
        // on top of this view's interesting widgets.  Sneaky huh?
        SecureViewOverlay overlay = (SecureViewOverlay)
                getLayoutInflater().inflate(R.layout.secure_view_overlay, null);
        overlay.setActivityToSpoof(this);

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.FILL, 0, 0);
        toast.setView(overlay);
        toast.show();
    }

    private void setClickedAction(Button button) {
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String[] messages = getResources().getStringArray(R.array.secure_view_clicked);
                String message = messages[mClickCount++ % messages.length];

                new AlertDialog.Builder(SecureView.this)
                    .setTitle(R.string.secure_view_action_dialog_title)
                    .setMessage(message)
                    .setNeutralButton(getResources().getString(
                            R.string.secure_view_action_dialog_dismiss), null)
                    .show();
            }
        });
    }

    private void setTouchFilter(Button button) {
        button.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if ((event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        new AlertDialog.Builder(SecureView.this)
                            .setTitle(R.string.secure_view_caught_dialog_title)
                            .setMessage(R.string.secure_view_caught_dialog_message)
                            .setNeutralButton(getResources().getString(
                                    R.string.secure_view_caught_dialog_dismiss), null)
                            .show();
                    }
                    // Return true to prevent the button from processing the touch.
                    return true;
                }
                return false;
            }
        });
    }
}



//layout/secure_view.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:padding="10dip"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/secure_view_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="secure_view_description"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:textStyle="bold"
            android:text="secure_view_step1_heading"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="secure_view_step1_detail"/>

        <Button
            android:id="@+id/secure_view_toast_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="secure_view_pop_toast"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:textStyle="bold"
            android:text="secure_view_step2_heading"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="secure_view_step2_detail"/>

        <Button
            android:id="@+id/secure_view_unsecure_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="#833"
            android:text="secure_view_button"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:textStyle="bold"
            android:text="secure_view_step3_heading"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="secure_view_step3_detail"/>

        <Button
            android:id="@+id/secure_view_builtin_secure_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:filterTouchesWhenObscured="true"
            android:textColor="#833"
            android:text="secure_view_button"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:textStyle="bold"
            android:text="secure_view_step4_heading"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="secure_view_step4_detail"/>

        <Button
            android:id="@+id/secure_view_custom_secure_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textColor="#833"
            android:text="secure_view_button"/>
    </LinearLayout>
</ScrollView>

This activity is an example of a simple settings screen that has default values.

package com.example.android.apis.preference;

import com.example.android.apis.ApiDemosApplication;
import com.example.android.apis.R;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;


public class DefaultValues extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.default_values);
    }

}

//xml/default_values.xml


<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
            android:key="default_toggle"
            android:defaultValue="true"
            android:title="@string/title_checkbox_preference"
            android:summary="@string/summary_checkbox_preference" />

    <EditTextPreference
            android:key="default_edittext"
            android:defaultValue="@string/default_value_edittext_preference"
            android:title="@string/title_edittext_preference"
            android:summary="@string/summary_edittext_preference"
            android:dialogTitle="@string/dialog_title_edittext_preference" />
            
    <ListPreference
            android:key="default_list"
            android:defaultValue="@string/default_value_list_preference"
            android:title="@string/title_list_preference"
            android:summary="@string/summary_list_preference"
            android:entries="@array/entries_list_preference"
            android:entryValues="@array/entryvalues_list_preference"
            android:dialogTitle="@string/dialog_title_list_preference" />

</PreferenceScreen>

Bind Click Action Activity

     
//package com.futonredemption.volumewidget.appwidgets;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class AppWidgetUtils {

  private static final int PENDING_INTENT_FLAGS = PendingIntent.FLAG_UPDATE_CURRENT;

  public static final void BindClickAction(final Context context, final RemoteViews views, final int resId,
      final int widgetId, final Intent intent) {
    final int requestCode = generateRequestCode(resId, widgetId);
    PendingIntent pIntent = PendingIntent.getService(context, requestCode, intent, PENDING_INTENT_FLAGS);
    views.setOnClickPendingIntent(resId, pIntent);
  }

  private static int generateRequestCode(int resId, int widgetId) {
    StringBuilder sb = new StringBuilder();
    sb.append(resId);
    sb.append(" ");
    sb.append(widgetId);
    // Only needed if we have more problems with uniqueness.
    //sb.append(System.currentTimeMillis());
    return sb.toString().hashCode();
  }

  public static final void BindClickActionActivity(final Context context, final RemoteViews views, final int resId,
      final int widgetId, final Intent intent) {
    final int requestCode = generateRequestCode(resId, widgetId);
    PendingIntent pIntent = PendingIntent.getActivity(context, requestCode, intent, PENDING_INTENT_FLAGS);
    views.setOnClickPendingIntent(resId, pIntent);
  }
}

get ActivityManager

     

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;

 class Utils {

    public static ActivityManager getActivityManager(Context context)
    {
      ActivityManager result = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
      if (result == null)
        throw new UnsupportedOperationException("Could not retrieve ActivityManager");
      return result;
    }
}

forward to another Activity

     

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.Button;

class Utils {
  public static final String APP_TYPE = "APP_TYPE";

  public static <T> void forward(final Button button, final Class<T> clazz,
      final Activity activity) {
    button.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        SharedPreferences e = activity.getSharedPreferences(APP_TYPE,
            Context.MODE_PRIVATE);
        Editor edit = e.edit();
        edit.putString(APP_TYPE, button.getText().toString());
        edit.commit();

        Intent intent = new Intent();
        intent.setClass(activity, clazz);
        activity.startActivity(intent);
      }
    });
  }
}

Request window features before setContentView

     

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class Test extends Activity {
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Request window features before setContentView
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
  }
}

No code required here to attach the listener

     


package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class Test extends Activity {
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      //No code required here to attach the listener
  }

  public void onMyButtonClick(View v) {
      //Code to handle the click event
  }


}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="My Button"
  android:onClick="onMyButtonClick"
/>

Save data to Preference

     

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Email:"
    android:padding="5dip" 
  />
  <EditText
    android:id="@+id/email"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:singleLine="true"
  />
  <CheckBox
    android:id="@+id/age"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Are You Over 18?"
  />
  <TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Message:"
    android:padding="5dip" 
  />
  <EditText
    android:id="@+id/message"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:minLines="3"
    android:maxLines="3"
  />
  <Button
    android:id="@+id/submit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Submit"
  />
</LinearLayout>
package app.test;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class Test extends Activity implements View.OnClickListener {

    EditText email, message;
    CheckBox age;
    Button submit;
    
    SharedPreferences formStore;
    
    boolean submitSuccess = false;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        email = (EditText)findViewById(R.id.email);
        message = (EditText)findViewById(R.id.message);
        age = (CheckBox)findViewById(R.id.age);
        
        submit = (Button)findViewById(R.id.submit);
        submit.setOnClickListener(this);
        formStore = getPreferences(Activity.MODE_PRIVATE);
    }
    
    @Override
    public void onResume() {
        super.onResume();
        email.setText(formStore.getString("email", ""));
        message.setText(formStore.getString("message", ""));
        age.setChecked(formStore.getBoolean("age", false));
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if(submitSuccess) {
            formStore.edit().clear().commit();
        } else {
            SharedPreferences.Editor editor = formStore.edit();
            editor.putString("email", email.getText().toString());
            editor.putString("message", message.getText().toString());
            editor.putBoolean("age", age.isChecked());
            editor.commit();
        }
    }

    @Override
    public void onClick(View v) {
        submitSuccess = true;
        finish();
    }
}

Save instance state

package com.commonsware.android.rotation.one;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class RotationOneDemo extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    Button btn=(Button)findViewById(R.id.pick);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                            Contacts.CONTENT_URI);

        startActivityForResult(i, PICK_REQUEST);
      }
    });
    
    viewButton=(Button)findViewById(R.id.view);
    
    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });
    
    restoreMe(savedInstanceState);
    
    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    
    if (contact!=null) {
      outState.putString("contact", contact.toString());
    }
  }
  
  private void restoreMe(Bundle state) {
    contact=null;
    
    if (state!=null) {
      String contactUri=state.getString("contact");
      
      if (contactUri!=null) {
        contact=Uri.parse(contactUri);
      }
    }
  }
}


//res\layout\main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>




//res\layout-land\main.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"
  >
  <Button android:id="@+id/pick"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="Pick"
    android:enabled="true"
  />
  <Button android:id="@+id/view"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:text="View"
    android:enabled="false"
  />
</LinearLayout>
onRetainNonConfigurationInstance
package com.commonsware.android.rotation.two;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.view.View;
import android.widget.Button;
import android.util.Log;

public class RotationTwoDemo extends Activity {
  static final int PICK_REQUEST=1337;
  Button viewButton=null;
  Uri contact=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    Button btn=(Button)findViewById(R.id.pick);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        Intent i=new Intent(Intent.ACTION_PICK,
                            Contacts.CONTENT_URI);

        startActivityForResult(i, PICK_REQUEST);
      }
    });
    
    viewButton=(Button)findViewById(R.id.view);
    
    viewButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        startActivity(new Intent(Intent.ACTION_VIEW, contact));
      }
    });
    
    restoreMe();
    
    viewButton.setEnabled(contact!=null);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
    if (requestCode==PICK_REQUEST) {
      if (resultCode==RESULT_OK) {
        contact=data.getData();
        viewButton.setEnabled(true);
      }
    }
  }

  @Override
  public Object onRetainNonConfigurationInstance() {
    return(contact);
  }
  
  private void restoreMe() {
    contact=null;
    
    if (getLastNonConfigurationInstance()!=null) {
      contact=(Uri)getLastNonConfigurationInstance();
    }
  }
}

Create a user interface in code.

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test extends Activity {

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // Create a new TextView object
    TextView myTextView = new TextView(this);

    // Assign the TextView to be the Activity's UI
    setContentView(myTextView);

    // Update the TextView properties
    myTextView.setText("Hello, Android");
  }

}

Redirect

package app.test;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * Entry into our redirection example, describing what will happen.
 */
public class Test extends Activity {
  static final int INIT_TEXT_REQUEST = 0;
  static final int NEW_TEXT_REQUEST = 1;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    // Watch for button clicks.
    Button clearButton = (Button) findViewById(R.id.clear);
    clearButton.setOnClickListener(mClearListener);
    Button newButton = (Button) findViewById(R.id.newView);
    newButton.setOnClickListener(mNewListener);

    // Retrieve the current text preference. If there is no text
    // preference set, we need to get it from the user by invoking the
    // activity that retrieves it. To do this cleanly, we will
    // temporarily hide our own activity so it is not displayed until the
    // result is returned.
    if (!loadPrefs()) {
      Intent intent = new Intent(this, RedirectGetter.class);
      startActivityForResult(intent, INIT_TEXT_REQUEST);
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == INIT_TEXT_REQUEST) {

      // If the request was cancelled, then we are cancelled as well.
      if (resultCode == RESULT_CANCELED) {
        finish();

        // Otherwise, there now should be text... reload the prefs,
        // and show our UI. (Optionally we could verify that the text
        // is now set and exit if it isn't.)
      } else {
        loadPrefs();
      }

    } else if (requestCode == NEW_TEXT_REQUEST) {

      // In this case we are just changing the text, so if it was
      // cancelled then we can leave things as-is.
      if (resultCode != RESULT_CANCELED) {
        loadPrefs();
      }

    }
  }

  private final boolean loadPrefs() {
    // Retrieve the current redirect values.
    // NOTE: because this preference is shared between multiple
    // activities, you must be careful about when you read or write
    // it in order to keep from stepping on yourself.
    SharedPreferences preferences = getSharedPreferences("RedirectData", 0);

    mTextPref = preferences.getString("text", null);
    if (mTextPref != null) {
      TextView text = (TextView) findViewById(R.id.text);
      text.setText(mTextPref);
      return true;
    }

    return false;
  }

  private OnClickListener mClearListener = new OnClickListener() {
    public void onClick(View v) {
      // Erase the preferences and exit!
      SharedPreferences preferences = getSharedPreferences(
          "RedirectData", 0);
      preferences.edit().remove("text").commit();
      finish();
    }
  };

  private OnClickListener mNewListener = new OnClickListener() {
    public void onClick(View v) {
      // Retrieve new text preferences.
      Intent intent = new Intent(Test.this, RedirectGetter.class);
      startActivityForResult(intent, NEW_TEXT_REQUEST);
    }
  };

  private String mTextPref;
}

/**
 * Sub-activity that is executed by the redirection example when input is needed
 * from the user.
 */
class RedirectGetter extends Activity {
  private String mTextPref;
  private TextView mText;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.row);

    // Watch for button clicks.
    Button applyButton = (Button) findViewById(R.id.apply);
    applyButton.setOnClickListener(mApplyListener);

    // The text being set.
    mText = (TextView) findViewById(R.id.text);

    // Display the stored values, or if not stored initialize with an empty
    // String
    loadPrefs();
  }

  private final void loadPrefs() {
    // Retrieve the current redirect values.
    // NOTE: because this preference is shared between multiple
    // activities, you must be careful about when you read or write
    // it in order to keep from stepping on yourself.
    SharedPreferences preferences = getSharedPreferences("RedirectData", 0);

    mTextPref = preferences.getString("text", null);
    if (mTextPref != null) {
      mText.setText(mTextPref);
    } else {
      mText.setText("");
    }
  }

  private OnClickListener mApplyListener = new OnClickListener() {
    public void onClick(View v) {
      SharedPreferences preferences = getSharedPreferences(
          "RedirectData", 0);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString("text", mText.getText().toString());

      if (editor.commit()) {
        setResult(RESULT_OK);
      }

      finish();
    }
  };
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="redirect_main"/>

    <TextView android:id="@+id/text"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip" />

    <Button android:id="@+id/clear"
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:text="clear_text">
        <requestFocus />
    </Button>

    <Button android:id="@+id/newView"
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:text="new_text">
    </Button>

</LinearLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="redirect_getter"/>

    <EditText android:id="@+id/text"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip">
        <requestFocus />
    </EditText>

    <Button android:id="@+id/apply"
        android:layout_width="wrap_content" android:layout_height="wrap_content" 
        android:text="apply" />

</LinearLayout>

Demonstrates how the various soft input modes impact window resizing.

package app.test;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * Demonstrates how the various soft input modes impact window resizing.
 */
public class Test extends Activity {
    Spinner mResizeMode;
    final CharSequence[] mResizeModeLabels = new CharSequence[] {
            "Unspecified", "Resize", "Pan", "Nothing"
    };
    final int[] mResizeModeValues = new int[] {
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED,
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE,
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN,
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING,
    };
    
    /**
     * Initialization of the Activity after it is first created.  Here we use
     * {@link android.app.Activity#setContentView setContentView()} to set up
     * the Activity's content, and retrieve the EditText widget whose state we
     * will persistent.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Be sure to call the super class.
        super.onCreate(savedInstanceState);

        // See assets/res/any/layout/save_restore_state.xml for this
        // view layout definition, which is being set here as
        // the content of our screen.
        setContentView(R.layout.main);
        
        mResizeMode = (Spinner)findViewById(R.id.resize_mode);
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_item, mResizeModeLabels);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mResizeMode.setAdapter(adapter);
        mResizeMode.setSelection(0);
        mResizeMode.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) {
                        getWindow().setSoftInputMode(mResizeModeValues[position]);
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                        getWindow().setSoftInputMode(mResizeModeValues[0]);
                    }
                });
    }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:textAppearance="?android:textAppearanceMedium"
        android:text="soft_input_modes_summary"/>

    <LinearLayout android:orientation="horizontal" android:gravity="center"
        android:layout_width="match_parent" android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textAppearance="?android:textAppearanceMedium"
            android:text="soft_input_modes_label"/>

        <Spinner android:id="@+id/resize_mode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="true">
        </Spinner>

    </LinearLayout>
    
    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingBottom="6dip"
        android:background="@drawable/icon"
        android:textAppearance="?android:textAppearanceMedium"
        android:text="soft_input_modes_content"/>

    <EditText android:id="@+id/saved"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:background="@drawable/icon"
        android:text="soft_input_modes_initial_text"
        android:freezesText="true">
        <requestFocus />
    </EditText>

</LinearLayout>

extends Activity implements OnClickListener

      

import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Test extends Activity implements OnClickListener {

  Button playButton;

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

    playButton = (Button) this.findViewById(R.id.Button01);
    playButton.setOnClickListener(this);
  }

  public void onClick(View v) {
    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

    File sdcard = Environment.getExternalStorageDirectory();
    File audioFile = new File(sdcard.getPath()
        + "/Music/a");

    intent.setDataAndType(Uri.fromFile(audioFile), "audio/mp3");
    startActivity(intent);
  }
}
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:text="Play Audio" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>