如何获得列表视图?

时间:2018-10-15 07:13:11

标签: java android

如何获取列表视图android studio。这是我的代码

public class StockSearchActivity extends AppCompatActivity {

SQLiteDatabase sqLiteDatabase;
DbHelper dbHelper;
Cursor cursor;
ListView listView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stock_search);

    listView = findViewById(R.id.display_listview);
    dbHelper = new DbHelper(this);


    Cursor result = dbHelper.getAllData();
    final ArrayList<String> theList = new ArrayList<>();

    //get the data to the list view
    if(result.getCount() == 0 ){
        Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
    }else{
        while (result.moveToNext()){
            theList.add(result.getString(0));
            theList.add(result.getString(1));
            theList.add(result.getString(2));
            theList.add(result.getString(3));
            theList.add(result.getString(4));
            ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
            listView.setAdapter(listAdapter);

        }
    }

}

}

以下代码是我用于列表视图的活动代码。正确吗?代码不起作用

//getAllData
public Cursor getAllData(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor result = db.rawQuery("SELECT * FROM  " + tbName ,null);
    return result;
}

以上代码已在数据库类中实现。

2 个答案:

答案 0 :(得分:0)

将您的Adapter放在while loop之外

//get the data to the list view
    if(result.getCount() == 0 ){
        Toast.makeText(StockSearchActivity.this,"Databse is empty",Toast.LENGTH_LONG).show();
    }else{
        while (result.moveToNext()){
            theList.add(result.getString(0));
            theList.add(result.getString(1));
            theList.add(result.getString(2));
            theList.add(result.getString(3));
            theList.add(result.getString(4));


        }
            ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,theList);
            listView.setAdapter(listAdapter);
    }

答案 1 :(得分:0)

您的问题在下面的行

    SQLiteDatabase db = this.getWritableDatabase();

当您尝试从数据库中获取数据时,应以如下所示的可读模式打开它。

    SQLiteDatabase db = this.getReadableDatabase();
相关问题