Reputation: 15552
Today i try to learn android sdk, but experience a very strange problem.
Below is the code of :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete_test);
Cursor cur = getBrowserData(); //Return an amount of data in cursor type.
UrlAdapter adapter = new UrlAdapter(AutoCompleteTest.this, cur);
//cur.close(); uncomment this, data will gone.
AutoCompleteTextView txtUrl = (AutoCompleteTextView) this.findViewById(R.id.txtUrl);
txtUrl.setAdapter(adapter);
}
The problem is on the line : cur.close(); UrlAdapter is custom class to fill the Cursor to adapter, and bind to AutoCompleteTextView.
On above, after i fill the cur (Cursor) to adapter, i close the cur for resource saving. However, after i close the cur, it affect the adapter.
The AutoComplete
list will be nothing.
But it don't happen on C#
,
Just like i fill DataTable
to DataAdaptor
, and Dispose()
the DataTable
, the dataon DataAdaptor will be preserve.
Upvotes: 0
Views: 124
Reputation: 8473
What Egor says is absolutely right. Also you need to optimize your code little more like below:
try {
Cursor cur = getBrowserData(); //Return an amount of data in cursor type.
UrlAdapter adapter = new UrlAdapter(AutoCompleteTest.this, cur);
AutoCompleteTextView txtUrl = (AutoCompleteTextView) this.findViewById(R.id.txtUrl);
txtUrl.setAdapter(adapter);
} catch(Exception ex) {
// Log the exception's message or whatever you like
Log.e("Exception", ex.getMessage());
} finally {
try {
if( cur != null && !cursor.isClosed )
cur .close();
} catch(Exception ex) {Log.e("Exception", ex.getMessage());}
}
Upvotes: 1
Reputation: 40193
You're passing the Cursor
by reference, so there's a single instance of Cursor
both in Adapter
and in Activity
. So once you closed the Cursor
in Activity
, you can't continue using it in the Adapter
. So close it only when you're sure you don't need it again. Another problem with your code is that making database calls on the main thread is prohibited, try to rewrite your code using AsyncTask
or Loader
.
Upvotes: 4