Activity的使用(四):两个activity的交互

本文介绍了一个名为LunchList的应用程序如何通过自定义SQLiteOpenHelper子类来管理和操作餐厅信息数据库。文章详细展示了如何创建数据库表、插入和更新数据、查询特定记录以及使用CursorAdapter进行数据展示的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LunchList中用到数据库,首先创建一个数据库类,要继承SQLiteOpenHelper,要重载onCreate和onUpgrade的方法:

package com.example.activity_and_service;

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;

public 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);
	}
	
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
	}
	
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		
	}
	
	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);
	}
}

在 LunchList中用到CursorAdapter,自定义个继承CursorAdapter的内部类:

package com.example.activity_and_service;

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;
import android.util.Log;

public class LunchList extends ListActivity {
	public final static String ID_EXTRA = "apt.tutorial._ID";
	
	Cursor model = null;
	RestaurantAdapter adapter = null;
	RestaurantHelper helper = null;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		helper = new RestaurantHelper(this);
		//Log.d("onCreate", "" + helper);
		model = helper.getAll();
		startManagingCursor(model);
		adapter = new RestaurantAdapter(model);
		
		setListAdapter(adapter);
		
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		Log.d("test", "" + helper);
		helper.close();
	}
	
	public void onListItemClick(ListView list, View view, int position, long id)
	{
		Intent i = new Intent(LunchList.this, MainActivity.class);
		i.putExtra(ID_EXTRA, String.valueOf(id));
		
		startActivity(i);
	}
	
	public boolean onCreateOptionsMenu(Menu menu)
	{
		new MenuInflater(this).inflate(R.menu.option, menu);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.add) {
			startActivity(new Intent(LunchList.this, MainActivity.class));
			
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	class RestaurantAdapter extends CursorAdapter
	{
		RestaurantAdapter(Cursor c)
		{
			super(LunchList.this, c);
		}
		
		public void bindView(View row, Context context, Cursor c)
		{
			RestaurantHolder holder = (RestaurantHolder)row.getTag();
			
			holder.populateFrom(c, helper);
		}
		
		public View newView(Context context, 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)
		{
			//Log.d("populateFrom", "cursor:" + c);
			try {
			name.setText(helper.getName(c));
			address.setText(helper.getAddress(c));
			
			if ("sit_down".equals(helper.getType(c))) {
				icon.setImageResource(R.drawable.bg_video);
			} else if ("take_out".equals(helper.getType(c))) {
				icon.setImageResource(R.drawable.bg_video);
			}
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}

当中用到两个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"/>

<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>

MainActivity类中主要是显示单项信息:

package com.example.activity_and_service;

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

public class MainActivity extends Activity  {

  EditText name = null;
  EditText address = null;
  EditText notes = null;
  RadioGroup types = null;
  String restaurantId = null;
  RestaurantHelper helper = null;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      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();
  }
  
  public void onDestroy()
  {
	  super.onDestroy();
	  
	  helper.close();
  }
  
  public 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 ("sit_down".equals(helper.getType(c))) {
		  types.check(R.id.sit_down);
	  } else if ("take_out".equals(helper.getType(c))) {
		  types.check(R.id.take_out);
	  } else {
		  types.check(R.id.delivery);
	  }
  }
  
  private View.OnClickListener onSave = new View.OnClickListener() {
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		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();
	}
};
}

其对应的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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值