我在编译程序时在Logcat中收到此错误。
根据Logcat,这两个导致错误的地方
1
db=openOrCreateDatabase("Restaurants_DB", Context.MODE_PRIVATE, null);
locations = loadLocationData();
addListenerOnButton();
initializeUI();
2
HashMap<String, Location> locations = new HashMap<String, Location>();
Cursor c=db.rawQuery("SELECT * FROM foods order by id asc", null);`
以下是我创建的2个java类: -
这是 MenuFoodActivity.java 类
public class MenuFoodActivity extends AppCompatActivity {
pizza mApp;
private HashMap<String, Location> locations;
ListView listView ;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_foods);
db=openOrCreateDatabase("Restaurants_DB", Context.MODE_PRIVATE, null);
locations = loadLocationData();
addListenerOnButton();
initializeUI();
}
private void addListenerOnButton() {
final Context context = this;
Button button1 = (Button) findViewById(R.id.btn_Foods);
listView = (ListView) findViewById(R.id.lvFoods);
listView.setOnItemClickListener( new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Object o = listView.getItemAtPosition(position);
String pen = o.toString();
mApp=((pizza) getApplicationContext());
mApp.setGlobalVarValue(pen);
Toast.makeText(getApplicationContext(), "You have chosen the" + " " + pen, Toast.LENGTH_LONG).show();
//showMessage("Text","text");
}
}
);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, AddFoodActivity.class);
startActivity(intent);
}
});
}
private String[] getMenuFoods() {
String[] menuFoods = new String[locations.size()];
menuFoods = locations.keySet().toArray(menuFoods);
return menuFoods;
}
private void initializeUI() {
String[] menuFoods = getMenuFoods();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menuFoods);
listView.setAdapter(adapter);
}
public void onListItemClick(ListView l, View view, int position, long id){
}
private void displaySelectedMenuFoods(String menuFoods){
}
private HashMap<String, Location> loadLocationData() {
HashMap<String, Location> locations = new HashMap<String, Location>();
Cursor c=db.rawQuery("SELECT * FROM foods order by id asc", null);
while(c.moveToNext()) {
locations.put("- " + c.getString(1).toString() + " : $" + c.getString(2).toString() + "", new Location(Integer.parseInt(c.getString(0)), c.getString(1).toString(), Double.parseDouble(c.getString(2))));
}
return locations;
}
}
AddDrinkActivity.java
类
public class AddDrinkActivity extends AppCompatActivity {
EditText ed_id,ed_name,ed_price;
Button btnAdd,btnDelete,btnUpdate,btnViewAll;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_drink);
ed_id=(EditText)findViewById(R.id.ed_Id);
ed_name=(EditText)findViewById(R.id.ed_Name);
ed_price=(EditText)findViewById(R.id.ed_Price);
db=openOrCreateDatabase("Restaurants_DB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS food(id int, name text, price int);");
addListenerOnButton();
}
public void showMessage(String title, String message){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
private void addListenerOnButton() {
final Context context = this;
btnAdd = (Button) findViewById(R.id.btn_Add);
btnDelete = (Button) findViewById(R.id.btn_Delete);
btnUpdate = (Button) findViewById(R.id.btn_Update);
btnViewAll = (Button) findViewById(R.id.btn_View);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.execSQL("INSERT INTO food VALUES('"+ed_id.getText()+"','"+ed_name.getText()+"','"+ed_price.getText()+"');");
showMessage("Success", "Drink added");
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
db.execSQL("UPDATE food SET name='"+ed_name.getText()+"', price='"+ed_price.getText()+"' WHERE id='"+ ed_id.getText()+"'");
showMessage("Success","Drink Modified");
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.execSQL("DELETE FROM drinks WHERE id='"+ed_id.getText()+"'");
showMessage("Success", "Drink Deleted");
}
});
btnViewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor cursor=db.rawQuery("SELECT * FROM food", null);
if(cursor.getCount()==0){
showMessage("Error","No records founds");
return;
}
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()){
buffer.append("Id: "+cursor.getString(0)+"\n");
buffer.append("Name: "+cursor.getString(1)+"\n");
buffer.append("Price: "+cursor.getString(2)+"\n\n");
}
showMessage("Drink Details",buffer.toString());
}
});
}
}
这是logcat:
04-26 14:48:55.336 21103-21103/com.example.prudentmubasha.ainnaresto E/DATABASE OPERATIONS: Database created /Opened...
04-26 14:48:55.593 21103-21103/com.example.prudentmubasha.ainnaresto E/DATABASE OPERATIONS: Database created /Opened...
04-26 14:48:55.753 21103-21121/com.example.prudentmubasha.ainnaresto E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
glUtilsParamSize: unknow param 0x000082da
04-26 14:48:58.743 21103-21103/com.example.prudentmubasha.ainnaresto E/SQLiteLog: (1) no such table: food
04-26 14:48:58.746 21103-21103/com.example.prudentmubasha.ainnaresto E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.prudentmubasha.ainnaresto, PID: 21103
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prudentmubasha.ainnaresto/com.example.prudentmubasha.ainnaresto.MenuDrinksActivity}: android.database.sqlite.SQLiteException: no such table: food (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM food order by id asc
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:101)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1786)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: android.database.sqlite.SQLiteException: no such table: food (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM food order by id asc
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:901)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:512)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1401)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1340)
at com.example.prudentmubasha.ainnaresto.MenuDrinksActivity.loadLocationData(MenuDrinksActivity.java:79)
at com.example.prudentmubasha.ainnaresto.MenuDrinksActivity.onCreate(MenuDrinksActivity.java:32)
at android.app.Activity.performCreate(Activity.java:7117)
at android.app.Activity.performCreate(Activity.java:7108)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1262)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2867)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3027)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:101)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1786)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
答案 0 :(得分:0)
在MenuDrinksActivity
之前调用活动AddDrinkActivity
,因此此时不会创建表。我建议在Application
类中初始化数据库。在任何活动之前调用此类,以便在开始使用数据库之前初始化数据库并创建表。
public class AndroidApplication extends Application {
@Override
public void onCreate() {
// initialize database here
}
}
不要忘记在清单中注册Application
课程,如下所示:
<application
...
android:name="com.example.AndroidApplication">
...
</application>