I am trying to create a database of restaurants and their items for an app as a starter project to get familiar with android. I have a list from a previous activity where a user clicks on the name of the restaurant and the items are shown. I created a helperDB class to handle the insert statements and database setup, although when I called my insert method from inside a new thread, they do not seem to execute. I have provided the code below:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_bar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
String barName = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
final TextView tv = (TextView) findViewById(R.id.name);
tv.setText(barName);
restaurants = new ArrayList<String>();
mydb = new DBHelper(this);
new Thread(new Runnable() {
@Override
public void run() {
mydb.insertDrink("cake", "McD's", 8);
mydb.insertDrink("muffin", "The Woods", 8);
restaurants = mydb.getDrinks("The Woods");
System.out.println(restaurants);
}
}).start();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, restaurants);
obj = (ListView)findViewById(R.id.listview);
obj.setAdapter(arrayAdapter);
}
The code for the insert statement and getDrinks method are as follows:
public boolean insertDrink(String drink, String name, int price){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("drink", drink);
contentValues.put("name", name);
contentValues.put("price", price);
db.insert("Bars", null, contentValues);
return true;
}
public ArrayList<String> getDrinks(String name){
ArrayList<String> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from Bars", null);
res.moveToFirst();
while(res.isAfterLast() == false){
arrayList.add(res.getString(res.getColumnIndex(BAR_COLUMN_DRINK)));
res.moveToNext();
}
return arrayList;
}
I know that I am not supposed to access any android toolkits from any thread besides the UI thread, although I don't think I am doing that. If this is not the normal way to populate a SQLite android database, I of course am willing to learn where to do that as well.
Aucun commentaire:
Enregistrer un commentaire