设置AsyncTask从SQLite数据库加载数据?

时间:2017-07-18 00:31:15

标签: android sqlite android-asynctask

下面的onCreate()方法可以在我的Activity中正常工作,从SQLite数据创建一个CardView:

helper = new SQLiteDB(this);  
listItems = new ArrayList<>();
listItems = helper.getAllListItems();

当我尝试设置AsyncTask()方法来替换上面的最后一行并在List中加载数据库数据时,CardView会在UI上显示,但不会填充SQLite数据。我在这里缺少什么?

CardViewDetailsActivity

public class CardViewDetilsActivity extends AppCompatActivity {

    List<ListItem> listItems;
    private SQLiteDB helper;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dets);   

        final CardView cardView = (CardView) findViewById(R.id.dets);

        // Get the position of the clicked on R. list CardView from
        // the MainActivity's intent bundle.
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // get the CardView item using the int position from the
            // MainActivity's onItemClick() and the putExtra in the intent.
            position = extras.getInt("position",0); 
        } 

        helper = new SQLiteDB(this);
        listItems = new ArrayList<>();
        listItems = helper.getAllListItems(); 
        // I tried to replace the last line above with:
        // "getDataFromSQLiteDB();" to launch the AsyncTask();

        ...
        cardType1 = (TextView) findViewById(R.id.cardType1);
        ...  
        cardType1.setText(listItems.get(position).getType()); 
    } // End of onCreate();

    private void getDataFromSQLiteDB() {

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                listItems.clear();
                listItems.addAll(helper.getAllListItems());
                // I also replaced the above two lines with 
                // helper.getAllListItems();

                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }.execute();
    }
}   

SQLiteDB.java

public class SQLiteDB extends SQLiteOpenHelper {

    // Get data from the database that the CardViewDetails Activity can use
    public List<ListItem> getAllListItems() {
    List<ListItem> modelList = new ArrayList<>();

    SQLiteDatabase db = getReadableDatabase();
    ...
        return modeList;    
    }
}

0 个答案:

没有答案
相关问题