您好,我正在编写一个具有数据库的 android 应用程序,该数据库允许用户通过它搜索特定事件。目前,我遇到了活动开始的问题。我正在我的 Droid Bionic 设备上测试这个应用程序,并且我正在使用 eclipse SDK 4.2 进行编程。如何开始我的活动?我是 android 新手,到目前为止我所学到的一切都是通过我自学和其他在线教程来完成的。任何帮助将不胜感激。
创建数据库的主要活动:
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.EditText;
public class MainActivity
{
EditText dEdit;
public static final String KEY_ROWID = "_id";
public static final String KEY_BUSINESS = "business";
public static final String KEY_ADDRESS = "address";
public static final String KEY_PHONE = "phone";
public static final String KEY_HOURS = "hours";
public static final String KEY_WEB = "website";
public static final String KEY_TYPE = "type";
private static final String TAG = "MainActivity";
private static final String DATABASE_NAME = "LocalDB";
private static final String DATABASE_TABLE = "Business";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table Business (_id integer primary key autoincrement, "
+ "business text not null, address text not null, phone text not null,hours text not null,website text not null,type text not null"
+ ")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase mDB;
public MainActivity(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try{
mDB=db;
mDB.execSQL(DATABASE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
try{
mDB=db;
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
mDB.execSQL("DROP TABLE IF EXISTS Business");
onCreate(mDB);
}catch (SQLException e){
e.printStackTrace();
}
}
}
//---opens the database---
public MainActivity open() throws SQLException
{
mDB = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a title into the database---
public long insertTitle(String business, String address, String phone, String hours, String website, String type)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_BUSINESS, business);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_PHONE, phone);
initialValues.put(KEY_HOURS, hours);
initialValues.put(KEY_WEB, hours);
initialValues.put(KEY_TYPE, type);
return mDB.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return mDB.delete(DATABASE_TABLE, KEY_ROWID +
"=" + rowId, null) > 0;
}
//---retrieves all the titles---
public Cursor getAllTitles()
{
return mDB.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_BUSINESS,
KEY_ADDRESS,
KEY_PHONE,
KEY_HOURS,
KEY_WEB,
KEY_TYPE},
null,
null,
null,
null,
null);
}
//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
mDB.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_BUSINESS,
KEY_ADDRESS,
KEY_PHONE,
KEY_HOURS,
KEY_WEB,
KEY_TYPE
},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a title---
public boolean updateTitle(long rowId, String business,
String address, String phone, String hours, String website, String type)
{
ContentValues args = new ContentValues();
args.put(KEY_BUSINESS, business);
args.put(KEY_ADDRESS, address);
args.put(KEY_PHONE, phone);
args.put(KEY_HOURS,hours);
args.put(KEY_WEB,website);
args.put(KEY_TYPE, type);
return mDB.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
添加到数据库的数据:
package com.example.database;
import android.app.Activity;
import android.os.Bundle;
public class DBActivity extends Activity {
//MainActivity eventsData;
//EditText output;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity db= new MainActivity(this);
//output = (EditText) findViewById(R.id.textView1);
//type.setOnClickListener(
// new OnClickListener(){
// public void onClick(View view){
// Log.v("Entry",dEdit.getText().toString());
// }
/// });
//try{String destPath="/data/data" +getPackageName()+ "/databases/BloomBusiness";
// File f = new File(destPath);
// if(!f.exists()){
// CopyDB(getBaseContext().getAssets().open("db"), new FileOutputStream(destPath));
// }
//
//
//}catch(FileNotFoundException e){
// e.printStackTrace();
//}catch(IOException e){
// e.printStackTrace();
//}
db.open();
//inserting all data
long id;
id =db.insertTitle("BloomingFoods","419 E. Kirkwood Ave. Bloomington, IN", "812-336-5300", "M-Sat:8AM-9PM Sun:9AM-8PM","http://www.bloomingfoods.coop","Grocery");
id=db.insertTitle("BloomingFoods","316 W. 6th Street Bloomington, IN", "812-333-5300", "M-Sat:7AM-10PM Sun:9AM-9PM","http://www.bloomingfoods.coop","Grocery");
id=db.insertTitle("BloomingFoods","3220 E. 3rd Street Bloomington, IN", "812-336-5300", "M-Sun:8AM-10PM","http://www.bloomingfoods.coop","Grocery");
id=db.insertTitle("The Uptown Cafe","102 E. Kirkwood Ave. Bloomington, IN", "812-339-0900", "M-Sat:8AM-9PM Sun:9AM-8PM", "http://www.the-uptown.com/","Cajun-Creole");
id=db.insertTitle("Crazy Horse","214 W. Kirkwood Ave. Bloomington, IN", "812-336-8877", "M-Sat:11AM-2AM Sun:Noon-Midnight", "http://www.crazyhorseindiana.com/","Restaurant & Live Music");
id=db.insertTitle("FARMbloomington","108 E. Kirkwood Ave. Bloomington, IN", "812-323-0002", "Tue.-Thurs.:8AM-10PM F:8AM-1AM Sat: 10AM-3AM Sun: 10AM-10PM","http://www.farm-bloomington.com","Grocery");
id=db.insertTitle("Laughing Planet","322 E. Kirkwood Ave. Bloomington, IN", "812-323-2233", "M-Sun:11AM-9PM","http://www.facebook.com/laughingplanetbtown","Burritos & Salads");
id=db.insertTitle("Soma Coffeehouse","322 E. Kirkwood Bloomington, IN", "812-331-2770", "M-Sat:7AM-11PM Sun:8AM-11PM","http://www.iheartsoma.com","Coffee House");
id=db.insertTitle("Upland Brewing Company","350 W. 11th St. Bloomington, IN", "812-336-2337", "M-Thurs:11AM-Midnight F-Sat:11AM-1AM Sun: Noon-Midnight","http://www.uplandbeer.com","Brewery & Restaraunt");
id=db.insertTitle("Nick's English Hut","423 E. Kirkwood Bloomington, IN", "812-332-4040", "M-Sat:11AM-2AM Sun: Noon-Midnight","http://www.nicksenglishhut.com","Bar & Restaraunt");
id=db.insertTitle("The Village Deli","409 E. Kirkwood Ave. Bloomington, IN", "812-336-2303", "M-F:7AM-8PM Sat-Sun 8AM-8PM","http://www.villagedeli.biz","Breakfast,Lunch,Dinner");
id=db.insertTitle("Rachael's Cafe","300 E. 3rd St. Bloomington, IN", "812-330-1882", "M-F:8AM-9PM Sat-Sun 9AM-9PM","http://www.rachaelscafe.com","Coffee House & Live Music");
id=db.insertTitle("Happy Pig","1604 W. 7th St. Bloomington, IN", "None", "W:Sample Gates Noon-3PM Thurs:Sample Gates Noon-3PM F:Atlas Bar 11:30PM-3:30AM Sat:Courthouse Square 11:30PM-3:30AM","http://www.happypigbloomington.com","BBQ Streetfood");
id=db.insertTitle("Lennie's Restaurant and Brewpub","1795 E. 10th St. Bloomington, IN", "812-323-2112", "Sun-Th:11AM-11PM F-Sat 11AM-Midnight","http://www.lenniesgourmetpizza.com","Bar & Restaurant");
id=db.insertTitle("Pizza X","1791 E. 10th St. Bloomington, IN", "812-339-7737", "Sun-Tues:11AM-2AM Wed-Thur: 11AM-3AM F-Sat:11AM-4AM","http://www.pizzaxbloomington.com","Pizza");
id=db.insertTitle("Pizza X","1610 W. 3rd St. Bloomington, IN", "812-332-2522", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
id=db.insertTitle("Pizza X","877 S. College Mall Rd. Bloomington, IN", "812-355-5000", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
}
搜索数据库:
package com.example.database;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DBUse extends Activity {
EditText dEdit;
SQLiteDatabase data;
public static final String KEY_ROWID = "_id";
public static final String KEY_BUSINESS = "business";
public static final String KEY_ADDRESS = "address";
public static final String KEY_PHONE = "phone";
public static final String KEY_HOURS = "hours";
public static final String KEY_WEB = "website";
public static final String KEY_TYPE = "type";
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity datab = new MainActivity(this);
Button buttonName =(Button)findViewById(R.id.buttonName);
buttonName.setOnClickListener(startName);
Button buttonType =(Button)findViewById(R.id.buttonType);
buttonType.setOnClickListener(startType);
dEdit =(EditText)findViewById(R.id.textView1);
datab.open();
Cursor c = datab.getAllTitles();
if((c!=null) && c.moveToFirst())
{
do{DisplayTitle(c);
}while (c.moveToNext());
}
datab.open();
Cursor b = datab.getAllTitles();
if ((b!=null) && b.moveToFirst())
DisplayTitle(b);
else
Toast.makeText(this,"No business found",Toast.LENGTH_LONG).show();
data.close();
data.close();
}
//displays the data
public void DisplayTitle(Cursor c) {
Toast.makeText(this,
"Name: " + c.getString(1)+"\n"+
"Address:" + c.getString(2)+"\n"+
"Phone:" + c.getString(3)+"\n"+
"Hours:" + c.getString(4)+"\n"+
"Website"+ c.getShort(5)+
"Type" + c.getShort(6),
Toast.LENGTH_LONG).show();
}
//Informs the user what is being searched
private OnClickListener startName=new OnClickListener(){
public void onClick (View v) {
Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where name like %"+dEdit.getText().toString()+"%", null);
String result="";
int iRow=cur.getColumnIndex(KEY_ROWID);
int iName=cur.getColumnIndex(KEY_BUSINESS);
int iAddress=cur.getColumnIndex(KEY_ADDRESS);
int iPhone=cur.getColumnIndex(KEY_PHONE);
int iHours=cur.getColumnIndex(KEY_HOURS);
int iWebsite=cur.getColumnIndex(KEY_WEB);
int iType=cur.getColumnIndex(KEY_TYPE);
Toast.makeText(DBUse.this, "Searching by Name", Toast.LENGTH_LONG).show();
// log.d("result",DBUse.getString(0));
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()){
result=result +cur.getString(iRow) + " "
+cur.getString(iName) + " "
+cur.getString(iAddress) + " "
+cur.getString(iPhone) + " "
+cur.getString(iHours) + " "
+cur.getString(iWebsite) + " "
+cur.getString(iType) + " " + "\n";
};
return;
}
};
//Informs the user what is being searched
private OnClickListener startType=new OnClickListener(){
public void onClick (View v){
Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like %"+dEdit.getText().toString()+"%", null);
String result="";
int iRow=cur.getColumnIndex(KEY_ROWID);
int iName=cur.getColumnIndex(KEY_BUSINESS);
int iAddress=cur.getColumnIndex(KEY_ADDRESS);
int iPhone=cur.getColumnIndex(KEY_PHONE);
int iHours=cur.getColumnIndex(KEY_HOURS);
int iWebsite=cur.getColumnIndex(KEY_WEB);
int iType=cur.getColumnIndex(KEY_TYPE);
Toast.makeText(DBUse.this, "Searching by Name", Toast.LENGTH_LONG).show();
// log.d("result",DBUse.getString(0));
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()){
result=result +cur.getString(iRow) + " "
+cur.getString(iName) + " "
+cur.getString(iAddress) + " "
+cur.getString(iPhone) + " "
+cur.getString(iHours) + " "
+cur.getString(iWebsite) + " "
+cur.getString(iType) + " " + "\n";
};
return;
};
};
}
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.database"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.database.DBUse"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
最后是 LogCat:
04-28 17:27:15.055: E/Trace(721): error opening trace file: No such file or directory (2)
04-28 17:27:16.124: D/dalvikvm(721): GC_FOR_ALLOC freed 47K, 2% free 10842K/11011K, paused 44ms, total 48ms
04-28 17:27:16.134: I/dalvikvm-heap(721): Grow heap (frag case) to 11.204MB for 614416-byte allocation
04-28 17:27:16.274: D/dalvikvm(721): GC_CONCURRENT freed 1K, 2% free 11441K/11655K, paused 76ms+16ms, total 141ms
04-28 17:27:16.324: D/dalvikvm(721): GC_FOR_ALLOC freed 0K, 2% free 11441K/11655K, paused 29ms, total 29ms
04-28 17:27:16.334: I/dalvikvm-heap(721): Grow heap (frag case) to 12.245MB for 1093136-byte allocation
04-28 17:27:16.474: D/dalvikvm(721): GC_CONCURRENT freed 0K, 2% free 12508K/12743K, paused 75ms+6ms, total 132ms
04-28 17:27:16.544: D/AndroidRuntime(721): Shutting down VM
04-28 17:27:16.544: W/dalvikvm(721): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-28 17:27:16.556: E/AndroidRuntime(721): FATAL EXCEPTION: main
04-28 17:27:16.556: E/AndroidRuntime(721): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database/com.example.database.DBUse}: java.lang.NullPointerException
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread.access$600(ActivityThread.java:130)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.os.Looper.loop(Looper.java:137)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-28 17:27:16.556: E/AndroidRuntime(721): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 17:27:16.556: E/AndroidRuntime(721): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 17:27:16.556: E/AndroidRuntime(721): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-28 17:27:16.556: E/AndroidRuntime(721): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-28 17:27:16.556: E/AndroidRuntime(721): at dalvik.system.NativeStart.main(Native Method)
04-28 17:27:16.556: E/AndroidRuntime(721): Caused by: java.lang.NullPointerException
04-28 17:27:16.556: E/AndroidRuntime(721): at com.example.database.DBUse.onCreate(DBUse.java:67)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.Activity.performCreate(Activity.java:5008)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
04-28 17:27:16.556: E/AndroidRuntime(721): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
04-28 17:27:16.556: E/AndroidRuntime(721): ... 11 more
04-28 17:27:18.624: I/Process(721): Sending signal. PID: 721 SIG: 9