//packages
//imports
public class MainActivity extends Activity
{
// some string declarations;
// object creations etc etc
DatabaseManipulation dbManage = new DatabaseManipulation();//whereDatabaseManipulation is a class bdManage -->object
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//creating contentViews;
}
public void methods()
{
//works
}
public void methods2(String name)
{
try{
dbManage.functioncall(name);
}
catch(Exception e)
{
System.out.println(e);// value of e is NullPointerException
}
}
}
第二类是DatabaseManipulation.class,如下所示
public class DatabaseManipulation extends Activity
{
public void functioncall(String name)
{
System.out.println(bookName+ " bookname in addBookmark");
SQLiteDatabase db;
db = openOrCreateDatabase("epub.db", SQLiteDatabase.CREATE_IF_NECESSARY,null);// error occurs here
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.setVersion(1);
String temp_address="nothing";
try
{
String selectQuery = "SELECT lastchapter FROM Bookdetails WHERE bookpath=?";
Cursor c = db.rawQuery(selectQuery, new String[] { name });
if (c.moveToFirst()) {
temp_address = c.getString(c.getColumnIndex("lastchapter")); // assigning value in lastchapter to temp_address
}
System.out.println(temp_address+" result of select Query"); //
}
catch(Exception e)
{
System.out.println(e);
}
try
{
System.out.println("BLOW FILE111");
System.out.println("BLOW FILE222");
final String createtabBook="CREATE TABLE IF NOT EXISTS BookMark(lid INTEGER UNIQUE AUTOINCREMENT, bookpath TEXT , lastchapter TEXT, PRIMARY KEY(bookpath,lastchapter));";
db.execSQL(createtabBook);
ContentValues val=new ContentValues();
val.put("bookpath",name );
val.put("lastchapter", temp_address);
db.insert("Bookdetails", val, "bookpath="+name, null);
System.out.println("BLOW FILE333");
}
catch(Exception e)
{
System.out.println(e+" errors happens");
}
finally
{
db.close();
}
}
}
我只是想从main活动到DatabaseManipulation.java调用这个函数,我做错了什么? 在log cat中,Null指针异常显示为错误,因为我在try catch中调用它 我们真的可以做这种类型的函数调用吗?请帮忙
答案 0 :(得分:4)
您无法实例化此类活动:
DatabaseManipulation dbManage = new DatabaseManipulation();
您需要使用Intent。像这样:
Intent intent = new Intent(this, DatabaseManipulation.class);
startActivity(intent);
答案 1 :(得分:1)
您无法在
之前初始化数据库类super.onCreate(savedInstanceState);
方法。为您的数据库类创建全局变量
DatabaseManipulation dbManage;
并在
之后的onCreate()方法之后初始化它setContentView(R.layout.urlayout)
方法
dbManage = new DatabaseManipulation();