2012-12-03 95 views
0

我想與我的應用程序建立數據庫連接。它爲訪客提供了允許和拒絕按鈕。每當我嘗試調用數據庫類的操作時,我的app force都會關閉。例如,當我單擊「允許」按鈕時,我希望應用程序將訪問者ID,日期和字符串響應存儲在數據庫中。 以下是在我的按鈕在MainActivity代碼:Android應用程序強制關閉數據庫連接嘗試

//databaseVisitor VisDB = new databaseVisitor (this); 
//VisitorDatabase VDB = new VisitorDatabase(); 
//Defining the actions of the Allow Button 

Button.OnClickListener allowListener = new Button.OnClickListener(){ 
    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 

     Toast allowToast = Toast.makeText(MainActivity.this, R.string.toastYes, Toast.LENGTH_LONG); 
     allowToast.show(); 

     //Log.d("Insert Log: ", "Inserting add log.."); 
     //count = VisDB.getVisitorCount(); 
     response = "Access Granted"; 
     //dt = date.getDate(); 

     //VisDB.addVisitor(new VisitorDatabase(count+1, dt, response)); 

    } 
}; 
+1

發佈您的LogCat錯誤,以便我們可以看到發生了什麼。 – Sam

+0

嗨,@Marcin捷克第一評論! – Ascension

+0

@Sam:這些是我得到的Logcat錯誤。 12-03 13:03:57.467:E/AndroidRuntime(283):致命異常:主 12-03 13:03:57.467:E/AndroidRuntime(283):java.lang.RuntimeException:無法啓動活動ComponentInfo { com.example.imagefetch/com.example.imagefetch.MainActivity}:java.lang.NullPointerException 12-03 13:03:57.467:E/AndroidRuntime(283):\t at android.app.ActivityThread.performLaunchActivity(ActivityThread.java :2663) 12-03 13:03:57.467:E/AndroidRuntime(283):\t at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) – pointNclick

回答

2

其最可能是因爲您在關閉遊標

cursor.close() 

,然後在其上

return cursor.getCount() 
使操作

請嘗試像這樣的smthg

int count = cursor.getCount(); 
cursor.close(); 
return count; 

編輯:

,並作爲VisDB那樣做

... 
databaseVisitor VisDB; 
... 
public void onCreate(Bundle savedInstanceState) { 
     ... 
     VisDB = new databaseVisitor (this); 
     ... 
} 
+0

謝謝,但是現在計數能夠工作,儘管我嘗試運行以下兩個語句之一,但仍然強制關閉。 (); // dt = date.getDate(); //VisDB.addVisitor(new VisitorDatabase(count + 1,dt,response)); 任何想法爲什麼是這樣?感謝您的幫助。 .Date獲得getDate()方法,而變量dt的類型爲int。所有變量都在主活動中聲明,但不在OnCreate類中,因爲當我嘗試這樣做時,它會給出一個錯誤,說「不能引用內部非最終變量類以不同方法定義「。 – pointNclick

+0

最好是問一個新的問題,並提供logcat堆棧來分析。你是否嘗試將變量聲明爲final? – AndroidGecko

+0

我宣佈visdb爲final。你是指另一個變量? – pointNclick

1

你給getCount將之前關閉光標()。 試試這個:

int count = cursor.getCount(); 
cursor.close(); 
return count; 

祝你好運!