我正在编写一个Android应用程序,允许用户在数据库中搜索并根据搜索结果查看数据库中的结果。目前我收到一个NullPointerException并且我不确定如何解决这个问题因为我已经尝试了很多东西以确保光标不为空这些抛出错误的行在它们前面有(*)..我的代码列在下面以及logcat中。 。我正在使用eclipse sdk 4.2并在我的Motorola Droid Bionic和模拟器上进行测试。我是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;
import android.widget.Toast;
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 = 2;
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 Cursor getBusinessInfo(String name) {
// TODO Auto-generated method stub
return mDB.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where name like ?", new String[]{"%"+name+"%"});
}
public Cursor getBusinessType(String type) {
// TODO Auto-generated method stub
return mDB.rawQuery("SELECT business,address,phone,hours,website,type FROM Business where type like ?", new String[]{"%"+type+"%"});
}
}
在DB中进行搜索的地方:
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();
}
//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.getBusinessInfo(dEdit.getText().toString());
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";
Toast.makeText(DBUse.this, result, Toast.LENGTH_LONG).show();
};
return;
}
};
//Informs the user what is being searched
private OnClickListener startType=new OnClickListener(){
public void onClick (View v){
Cursor cur=data.getBusinessType(dEdit.getText().toString());
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";
Toast.makeText(DBUse.this, result, Toast.LENGTH_LONG).show();
};
return;
};
};
}
数据的来源: package com.example.database; import android.app.Activity; import android.os.Bundle; 公共类DBActivity扩展Activity { // MainActivity eventsData; // EditText输出; @覆盖 public void onCreate(Bundle savedInstanceState){ // TODO自动生成的方法存根 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");
}
logcat的:
04-28 18:06:32.648: E/Trace(692): error opening trace file: No such file or directory (2)
04-28 18:06:33.160: D/dalvikvm(692): GC_FOR_ALLOC freed 40K, 2% free 10842K/11011K, paused 44ms, total 46ms
04-28 18:06:33.160: I/dalvikvm-heap(692): Grow heap (frag case) to 11.204MB for 614416-byte allocation
04-28 18:06:33.298: D/dalvikvm(692): GC_CONCURRENT freed 1K, 2% free 11441K/11655K, paused 88ms+4ms, total 135ms
04-28 18:06:33.368: D/dalvikvm(692): GC_FOR_ALLOC freed 0K, 2% free 11441K/11655K, paused 28ms, total 28ms
04-28 18:06:33.381: I/dalvikvm-heap(692): Grow heap (frag case) to 12.245MB for 1093136-byte allocation
04-28 18:06:33.498: D/dalvikvm(692): GC_CONCURRENT freed 0K, 2% free 12508K/12743K, paused 76ms+7ms, total 126ms
04-28 18:06:34.188: D/gralloc_goldfish(692): Emulator without GPU emulation detected.
04-28 18:07:12.528: D/AndroidRuntime(692): Shutting down VM
04-28 18:07:12.528: W/dalvikvm(692): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-28 18:07:12.542: E/AndroidRuntime(692): FATAL EXCEPTION: main
04-28 18:07:12.542: E/AndroidRuntime(692): java.lang.NullPointerException
04-28 18:07:12.542: E/AndroidRuntime(692): at com.example.database.DBUse$2.onClick(DBUse.java:123)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.view.View.performClick(View.java:4084)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.view.View$PerformClick.run(View.java:16966)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.os.Handler.handleCallback(Handler.java:615)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.os.Handler.dispatchMessage(Handler.java:92)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.os.Looper.loop(Looper.java:137)
04-28 18:07:12.542: E/AndroidRuntime(692): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-28 18:07:12.542: E/AndroidRuntime(692): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 18:07:12.542: E/AndroidRuntime(692): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 18:07:12.542: E/AndroidRuntime(692): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-28 18:07:12.542: E/AndroidRuntime(692): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-28 18:07:12.542: E/AndroidRuntime(692): at dalvik.system.NativeStart.main(Native Method)
04-28 18:07:14.911: I/Process(692): Sending signal. PID: 692 SIG: 9
04-28 18:10:06.128: E/Trace(711): error opening trace file: No such file or directory (2)
04-28 18:10:07.179: D/dalvikvm(711): GC_FOR_ALLOC freed 43K, 2% free 10842K/11011K, paused 70ms, total 71ms
04-28 18:10:07.188: I/dalvikvm-heap(711): Grow heap (frag case) to 11.204MB for 614416-byte allocation
04-28 18:10:07.258: D/dalvikvm(711): GC_CONCURRENT freed 1K, 2% free 11441K/11655K, paused 28ms+14ms, total 71ms
04-28 18:10:07.318: D/dalvikvm(711): GC_FOR_ALLOC freed 0K, 2% free 11441K/11655K, paused 26ms, total 26ms
04-28 18:10:07.330: I/dalvikvm-heap(711): Grow heap (frag case) to 12.245MB for 1093136-byte allocation
04-28 18:10:07.461: D/dalvikvm(711): GC_CONCURRENT freed 0K, 2% free 12508K/12743K, paused 26ms+4ms, total 129ms
04-28 18:10:07.461: D/dalvikvm(711): WAIT_FOR_CONCURRENT_GC blocked 12ms
04-28 18:10:08.179: D/gralloc_goldfish(711): Emulator without GPU emulation detected.
04-28 18:10:30.158: D/AndroidRuntime(711): Shutting down VM
04-28 18:10:30.158: W/dalvikvm(711): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
04-28 18:10:30.168: E/AndroidRuntime(711): FATAL EXCEPTION: main
04-28 18:10:30.168: E/AndroidRuntime(711): java.lang.NullPointerException
04-28 18:10:30.168: E/AndroidRuntime(711): at com.example.database.DBUse$1.onClick(DBUse.java:94)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.view.View.performClick(View.java:4084)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.view.View$PerformClick.run(View.java:16966)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.os.Handler.handleCallback(Handler.java:615)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.os.Handler.dispatchMessage(Handler.java:92)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.os.Looper.loop(Looper.java:137)
04-28 18:10:30.168: E/AndroidRuntime(711): at android.app.ActivityThread.main(ActivityThread.java:4745)
04-28 18:10:30.168: E/AndroidRuntime(711): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 18:10:30.168: E/AndroidRuntime(711): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 18:10:30.168: E/AndroidRuntime(711): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-28 18:10:30.168: E/AndroidRuntime(711): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-28 18:10:30.168: E/AndroidRuntime(711): at dalvik.system.NativeStart.main(Native Method)
04-28 18:10:32.229: I/Process(711): Sending signal. PID: 711 SIG: 9
答案 0 :(得分:0)
在MainActivity中创建方法
public Cursor getBusinessInfo(String name) {
return mDb.rawQuery("SELECT business,address,phone,hours,website,type FROM Business
where name like ?", new String[]{"%"+name+"%"});
并在onClick
//Informs the user what is being searched
private OnClickListener startName=new OnClickListener(){
public void onClick (View v) {
Cursor cur=data.getBusinessInfo(dEdit.getText().toString());
String result="";
int iRow=cur.getColumnIndex(KEY_ROWID);
.....................
而不是SQLiteDatabase data;
更改为MainActivity data;
并改变onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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());
}
Cursor b = data.getAllTitles();
if (b.moveToFirst())
DisplayTitle(b);
else
Toast.makeText(this,"No business found",Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
在DBUse中,每次打开时都尝试显式调用Cursor.close()。你打开了几个游标,并且不能保证垃圾收集能够及时清理它们。
这可能不会这样做,但它可能会消除一种可能性。