Life cycle : Activity « UI « Android






Life cycle

     


/*
Welcome to the source code for Android Programming Tutorials (http://commonsware.com/AndTutorials)!

Specifically, this is for Version 3.2 and above of this book.
For the source code for older versions of this book, please
visit:

https://github.com/commonsguy/cw-andtutorials

All of the source code in this archive is licensed under the
Apache 2.0 license except as noted.

The names of the top-level directories roughly correspond to a
shortened form of the chapter titles. Since chapter numbers
change with every release, and since some samples are used by
multiple chapters, I am loathe to put chapter numbers in the
actual directory names.

If you wish to use this code, bear in mind a few things:

* The projects are set up to be built by Ant, not by Eclipse.
  If you wish to use the code with Eclipse, you will need to
  create a suitable Android Eclipse project and import the
  code and other assets.

* You should delete build.xml from the project, then run

    android update project -p ...
  (where ... is the path to a project of interest)

  on those projects you wish to use, so the build files are
  updated for your Android SDK version.

*/

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>

   
    
    
    
    
  








Related examples in the same category

1.Backup Activity
2.Notification Activity
3.Timing Activity
4.Set content view from xml for Activity
5.More than one Activity
6.Find user control by using findViewById
7.A Simple Form
8.Link form with POJO
9.Comparing Android UI Elements to Swing UI Elements
10.add android:background = "#FFFF0000"
11.Rotation demo
12.Set activity screen Orientation
13.Check activity result
14.Activity lifecycle event
15.Activity key event
16.Allows the activity to manage the Cursor's lifecyle based on the activity’s lifecycle---
17.Activity configuration changed event
18.Check Activity result and onActivityResult
19.Phone Call Activity
20.Using Media Store Activity
21.External Storage Activity
22.Making Activity Go Full-Screen
23.Surface View Test Activity
24.Widget Preview Activity
25.This class provides a basic demonstration of how to write an Android activity.
26.This demonstrates the basic code needed to write a Screen activity
27.Example of removing yourself from the history stack after forwarding to another activity.
28.Fancy Blur Activity
29.Example of receiving a result from another activity.
30.Demonstrates required behavior of saving and restoring dynamic activity state
31.Securer Activity
32.This activity is an example of a simple settings screen that has default values.
33.Bind Click Action Activity
34.get ActivityManager
35.forward to another Activity
36.Request window features before setContentView
37.No code required here to attach the listener
38.Save data to Preference
39.Save instance state
40.onRetainNonConfigurationInstance
41.Create a user interface in code.
42.Redirect
43.Demonstrates how the various soft input modes impact window resizing.
44.extends Activity implements OnClickListener