android simplecursoradapter errors out every time - android

I'm stuck trying to create a simple cursor adapter. I've checked every website I can find, and all the threads here and I just can't see what's wrong.
gcDBAssist dbHelper;
SQLiteDatabase db;
Cursor cursor;
String display;
String TAG = "Listing the database";
ListView listTimeline;
SimpleCursorAdapter adapter;
static final String[] FROM = { gcDBAssist.C_ID, gcDBAssist.C_TIME, gcDBAssist.C_SCORE, gcDBAssist.C_LEVEL, gcDBAssist.C_POSTED, gcDBAssist.C_USER };
static final int[] TO = { R.id.textID, R.id.textTime, R.id.textScore, R.id.textLevel, R.id.textPosted, R.id.textUser };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_list);
listTimeline = (ListView) findViewById(R.id.listTimeline);
dbHelper = new gcDBAssist(this);
db = dbHelper.getReadableDatabase();
}
#Override
protected void onResume() {
super.onResume();
//get the data
cursor = db.rawQuery("SELECT * from " +gcDBAssist.TABLE, null);
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, FROM, TO, 0);
listTimeline.setAdapter(adapter);
I've run some checks and I can access the database using a while(cursor.moveToNext()).

Related

Android onListItemClick exception: "java.lang.String cannot be cast to android.database.Cursor"

As title says, it get this exception from the code I pasted below. I tried to make it work both with the uncommented code and also with the commented part insted of the IF block just before it.
The error I get is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor which I don't understand, since the item in the listview should exactly be a String! Any idea?
public class ListScoutActivity extends ListActivity {
private DBHelper database;
private ListView listav;
private Cursor cursor;
ArrayList<String> stringlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_scout);
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getWritableDatabase();
listav = this.getListView();
listav.setVisibility(View.VISIBLE);
int codpartita;
String team;
cursor = db.rawQuery("SELECT _codpartita as _id, team, FROM partita ORDER BY _codpartita DESC", null);
cursor.moveToFirst();
while ( !cursor.isAfterLast() ) {
team = cursor.getString(cursor.getColumnIndex("team"));
stringlist.add(team);
cursor.moveToNext();
}
cursor.moveToFirst();
if (cursor.getCount()>0) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListScoutActivity.this,
android.R.layout.simple_list_item_1, cursor, new String[]{"team"},
new int[]{android.R.id.text1}, 0);
listav.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListScoutActivity.this,
// android.R.layout.simple_list_item_1, android.R.id.text1, stringlist);
// listav.setAdapter(adapter);
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor)l.getItemAtPosition(position);
//.. other things..
}

Getting item from ListView

I'm working on a android project and a got stuck. I'm trying to get an item from a ListView but all I get is info about the item's position in the database I created and not the item itself.
this is my code :
public class Map extends Activity {
Cursor cursor;
ListView listView;
String categoria = "livro";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final CitySQL dbHelper = new CitySQL(Map.this, null, null, 1);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final String[] camposDb = {"city", BaseColumns._ID};
cursor = db.query("cities", camposDb, null, null, null, null, "city ASC");
int[] camposView = new int[] {android.R.id.text1};
#SuppressWarnings("deprecation")
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(Map.this,
android.R.layout.two_line_list_item, cursor, camposDb, camposView);
listView= (ListView)findViewById(R.id.city_list);
listView.setAdapter(adapter);
final Geocoder geocoder=new Geocoder(this, Locale.ENGLISH);
listView.setOnItemClickListener(new OnItemClickListener(){
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onItemClick(AdapterView<?> parent, View view, int posicao,long id) {
final String morada = listView.getAdapter().getItem(posicao).toString();
Toast.makeText(Map.this, morada, Toast.LENGTH_LONG).show();
I made a Toast to see exactly what was happening when I clicked but my goal is to get the item (a city name) and look for a location.
Change
final String morada = listView.getAdapter().getItem(posicao).toString();
to
Cursor cursor = (Cursor) listView.getAdapter().getItem(posicao);
String morada = cursor.getString(cursor.getColumnIndex("column_name_for_city"));

Unable to access query

I get db cannot be resloved error in this class. At the displayListView() function. Can anyone please help me solve it. Thanks
got code from here http://kdehairy.com/2012/08/19/using-a-preloaded-sqlite-database-with-sqliteopenhelper/
public class PrepopSqliteDbActivity extends Activity {
// private static final String DB_NAME = "hymnals";
//A good practice is to define database field names as constants
private SimpleCursorAdapter dataAdapter;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Our key helper
ExternalDbOpenHelper repo = ExternalDbOpenHelper.getInstance( context );
SQLiteDatabase db = repo.getWritableDatabase();
displayListView();
}
private void displayListView() {
//all hymns are fetched
*final Cursor cursor = db.fetchAllHymns();*
// The desired columns to be bound
String[] columns = new String[] {
ExternalDbOpenHelper.HYMN_ID,
ExternalDbOpenHelper.HYMN_NAME,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.tVid,
R.id.name,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_main,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
}
});
}
}
The variable db is a local variable within the onCreate method. Use an instance variable instead:
class /* ... */ {
private SQLiteDatabase db;
/* ... */
#Override
public void onCreate(Bundle savedInstanceState) {
/* ... */
db = repo.getWritableDatabase();
/* ... */
}
/* ... */
}

NullPointerException when I run this code

So in this code, I am trying to retrieve a cursor based on the query passed through my showResults() and then create an adapter and loadermanager. I feel like the problem is being caused with the layout and id within my SimpleCursorAdapter constructor because the error started when I created the layout and id. I used Log and if statement to see whether it was the cursor that was null and nothing showed up on the logcat, so that must mean by cursor is fine.
public class SearchResultsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private ListView list;
private DatabaseTable db;
private SimpleCursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
db = new DatabaseTable(this);
handleIntent(getIntent());
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
db = new DatabaseTable(this);
Cursor cursor = db.getContactMatches(query, null);
list = (ListView)findViewById(android.R.id.list);
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
getLoaderManager().initLoader(0, null, this);
list.setAdapter(mAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent contactIntent = new Intent(getApplicationContext(), ContactActivity.class);
contactIntent.setData(getIntent().getData());
startActivity(contactIntent);
}
});
}
Since your code is crashing on the line list.setAdapter(mAdapter);, list is the only object that it makes sense to give you a null pointer.
Upon further examination, it is clear you are not assigning list after it is initially declared. You need to add something like this in onCreate(), after setContentView():
list = (ListView) findViewById(android.R.id.list);
(This is how you'd access it if your object had android:id="#android:id/list"; if you assigned your own ID, use R.id.your_id_here instead.)
this is probably your error here:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
that adapter requires a Cursor passed into the constructor at the spot where you passed null in for the parameter, like this:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
cursor, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
Try getting a readable database first before you query it:
db = new DatabaseTable(this);
Cursor cursor = db.getReadableDatabase().getContactMatches(query, null);

android IllegalStateException, database already closed

I am using SimpleCursorAdapter and database table to populate a List. The list gets populated and I am able to click on list items to open the desired item(This starts a new activity). The problem is when I press the back key, I got Following error.
IllegalStateException: database already closed.
My code is as follows:
public class populatingLectures extends ListActivity{
private static String[] FROM = {SUBJECT, TOPIC, LECTURENUMBER, DATE };
private static int[] TO = {R.id.subject, R.id.topic,
R.id.lecturenumber, R.id.date };
private static String[] data = { SUBJECT, TOPIC, LECTURENUMBER, _DATA };
private static String ORDER_BY = DATE + " DESC";
private SoftCopyDatabase lectures;
String gotId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SoftCopyDatabase lectures = new SoftCopyDatabase(this);
try {
Cursor cursor = getLectures();
showLectures(cursor);
} finally {
lectures.close();
}
}
public void onStart() {
super.onStart();
lectures = new SoftCopyDatabase(this);
try {
Cursor cursor = getLectures();
showLectures(cursor);
} finally {
lectures.close();
}
}
private Cursor getLectures() {
SQLiteDatabase db = lectures.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,null, "subject=?", new String[] {OpenClick.subjectName}, null, null,
ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
private void showLectures(Cursor cursor) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item_lectures, cursor, FROM, TO);
setListAdapter(adapter);
}
private Cursor getFileName(String ID) {
SQLiteDatabase db = lectures.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, data, "_ID=?",
new String[] { ID }, null, null, null);
startManagingCursor(cursor);
return cursor;
}
#Override
protected void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
//...CODE TO START NEW ACTIVITY
}
}
}
Kindly tell me what mistake am I doing. Because I am not closing the database explicitly any where.
Regards,
Waneya Iqbal.
finally
{
lectures.close();
}
I think this line gives the exception, so put it in onDestroy().
You're closing the database as soon as you populate the list. You should move the
lectures.close()
line from onStart() to onDestroy(), which will make sure your database gets closed when the activity is complete, rather than as soon as the list is populated.

Categories

Resources