我正在开发一个Android应用程序,它将在编辑文本中输入的用户信息作为sql参数中的参数。这方面的一个例子是,如果我输入“Business A”并单击我的一个按钮,其中显示“按名称”,它将使用“名称”列搜索数据库并显示结果。另一个按钮是“按类型”,它基本上会做同样的事情,但只有业务类型。我的代码在模拟器上运行时没有错误,并显示我的背景图像,按钮和文本。单击它将关闭应用程序。我是Android编程的新手,任何帮助或建议将不胜感激。我已将我的代码和logcat放在下面供其他人查看。
创建数据库的主要活动:
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;
}
}
有希望显示数据的地方:
public class DBUse extends Activity {
EditText dEdit;
MainActivity 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 data = 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);
data.open();
Cursor c = data.getAllTitles();
if(c.moveToFirst())
{
do{DisplayTitle(c);
}while (c.moveToNext());
}
data.open();
Cursor b = data.getAllTitles();
if (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;
}
};
};
}
最后,所有数据都来自。
package com.example.database;
import java.io.IOException;
import java.io.InputStream;
import static android.provider.BaseColumns._ID;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;
import java.io.OutputStream;
import android.database.sqlite.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
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");
id=db.insertTitle("Pizza X","2443 S. Walnut St. Pk. Bloomington, IN", "812-332-8500", "Sun-Wed:4PM-Midnight Thur: 4PM-3AM F-Sat:4PM-4AM","http://www.pizzaxbloomington.com","Pizza");
id=db.insertTitle("The Atlas Bar","209 S. College Ave. Bloomington, IN", "812-334-4435", "M-F:5PM-3AM Sat-Sun:7PM-3AM","http://www.atlasballroom.com","Bar");
id=db.insertTitle("The Bishop","123 S. Walnut St. Bloomington, IN", "812-333-4700", "Mon-Sat:7PM-3AM","http://www.thebishopbar.com","Bar & Live Music");
id=db.insertTitle("Oliver Winery","8024 N. State Road 37 Bloomington, IN", "812-876-5800", "Mon-Sat:10AM-6PM Sun: 12PM-6PM Tours:F-Sat Noon-4:30PM Sun:1PM-4:30PM","http://www.oliverwinery.com","Winery");
id=db.insertTitle("Revolution Bike and Bean","401 E. 10th St. Bloomington, IN", "812-336-0241", "Mon-Fri:10AM-6PM Sat: 10AM-5PM","http://www.revolutionbikeandbean.com","Coffee House & Bike Repair Shop");
id=db.insertTitle("Mother Hubbard's Cupboard","1010 S. Walnut Bloomington, IN", "812-355-6843", "Mon-Fri:4PM-6PM","http://www.mhcfoodpantry.org","Food Pantry Service & Non-Profit");
id=db.insertTitle("Patricia's Wellness Arts Cafe and Quilter's Comfort Teas","725 W. Kirkwood Ave. Bloomington, IN", "812-331-0886", "Mon-Sat:11AM-5PM First Friday: 11AM-8PM","http://www.hartrock.net/cafe.htm","Tea House & Holistic and Naturopathic & Reiki & Counseling");
id=db.insertTitle("One World Catering and Events","2234 W. Industrial Pk. Dr. Bloomington, IN", "812-334-3663", "","http://www.oneworldcateringandevents.com","Catering");
id=db.insertTitle("Nelson's Furniture Restoration","6573 S. Old State Road 37 Bloomington, IN", "812-824-7769", "M-F:10AM-6PM","http://www.nelsonrestoration.com","Furniture Restoration");
id=db.insertTitle("NR Hiller Design, Inc","3450 S. Garrison Chapel. Rd. Bloomington, IN", "812-825-5872", "Hours By Appointment","http://www.nrhillerdesign.com","Furniture Design & Furniture Building & Cabinet-Making & Furniture");
id=db.insertTitle("Showers Inn Bed and Breakfast","430 N. Washington St. Bloomington, IN", "812-334-9000", "Hours By Appointment","http://www.showersinn.com","Bed and Breakfast");
id=db.insertTitle("Monroe County History Center","202 E. 6th St. Bloomington, IN", "812-332-2517", "Tues-Sat:10AM-4PM","http://www.monroehistory.org","Museum");
id=db.insertTitle("WFHB","108 W. 4th St. Bloomington, IN", "812-323-0320", "Hours By Appointment","http://www.wfhb.org","Radio Station & Non-Profit");
id=db.insertTitle("Brinegar Eye Care","4001 E. 3rd St. Suite 8 Bloomington, IN", "812-339-7995", "Mon-F:9AM-5PM","http://www.brinegareyecare.com","Optometrist");
id=db.insertTitle("Sole Sensations","414 S. College Ave. Bloomington, IN", "812-331-1962", "Mon:10AM-6PM Tues:10AM-8PM Wed:10AM-6PM Thurs:10AM-8PM Sat:10AM-5PM","http://www.solesensations.com/Soul-Inspirations.html","Orthotics & Shoes");
id=db.insertTitle("Bloomignton Area Birth Services (BABS)","2458 S. Walnut St. Bloomington, IN", "812-337-8121", "Mon-Fri:10AM-5PM Sat:10AM-2PM" ,"http://www.bloomingtonbirth.org","Holistic and Naturopathic & Non-Profit & Gifts & Toys & Books & Maternity/Nursing Wear & Prenatal and Postnatal Yoga & Childbirth Classes & Breastfeeding Classes and Consultation");
id=db.insertTitle("Karen Knight, LMHC Counseling Services","115 N. College Ave Suite 214 Bloomington, IN", "812-361-3601", "Mon-Fri:9AM-8PM By Appointment" ,"http://www.karenknight.net","Mental Health & Counseling");
id=db.insertTitle("Mister Buck's Genuinely Good Pet Food Compnay","319 S. Mitchell Bloomington, IN", "812-384-3853", "24hr Internet Access" ,"http://www.mrbuckspetfood.com","Pet Care");
id=db.insertTitle("Center for Sustainable Living","323 S. Walnut St. Bloomington, IN", "812-332-8796", "24hr Internet Access" ,"http://www.simplycsl.org","Non-Profit");
id=db.insertTitle("Friends of Art Bookshop","1201 E. 7th St. (Fine Arts Building, Indiana University) Bloomington, IN", "812-855-7498","M-Thurs:9AM-6PM Sat-Sun:1PM-5PM" ,"http://www.fa.indiana.edu/foart/","Non-Profit & Books & Art Books & Textbooks");
id=db.insertTitle("Cardinal Stage Company","900 S. Walnut St. Bloomington, IN", "812-323-3020", "24hr Internet Access" ,"http://www.cardinalstage.org","Non-Profit & Theater");
id=db.insertTitle("Bloomington Playwrights Project","107 W. 9th St. Bloomington, IN", "812-334-1188", "Mon-Fri:9AM-5PM" ,"http://www.newplays.org","Non-Profit");
id=db.insertTitle("Boxcar Books","408 E. 6th St. Bloomington, IN", "812-339-8710", "Mon-Fri: 11AM-9PM Sat:10AM-9PM Sun:10AM-5PM" ,"http://www.boxcarbooks.org","Non-Profit & Books & Textbooks");
id=db.insertTitle("Community Foundation of Bloomington and Monroe County,Inc.","101 W. Kirkwood Ave. Suite 321 Bloomington, IN", "812-333-9016", "Mon-Fri:8:30AM-5PM" ,"http://www.cfbmc.org","Non-Profit");
id=db.insertTitle("Windfall Dancers","1101 N. Dunn St. Bloomington, IN", "812-334-0506", "24hr Internet Access" ,"http://www.windfalldancers.org","Non-Profit & Modern Dance & Dance");
id=db.insertTitle("The Updraft Supplementary Scholarship Project, Inc. (USSP)","403 E. 6th St. Bloomington, IN", "812-961-3553 Toll Free:877-451-8535", "Mon-Fri:9AM-5PM" ,"http://www.usspkids.org","Non-Profit");
id=db.insertTitle("Story Insights","P.O. Box 2264. Bloomington, IN 47402", "812-340-0479", "24hrs" ,"http://storyinsights.com","Non-Profit & Story Development & Project Management & Web Design");
id=db.insertTitle("Middle Way House","P.O. Box 95 Bloomington, IN 47402", "Administration:812-333-7404 Crisis Line:812-336-9063", "24hr Internet Access" ,"http://www.middlewayhouse.org","Non-Profit");
id=db.insertTitle("Baugh Enterprises, Inc","1611 S Rogers St. Bloomington, IN", "812-334-8189", "Mon-Fri:8:30AM-5PM" ,"http://www.baughenterprises.com","Printing Service & Printwork Design");
id=db.insertTitle("White Rabbit","118 W. 6th St. Bloomington, IN", "812-339-5020 Fax:812-339-7847", "Mon-Fri:8:30AM-5PM" ,"http://www.whiterabbitcopyservice.com","Printing Service");
id=db.insertTitle("Mr. Copy","501 E. 10th St. Bloomington, IN", "812-334-2679", "Mon-Fri:9AM-6PM Sat: Noon-5PM" ,"http://www.copysales.com","Printing Service & Graphic Design");
id=db.insertTitle("Rosenplot Design","P.O Box 1083 Bloomington, IN 47402", "812-822-2077 Fax:812-822-2077", "Mon-Fri:8:30AM-5PM" ,"http://www.rosenplotdesign.com","Graphic Design");
id=db.insertTitle("Patrick Siney Art Direction and Design","1303 S. Stull Ave. Bloomington, IN", "812-334-0019", "Mon-Fri:8:30AM-5PM" ,"http://www.patricksiney.com","Graphic Design & Web Design");
id=db.insertTitle("Bloomington Cooking School","115 N. College Ave. Suite 014 Bloomington, IN ", "812-333-7100", "Mon-Fri:8:30AM-5PM" ,"http://www.bloomingtoncookingschool.com","Cooking Class");
}
//private void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {
// // TODO Auto-generated method stub
// byte[] buffer=new byte[1024];
// int length;
// while((length=inputStream.read(buffer))>0){
// outputStream.write(buffer,0,length);
// }
// inputStream.close();
// outputStream.close();
//}
}
经过一些编辑后,我现在收到logcat
中显示的错误 04-26 07:12:49.949: I/Process(18874): Sending signal. PID: 18874 SIG: 9
04-26 07:12:54.070: D/dalvikvm(19443): GC_FOR_ALLOC freed 61K, 2% free 10842K/11011K, paused 50ms, total 52ms
04-26 07:12:54.070: I/dalvikvm-heap(19443): Grow heap (frag case) to 11.203MB for 614416-byte allocation
04-26 07:12:54.220: D/dalvikvm(19443): GC_CONCURRENT freed 1K, 2% free 11440K/11655K, paused 82ms+17ms, total 148ms
04-26 07:12:54.280: D/dalvikvm(19443): GC_FOR_ALLOC freed 0K, 2% free 11440K/11655K, paused 33ms, total 33ms
04-26 07:12:54.300: I/dalvikvm-heap(19443): Grow heap (frag case) to 12.245MB for 1093136-byte allocation
04-26 07:12:54.440: D/dalvikvm(19443): GC_CONCURRENT freed 0K, 2% free 12508K/12743K, paused 74ms+15ms, total 141ms
04-26 07:12:55.160: D/gralloc_goldfish(19443): Emulator without GPU emulation detected.
04-26 07:13:00.769: D/AndroidRuntime(19443): Shutting down VM
04-26 07:13:00.769: W/dalvikvm(19443): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-26 09:12:27.900: E/AndroidRuntime(3962): FATAL EXCEPTION: main
04-26 09:12:27.900: E/AndroidRuntime(3962): java.lang.NullPointerException
04-26 09:12:27.900: E/AndroidRuntime(3962): at com.example.database.DBUse$2.onClick(DBUse.java:123)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.view.View.performClick(View.java:4084)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.view.View$PerformClick.run(View.java:16966)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.os.Handler.handleCallback(Handler.java:615)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.os.Handler.dispatchMessage(Handler.java:92)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.os.Looper.loop(Looper.java:137)
04-26 09:12:27.900: E/AndroidRuntime(3962): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-26 09:12:27.900: E/AndroidRuntime(3962): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 09:12:27.900: E/AndroidRuntime(3962): at java.lang.reflect.Method.invoke(Method.java:511)
04-26 09:12:27.900: E/AndroidRuntime(3962): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-26 09:12:27.900: E/AndroidRuntime(3962): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-26 09:12:27.900: E/AndroidRuntime(3962): at dalvik.system.NativeStart.main(Native Method)
这就是我的问题,现在它说MainActivity未定义rawQuery这是否意味着我需要使用变量SQLiteDatabase?代码如下:
Cursor cur=data.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like %"+dEdit.getText().toString()+"%", null);
答案 0 :(得分:1)
在onClick()函数中看起来像db是null。另外,为什么两次使用相同的变量名,一个用于SQLiteDatabase,另一个用于MainActivity。
答案 1 :(得分:1)
检查logcat时,你有这个:
04-26 09:12:27.900: E/AndroidRuntime(3962): FATAL EXCEPTION: main
04-26 09:12:27.900: E/AndroidRuntime(3962): java.lang.NullPointerException
04-26 09:12:27.900: E/AndroidRuntime(3962): at com.example.database.DBUse$2.onClick(DBUse.java:123)
转到DBUse的第123行,然后对其进行调试。发生的事情就是在这一行上你有一个实例调用一个方法(例如db.rawQuery
)并且该实例为null。在这个例子中db。
如果仍然无法找到问题,请在帖子的第123行发布内容
如果这是你的行
Cursor cur=db.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like %"+dEdit.getText().toString()+"%", null);
那么不应为空的db
或dEdit
或dEdit.getText()
我没有看到代码中db
的初始化位置。我认为这是问题
解决方案的步骤:
将private SQLiteDatabase db;
重命名为private SQLiteDatabase mDB;
(这样您就可以将其与其他变量区分开来)
将DataHelper的OnCreate更改为此
@Override
public void onCreate(SQLiteDatabase db)
{
try{
mDb = db;
mDb.execSQL(DATABASE_CREATE);
} catch(SQLException e){
e.printStackTrace();
}
}
(升级做同样的事情)
并且其他地方都使用mDb而不是db。
(也改变了MainActivity db
的名称,令人困惑)