引起:android.database.sqlite.SQLiteException:没有这样的表:food(代码1 SQLITE_ERROR):,同时编译:SELECT * FROM food order by id asc 2

时间:2018-04-27 16:21:39

标签: java android android-sqlite

我在编译程序时在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) 

现在错误是在总活动java类

中创建的

这里是logcat

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.prudentmubasha.ainnaresto/com.example.prudentmubasha.ainnaresto.TotalActivity}: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    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: java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    at java.lang.String.substring(String.java:2036)
    at com.example.prudentmubasha.ainnaresto.TotalActivity.onCreate(TotalActivity.java:33)
    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) 

04-28 21:19:42.719 1676-2777 / system_process E / eglCodecCommon:glUtilsParamSize:unknow param 0x000082da     glUtilsParamSize:unknow param 0x000082da

这是发生错误的地方

enter c while (st.hasMoreElements()) {
        //Toast.makeText(getApplicationContext(), st.nextElement().toString().substring(0,1), Toast.LENGTH_LONG).show();
        test = st.nextElement().toString().substring(3,1);
        if(count>0)
            total+= Float.parseFloat(test);
        count++;
    }

这是总活动java类文件

 pizza mApp;
EditText et_summary;
TextView tv_total;

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

    mApp=((pizza) getApplicationContext());
    et_summary = (EditText) findViewById(R.id.et_summary);
    tv_total = (TextView) findViewById(R.id.tv_total);
    //Toast.makeText(getApplicationContext(), "You have chosen the" + " " +  mApp.getGlobalVarValue(), Toast.LENGTH_LONG).show();
    et_summary.setText(mApp.getGlobalVarValue());
    String str = mApp.getGlobalVarValue();
    StringTokenizer st = new StringTokenizer(str,"$");
    String test="";
    float total=0;
    int count=0;
    while (st.hasMoreElements()) {
        //Toast.makeText(getApplicationContext(), st.nextElement().toString().substring(0,1), Toast.LENGTH_LONG).show();
        test = st.nextElement().toString().substring(3,1);
        if(count>0)
            total+= Float.parseFloat(test);
        count++;
    }
    et_summary.setText(mApp.getGlobalVarValue());
    tv_total.setText("Total :" + total+"");
    mApp.setGlobalClear();


}
public boolean isFloat( String input )
{
    try
    {
        Float.parseFloat( input );
        return true;
    }
    catch( Exception e)
    {
        return false;
    }
}

}

1 个答案:

答案 0 :(得分:0)

很明显,当您在locations = loadLocationData();中使用MenuFoodActivity时,食物表格不存在。

您可以通过在调用loadLocationData方法之前创建表来绕过此错误。例如: -

db=openOrCreateDatabase("Restaurants_DB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS food(id int, name text, price int);");
locations = loadLocationData();
addListenerOnButton();
initializeUI();