我按照我的first answered post發佈。Android Studio,Sql,TextView
經過測試並添加了建議的修改後,我仍然無法讓我的代碼正常工作。每次我重新開始tuto,然後嘗試添加我的代碼,然後失敗。
如果你能改正我或指出我錯過了這一點,那將會很棒。
這工作得很好:
在MyActivity.java有一個可點擊按鈕
/** Called when the user clicks the Send button */
public void goExample(View view) {
Intent intent = new Intent(this, Example.class);
startActivity(intent);
}
這使類實例:
public class Example extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView total = (TextView)findViewById(R.id.total);
setContentView(R.layout.example);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}}
隨着其觀點的example.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Example">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+android:id/total"
android:layout_weight="1" />
</RelativeLayout>
沒有問題,直到我嘗試添加自己的代碼(如下):
public class Example extends MyActivity {
private TaskDBHelper helper;
public int getContactsCount() {
helper = new TaskDBHelper(Example.this);
SQLiteDatabase db = helper.getReadableDatabase();
String countQuery = "SELECT * FROM " + Playas.TABLE;
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public static void main(String[] args) {
Example example = new Example();
int a = example.getContactsCount();
System.out.println(a);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView total = (TextView)findViewById(R.id.total);
total.setText(String.valueOf(getContactsCount()));
setContentView(R.layout.example);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
然後悲慘的失敗,與以下錯誤:
6715-6715/tab.sqltesting.com.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{tab.sqltesting.com.myapplication/tab.sqltesting.com.myapplication.Example}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM joueurs
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at dalvik.system.NativeStart.main(Native Method)
...
Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM joueurs
at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:58)
老實說,我不知道做什麼,任何幫助將不勝感激......
感謝