创建数据库和表后,SQL(查询)错误或丢失数据库

时间:2018-05-23 06:47:09

标签: java android sql sqlite

在我的第一个活动(会议室活动)中,我显示在数据库中输入的会议室列表。在同一个屏幕上,我添加了按钮以创建更多房间。在CreateRoom活动中,我们可以添加更多房间,创建后将返回第1个活动。到目前为止,一切都很完美。如果点击任何房间,它将打开设备活动与设备列表但是当我点击任何房间崩溃的应用程序。如果没有创建数据库或表,那么它也应该在Room Activity上崩溃,为什么它仅在Appliance活动中崩溃?

会议室活动

public class Rooms extends AppCompatActivity {

ListView listView;
ArrayList<HashMap<String,String>> roomList;
DBOpenHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rooms);

    db = new DBOpenHelper(this);
    roomList = db.GetRooms();
    listView = (ListView) findViewById(R.id.listRooms);
    final ListAdapter listAdapter = new SimpleAdapter(this, roomList, R.layout.roomlist, new String[]{"name"}, new int[]{R.id.txtRoomName});
    listView.setAdapter(listAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(Rooms.this, Appliance.class);
            intent.putExtra("roomname", listView.getItemAtPosition(position).toString());
            startActivity(intent);
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    db = new DBOpenHelper(this);
    roomList = db.GetRooms();
    ListAdapter listAdapter = new SimpleAdapter(this, roomList, R.layout.roomlist, new String[]{"name"}, new int[]{R.id.txtRoomName});
    listView.setAdapter(listAdapter);
}
}

CreateRoom

public class CreateRoom extends AppCompatActivity {

int i = 1;
EditText editText;
List<EditText> ed;

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

    final LinearLayout textLayout = (LinearLayout) findViewById(R.id.textLayout);
    Button btnAddRoom = (Button) findViewById(R.id.btnAddRoom);
    Button btnCreateRoom = (Button) findViewById(R.id.btnCreateRoom);
    final EditText txtRoomname = (EditText) findViewById(R.id.r1);
    ed = new ArrayList<EditText>();

    btnAddRoom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            i += 1;
            editText = new EditText(CreateRoom.this);
            editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            editText.setHint("Room Name" + i);
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            textLayout.addView(editText);
            ed.add(editText);
        }
    });

    btnCreateRoom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DBOpenHelper db = new DBOpenHelper(CreateRoom.this);
            if (txtRoomname.getText().toString().length() > 0) {
                db.addRoom(txtRoomname.getText().toString());
            }
            int i = 0;
            while (i< ed.size()) {
                if (ed.get(i).getText().toString().length() > 0) {
                    db.addRoom(ed.get(i).getText().toString());
                }
                i++;
            }
            finish();
        }
    });

}
 }

DBOpenHelper

public class DBOpenHelper extends SQLiteOpenHelper {

private static final int DB_VERSION = 2;
private static final String DB_NAME = "Automation";
private static final String TABLE_NAME = "Room";
private static final String ROOM_NAME = "roomname";
private static final String TB_NAME = "Appliance";
private static final String RM_NAME = "RmName";
private static final String APPLIANCE_NAME = "AppName";


public DBOpenHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String QUERY_CREATE_ROOM = "CREATE TABLE " + TABLE_NAME + " (" + ROOM_NAME + " TEXT"+ ")";
    String QUERY_CREATE_APPLIANCE = "CREATE TABLE " + TB_NAME + " (" + RM_NAME + " TEXT, "+ APPLIANCE_NAME + " TEXT"+")";
    db.execSQL(QUERY_CREATE_ROOM);
    db.execSQL(QUERY_CREATE_APPLIANCE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + TB_NAME);
    onCreate(db);
}

void addRoom(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(ROOM_NAME, name);
    long newRowID = db.insert(TABLE_NAME, null, contentValues);
    db.close();
}



public ArrayList<HashMap<String, String>> GetRooms(){
    SQLiteDatabase db = this.getWritableDatabase();
    ArrayList<HashMap<String, String>> roomList = new ArrayList<>();
    String query = "SELECT roomname FROM " + TABLE_NAME;
    Cursor cursor = db.rawQuery(query, null);
    while (cursor.moveToNext()){
        HashMap<String, String> room = new HashMap<>();
        room.put("name", cursor.getString(cursor.getColumnIndex(ROOM_NAME)));
        roomList.add(room);
    }
    return roomList;
}

void addApplance(String roomname, String appliancename){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(RM_NAME, roomname);
    contentValues.put(APPLIANCE_NAME, appliancename);
    long newRowID = db.insert(TB_NAME, null, contentValues);
    db.close();
}



public ArrayList<HashMap<String, String>> GetAppliance(String name){
    SQLiteDatabase db = this.getWritableDatabase();
    ArrayList<HashMap<String, String>> applianceList = new ArrayList<>();
    String query = "SELECT AppName FROM " + TB_NAME + " WHERE RmNAme=" + name;
    Cursor cursor = db.rawQuery(query, null);
    while (cursor.moveToNext()){
        HashMap<String, String> appliance = new HashMap<>();
        appliance.put("appliance", cursor.getString(cursor.getColumnIndex(APPLIANCE_NAME)));
        applianceList.add(appliance);
    }
    return applianceList;
}
}

ApplianceActivity - 应用崩溃的地方

public class Appliance extends AppCompatActivity {

ListView listView;
ArrayList<HashMap<String,String>> applianceList;
DBOpenHelper db;
String room;

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

    Intent intent = getIntent();
    String r = intent.getStringExtra("roomname");
    room = r.replace("{name=", "").replace("}","");

    if (getSupportActionBar()!= null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(room);
    }

    db = new DBOpenHelper(this);
    applianceList = db.GetAppliance(room);
    listView = (ListView) findViewById(R.id.listAppliance);
    final ListAdapter listAdapter = new SimpleAdapter(this, applianceList, R.layout.roomlist, new String[]{"appliance"}, new int[]{R.id.txtRoomName});
    listView.setAdapter(listAdapter);
}

@Override
protected void onResume() {
    super.onResume();
    db = new DBOpenHelper(this);
    applianceList = db.GetAppliance(room);
    ListAdapter listAdapter = new SimpleAdapter(this, applianceList, R.layout.roomlist, new String[]{"appliance"}, new int[]{R.id.txtRoomName});
    listView.setAdapter(listAdapter);
}

 }

错误记录

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.smiles.automation, PID: 24981
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.smiles.automation/com.smiles.automation.Appliance}: android.database.sqlite.SQLiteException: no such column: G (code 1): , while compiling: SELECT AppName FROM Appliance WHERE RmNAme=G
              #################################################################
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (no such column: G (code 1): , while compiling: SELECT AppName FROM Appliance WHERE RmNAme=G)
              #################################################################
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                  at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:7325)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
               Caused by: android.database.sqlite.SQLiteException: no such column: G (code 1): , while compiling: SELECT AppName FROM Appliance WHERE RmNAme=G
              #################################################################
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (no such column: G (code 1): , while compiling: SELECT AppName FROM Appliance WHERE RmNAme=G)
              #################################################################
                  at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                  at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1062)
                  at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:627)
                  at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                  at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1471)
                  at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1410)
                  at com.smiles.automation.DBOpenHelper.GetAppliance(DBOpenHelper.java:83)
                  at com.smiles.automation.Appliance.onCreate(Appliance.java:39)
                  at android.app.Activity.performCreate(Activity.java:6904)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                    ... 9 more

我的会议室活动和设备活动几乎相似,但为什么它只在设备中崩溃?

2 个答案:

答案 0 :(得分:1)

  

引起:android.database.sqlite.SQLiteException:没有这样的列:G   (代码1):,编译时:SELECT AppName FROM Appliance WHERE   RMNAME = G

您将获得SQLiteException

  

SQLite异常,指示SQL解析时出错   或执行。

您应 RECTIFY SELECT 声明。

  • 您需要 single quote

试试这个

"SELECT AppName FROM " + TB_NAME + " WHERE RmNAme ='" + name + "'";

然后 Uninstall App 再次运行。

答案 1 :(得分:0)

  

没有这样的列:G(代码1):,编译时:SELECT AppName FROM Appliance WHERE RmNAme = G)

至少引用G

String query = "SELECT AppName FROM " + TB_NAME + " WHERE RmNAme= '" + name + "'";

但是使用类似

的prearedStatement会更好