Я читаю базу данных sqlite в tableLayout. Я не хочу делать это в отдельном потоке вместо долгого ожидания без обновлений пользовательского интерфейса. Поэтому я использовал AsyncTask, чтобы выполнить часть работы и опубликовать результаты. Тем не менее, только около 1/4 элемента в моем списке фактически попадают в TableLayout. Работает нормально без AsyncTask. Большинство элементов в списке выдает ошибку (которую я поймал) java.util.concurrent.RejectedExecutionException. Я не уверен, почему это так. Вот мой код.
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id INTEGER PRIMARY KEY, filepath TEXT UNIQUE, title TEXT, artist TEXT, album TEXT, time TEXT, playcount NUMERIC);");
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
c.moveToFirst();
if (c != null) {
int color = 0xFFdfe8ea;
this.startManagingCursor(c);
// Loop through all Results
do {
try{
MyAsyncTask aTask = new MyAsyncTask();
String[]strings= {c.getString(c.getColumnIndex("title")),c.getString(c.getColumnIndex("artist")),c.getString(c.getColumnIndex("time")),c.getString(c.getColumnIndex("album")),""+color};
aTask.execute(strings);
}catch(Exception e){
Log.w("****", e);
}
if (color == 0xFFdfe8ea) {
color = 0xFFf2f8fa;
} else {
color = 0xFFdfe8ea;
}
} while (c.moveToNext());
}
} catch (SQLException e) {
Log.e("****", e.toString());
} finally {
if (myDB != null) {
myDB.close();
}
}
и вот AsyncTask
class MyAsyncTask extends AsyncTask<String, Void, View> {
@Override
protected View doInBackground(String... params) {
int color = Integer.parseInt(params[4]);
TableRow tr = new TableRow(MainActivity.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView space = new TextView(MainActivity.this);
space.setText("");
space.setBackgroundColor(color); //0xFFf2f8fa alternating
space.setSingleLine();
space.setPadding(2, 2, 2, 2);
space.setGravity(Gravity.LEFT);
space.setTextColor(0xFF000000);
space.setLayoutParams(new LayoutParams(
findViewById(R.id.spaceColumn).getWidth(),
LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
TextView title = new TextView(MainActivity.this);
title.setText(params[0]);
title.setBackgroundColor(color); //0xFFf2f8fa alternating
title.setSingleLine();
title.setPadding(2, 2, 2, 2);
title.setGravity(Gravity.LEFT);
title.setTextColor(0xFF000000);
title.setEllipsize(TruncateAt.END);
title.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Create a Button to be the row-content. */
TextView artist = new TextView(MainActivity.this);
artist.setText(params[1]);
artist.setBackgroundColor(color); //0xFFf2f8fa alternating
artist.setSingleLine();
artist.setPadding(2, 2, 2, 2);
artist.setGravity(Gravity.LEFT);
artist.setTextColor(0xFF000000);
artist.setEllipsize(TruncateAt.END);
artist.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Create a Button to be the row-content. */
TextView time = new TextView(MainActivity.this);
time.setText(params[2]);
time.setBackgroundColor(color); //0xFFf2f8fa alternating
time.setSingleLine();
time.setPadding(2, 2, 2, 2);
time.setGravity(Gravity.LEFT);
time.setTextColor(0xFF000000);
time.setLayoutParams(new LayoutParams(
findViewById(R.id.timeColumn).getWidth(),
LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
TextView album = new TextView(MainActivity.this);
album.setText(params[3]);
album.setBackgroundColor(color); //0xFFf2f8fa alternating
album.setSingleLine();
album.setPadding(2, 2, 2, 2);
album.setGravity(Gravity.LEFT);
album.setTextColor(0xFF000000);
album.setEllipsize(TruncateAt.END);
album.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Add Button to row. */
tr.addView(space);
tr.addView(title);
tr.addView(artist);
tr.addView(time);
tr.addView(album);
/* Add row to TableLayout. */
return tr;
}
@Override
protected void onPostExecute(View tr) {
((TableLayout) findViewById(R.id.tableLayout)).addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
@Override
protected void onPreExecute() {
}
}
Для справки я так и исправил.
class MyAsyncTask extends AsyncTask<Void, Song, Void> {
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase myDB = openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
String TableName = "songs";
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id INTEGER PRIMARY KEY, filepath TEXT UNIQUE, title TEXT, artist TEXT, album TEXT, time TEXT, playcount NUMERIC);");
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
c.moveToFirst();
int filepathIndex=c.getColumnIndex("filepath");
int titleIndex=c.getColumnIndex("title");
int artistIndex=c.getColumnIndex("artist");
int albumIndex=c.getColumnIndex("album");
int timeIndex=c.getColumnIndex("time");
int playcountIndex=c.getColumnIndex("playcount");
if (c != null) {
int color = 0xFFdfe8ea;
// this.startManagingCursor(c);
// Loop through all Results
do {
Song song = new Song(c.getString(filepathIndex),c.getString(titleIndex),c.getString(artistIndex),c.getString(albumIndex),c.getString(timeIndex),c.getInt(playcountIndex),color);
// Add to song the data from your cursor
publishProgress(song);
if (color == 0xFFdfe8ea) {
color = 0xFFf2f8fa;
} else {
color = 0xFFdfe8ea;
}
} while (c.moveToNext());
}
return null;
}
@Override
protected void onPostExecute(Void item) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Song... items) {
for (Song song : items) {
TableRow tr = new TableRow(MainActivity.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView space = new TextView(MainActivity.this);
space.setText("");
space.setBackgroundColor(song.color); //0xFFf2f8fa alternating
space.setSingleLine();
space.setPadding(2, 2, 2, 2);
space.setGravity(Gravity.LEFT);
space.setTextColor(0xFF000000);
space.setLayoutParams(new LayoutParams(
findViewById(R.id.spaceColumn).getWidth(),
LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
TextView title = new TextView(MainActivity.this);
title.setText(song.title);
title.setBackgroundColor(song.color); //0xFFf2f8fa alternating
title.setSingleLine();
title.setPadding(2, 2, 2, 2);
title.setGravity(Gravity.LEFT);
title.setTextColor(0xFF000000);
title.setEllipsize(TruncateAt.END);
title.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Create a Button to be the row-content. */
TextView artist = new TextView(MainActivity.this);
artist.setText(song.artist);
artist.setBackgroundColor(song.color); //0xFFf2f8fa alternating
artist.setSingleLine();
artist.setPadding(2, 2, 2, 2);
artist.setGravity(Gravity.LEFT);
artist.setTextColor(0xFF000000);
artist.setEllipsize(TruncateAt.END);
artist.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Create a Button to be the row-content. */
TextView time = new TextView(MainActivity.this);
time.setText(song.time);
time.setBackgroundColor(song.color); //0xFFf2f8fa alternating
time.setSingleLine();
time.setPadding(2, 2, 2, 2);
time.setGravity(Gravity.LEFT);
time.setTextColor(0xFF000000);
time.setLayoutParams(new LayoutParams(
findViewById(R.id.timeColumn).getWidth(),
LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
TextView album = new TextView(MainActivity.this);
album.setText(song.album);
album.setBackgroundColor(song.color); //0xFFf2f8fa alternating
album.setSingleLine();
album.setPadding(2, 2, 2, 2);
album.setGravity(Gravity.LEFT);
album.setTextColor(0xFF000000);
album.setEllipsize(TruncateAt.END);
album.setLayoutParams(new LayoutParams(
0,
LayoutParams.WRAP_CONTENT, 1));
/* Add Button to row. */
tr.addView(space);
tr.addView(title);
tr.addView(artist);
tr.addView(time);
tr.addView(album);
// Add the row to the table
((TableLayout) findViewById(R.id.tableLayout)).addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
}