android.database.sqlite.SQLiteException:没有这样的列:highID(Sqlite代码1):

时间:2017-04-04 06:42:46

标签: java android sqlite

DatabaseCoconet.java

public static final String COL_CODE_TREE = "code_tree";

public static final String TABLE_NAME_HIGH = "High";
public static final String COL_HIGH_TREE = "high_tree";
public static final String COL_DATE_HIGH = "date_high";
public static final String COL_STATUS_HIGH = "udpateStatus";

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

public void onCreate(SQLiteDatabase db) {


    db.execSQL("CREATE_TABLE "+ TABLE_NAME_HIGH +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COL_CODE_TREE + " VARCHAR, " + COL_HIGH_TREE + " INTEGER, "+ COL_STATUS_HIGH + " TEXT, " + COL_DATE_HIGH + " DATE);");

    /*db.execSQL("INSERT INTO "+ TABLE_NAME_HIGH +" (" + COL_CODE_TREE + ", " + COL_HIGH_TREE + ", " + COL_STATUS_HIGH
            + ", " + COL_DATE_HIGH + ") VALUES ('test', '555', 'no', '20/2/2560');");
    /**db.execSQL("CREATE TABLE "+ TABLE_NAME +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COL_NAME + " TEXT, " + COL_LASTNAME + " TEXT, " + COL_SCHOOL + " TEXT);");
    db.execSQL("INSERT INTO "+ TABLE_NAME +" (" + COL_NAME + ", " + COL_LASTNAME
            + ", " + COL_SCHOOL + ") VALUES ('Sleeping', 'For Less', 'Android School');");*/

}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME_HIGH);
    String query;
    query = "DROP TABLE IF EXISTS High";
    db.execSQL(query);
    onCreate(db);
}
/**
 * Get list of High from SQLite DB as Array List
 * @return
 */
public ArrayList<HashMap<String, String>> getAllUsers() {
    ArrayList<HashMap<String, String>> wordList;
    wordList = new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM "+ TABLE_NAME_HIGH ;
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(COL_CODE_TREE, cursor.getString(0));
            map.put(COL_HIGH_TREE, cursor.getString(1));
            map.put(COL_DATE_HIGH, cursor.getString(2));
            wordList.add(map);
        } while (cursor.moveToNext());
    }
    database.close();
    return wordList;
}

/**
 * Compose JSON out of SQLite records
 * @return
 */
public String composeJSONfromSQLite(){
    ArrayList<HashMap<String, String>> wordList;
    wordList = new ArrayList<HashMap<String, String>>();
    String selectQuery = "SELECT  * FROM "+ TABLE_NAME_HIGH +" where udpateStatus = '"+"no"+"'";`enter code here`
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("highID", cursor.getString(0));
            map.put("code_tree", cursor.getString(1));
            map.put("high_tree", cursor.getString(2));
            map.put("date_high", cursor.getString(3));
            wordList.add(map);
        } while (cursor.moveToNext());
    }
    database.close();
    Gson gson = new GsonBuilder().create();
    //Use GSON to serialize Array List to JSON
    return gson.toJson(wordList);
}

/**
 * Get Sync status of SQLite
 * @return
 */
public String getSyncStatus(){
    String msg = null;
    if(this.dbSyncCount() == 0){
        msg = "SQLite and Remote MySQL DBs are in Sync!";
    }else{
        msg = "DB Sync needed\n";
    }
    return msg;
}

/**
 * Get SQLite records that are yet to be Synced
 * @return
 */
public int dbSyncCount(){
    int count = 0;
    String selectQuery = "SELECT  * FROM High where udpateStatus = '"+"no"+"'";`enter code here`
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);
    count = cursor.getCount();
    database.close();
    return count;
}

/**
 * Update Sync status against each User ID
 * @param id
 * @param status
 */
public void updateSyncStatus(String id, String status){
    SQLiteDatabase database = this.getWritableDatabase();
    String updateQuery = "Update High set udpateStatus = '"+ status +"' where highID="+"'"+ id +"'";
    Log.d("query",updateQuery);
    database.execSQL(updateQuery);
    database.close();
 }
}

HighActivity

DatabaseCoconut mHelper;
SQLiteDatabase mDb;
Cursor mCursor;
ListView listhigh;

public static final String BARCODE_KEY = "BARCODE";
private Barcode barcodeResult;
private EditText result;
ProgressDialog prgDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hight);
    Log.d("HightActivity", "onCreate");

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mHelper = new DatabaseCoconut(this);
    mDb = mHelper.getWritableDatabase();

    result = (EditText) findViewById(R.id.editCodeHight);
    final EditText editHigh = (EditText)findViewById(R.id.editHigh);

   Button buttonAdd = (Button)findViewById(R.id.buttonAddHigh);
    buttonAdd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String codehigh = result.getText().toString();
            String high = editHigh.getText().toString();
            String no = "no";

            if(codehigh.trim().length() != 0 && high.trim().length() != 0 ) {

                Cursor mCursor = mDb.rawQuery("SELECT * FROM " + DatabaseCoconut.TABLE_NAME_HIGH
                        + " WHERE " + DatabaseCoconut.COL_CODE_TREE + "='" + codehigh + "'"
                        + " AND " + DatabaseCoconut.COL_HIGH_TREE + "='" + high + "'"
                        + " AND " + DatabaseCoconut.COL_STATUS_HIGH + "='" + no + "'"
                        + " AND " + DatabaseCoconut.COL_DATE_HIGH + "='" + getDateTime() + "'", null);

                if(mCursor.getCount() == 0) {
                    mDb.execSQL("INSERT INTO "+ DatabaseCoconut.TABLE_NAME_HIGH
                            +" (" + DatabaseCoconut.COL_CODE_TREE
                            + ", " + DatabaseCoconut.COL_HIGH_TREE
                            + ", " + DatabaseCoconut.COL_STATUS_HIGH
                            + ", " + DatabaseCoconut.COL_DATE_HIGH + ") VALUES ('"
                            + codehigh + "', '" + high + "', '" + no + "', '" + getDateTime() + "');");

                    result.setText("");
                    editHigh.setText("");

                    Toast.makeText(getApplicationContext()
                            ,"เพิ่มข้อมูลเรียบร้อยแล้ว", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext()
                            ,"คุณมีข้อมูลนี้อยู่แล้ว", Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(getApplicationContext()
                        ,"กรุณากรอกข้อมูลให้ครบทุกช่อง", Toast.LENGTH_SHORT).show();
            }

            mCursor = mDb.rawQuery("SELECT * FROM "
                    + DatabaseCoconut.TABLE_NAME_HIGH, null);

            listhigh = (ListView)findViewById(R.id.listhigh);
            listhigh.setAdapter(updateListView());

        }
    });

    final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    assertNotNull(result);
    assertNotNull(fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startScan();
        }
    });
    if(savedInstanceState != null){
        Barcode restoredBarcode = savedInstanceState.getParcelable(BARCODE_KEY);
        if(restoredBarcode != null){
            result.setText(restoredBarcode.rawValue);
            barcodeResult = restoredBarcode;
        }
    }
     /*----------------------- HideKeyPad ------------------------*/
    getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
    );
    //-----------------โชวโปเซสไดอะล๊อค
    prgDialog = new ProgressDialog(this);
    prgDialog.setMessage("กำลังอัพเดตฐานข้อมูลกรุณารอซักครู่..");
    prgDialog.setCancelable(false);

}

public void onResume() {
    super.onResume();
    Log.d("HightActivity", "onResume");

    mHelper = new DatabaseCoconut(this);
    mDb = mHelper.getWritableDatabase();

    mCursor = mDb.rawQuery("SELECT * FROM "
            + DatabaseCoconut.TABLE_NAME_HIGH, null);

    listhigh = (ListView)findViewById(R.id.listhigh);
    listhigh.setAdapter(updateListView());

    listhigh.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
            mCursor.moveToPosition(arg2);

            AlertDialog.Builder builder = new AlertDialog.Builder(HightActivity.this);
            builder.setTitle("ยืนยันการลบข้อมูล");
            builder.setMessage("คุณต้องการลบข้อมูลนี้ใช่หรือไม่?");
            builder.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    String code_tree = mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_CODE_TREE));
                    String high = mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_HIGH_TREE));
                    String date = mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_DATE_HIGH));

                    mDb.execSQL("DELETE FROM "+ DatabaseCoconut.TABLE_NAME_HIGH
                            + " WHERE " + DatabaseCoconut.COL_CODE_TREE + "='" + code_tree + "'"
                            + " AND " + DatabaseCoconut.COL_HIGH_TREE + "='" + high + "'"
                            + " AND " + DatabaseCoconut.COL_DATE_HIGH + "='" + date + "';");

                    mCursor.requery();

                    listhigh.setAdapter(updateListView());

                    Toast.makeText(getApplicationContext()
                            ,"ลบเรียบร้อย", Toast.LENGTH_SHORT).show();
                }
            });
            builder.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();

            return true;
        }
    });
}

public void onStop() {
    super.onStop();
    Log.d("HighiActivity", "onStop");
    mHelper.close();
    mDb.close();
}
@Override
protected void onStart() {
    super.onStart();
    Log.d("HightActivity", "onStart");
}

@Override
protected void onPause() {
    super.onPause();
    Log.d("HightActivity", "onPause");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.d("HightActivity", "onDestroy");
}

@Override
protected void onRestart() {
    super.onRestart();
    Log.d("HightActivity", "onRestart");
}

public void syncSQLiteMySQLDB(){
    //Create AsycHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    ArrayList<HashMap<String, String>> hightList =  mHelper.getAllUsers();
    if(hightList.size()!=0){
        if(mHelper.dbSyncCount() != 0){
            prgDialog.show();
            params.put("highJSON", mHelper.composeJSONfromSQLite());
            //http://www.coconutstoring.com/insertuser.php
            client.post("http://www.coconutstoring.com/inserthigh.php",params ,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    System.out.println(response);
                    prgDialog.hide();
                    try {
                        JSONArray arr = new JSONArray(response);
                        System.out.println(arr.length());
                        for(int i=0; i<arr.length();i++){
                            JSONObject obj = (JSONObject)arr.get(i);
                            System.out.println(obj.get("id"));
                            System.out.println(obj.get("status"));
                            mHelper.updateSyncStatus(obj.get("id").toString(),obj.get("status").toString());
                        }
                        Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Throwable error,
                                      String content) {
                    // TODO Auto-generated method stub
                    prgDialog.hide();
                    if(statusCode == 404){
                        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }else if(statusCode == 500){
                        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }else{
            Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
        }
    }else{
        Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
    }
}

/**-------------------- Time------------------------------------------*/

private String getDateTime() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd ", Locale.getDefault());
    Date date = new Date();
    return dateFormat.format(date);
}

/**---------------- แสดงข้อมูลบน list view-----------------------*/

public ArrayAdapter<String> updateListView() {
    ArrayList<String> arr_list = new ArrayList<String>();
    mCursor.moveToFirst();
    while ( !mCursor.isAfterLast() ){
        arr_list.add("รหัส : " + mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_CODE_TREE)) + "\t\t"
                + ("ความสูง :  " + mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_HIGH_TREE))) + "\n"
                + "วันที่ : " + mCursor.getString(mCursor.getColumnIndex(DatabaseCoconut.COL_DATE_HIGH)));
        mCursor.moveToNext();
    }

    ArrayAdapter<String> adapterDir = new ArrayAdapter<String>(getApplicationContext()
            , R.layout.my_listview, arr_list);
    //Toast.makeText(getApplicationContext(), mHelper.getSyncStatus(), Toast.LENGTH_LONG).show();
    return adapterDir;
}

/**------------------------------   ScanQr----------------------------- */
private void startScan() {
    final MaterialBarcodeScanner materialBarcodeScanner = new MaterialBarcodeScannerBuilder()
            .withActivity(HightActivity.this)
            .withEnableAutoFocus(true)
            .withBleepEnabled(true)
            .withBackfacingCamera()
            .withCenterTracker()
            .withText("")
            .withResultListener(new MaterialBarcodeScanner.OnResultListener() {
                @Override
                public void onResult(Barcode barcode) {
                    barcodeResult = barcode;
                    result.setText(barcode.rawValue);
                }
            })
            .build();
    materialBarcodeScanner.startScan();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putParcelable(BARCODE_KEY, barcodeResult);
    super.onSaveInstanceState(outState);
}

/**---------------------ขอสิทธิเพื่อเข้าถึงกล้อง-------------------------------- */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode != MaterialBarcodeScanner.RC_HANDLE_CAMERA_PERM) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }
    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        startScan();
        return;
    }
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    };
    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
    builder.setTitle("Error")
            .setMessage(R.string.no_camera_permission)
            .setPositiveButton(android.R.string.ok, listener)
            .show();
}
/**---------- สร้างเมนู และ เปลี่ยนหน้า--------------------- */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.menuLogout) {
        logout();
    }else if (id == R.id.menuhight){
        hight();
    }else if (id == R.id.menuproduct){
        //product();
        syncSQLiteMySQLDB();
    }else if (id == R.id.menuwater){
        water();
    }else if (id == R.id.menuvitamin){
        soundly();
    }else if (id == R.id.menutrim){
        trim();
    }else if (id == R.id.menutoxic){
        toxic();
    }

    return super.onOptionsItemSelected(item);
}
private void hight(){
 Intent intent = new Intent(this, HightActivity.class);
 startActivity(intent);
 }
private void product(){
 Intent intent = new Intent(this, ProductActivity.class);
 startActivity(intent);
 }
 private void soundly(){
 Intent intent = new Intent(this, SoundlyActivity.class);
 startActivity(intent);
 }
 private void water(){
 Intent intent = new Intent(this, WaterActivity.class);
 startActivity(intent);
 }
private void trim(){
    Intent intent = new Intent(this, TrimActivity.class);
    startActivity(intent);
}
private void toxic(){
    Intent intent = new Intent(this, ToxicActivity.class);
    startActivity(intent);
}

private void logout(){
    //Creating an alert dialog to confirm logout
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("คุณต้องการออกจากระบบใช่หรือไม่");
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setNegativeButton("ไม่",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                }
            });
    alertDialogBuilder.setPositiveButton("ใช่",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                    //Getting out sharedpreferences
                    SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                    //Getting editor
                    SharedPreferences.Editor editor = preferences.edit();

                    //Puting the value false for loggedin
                    editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

                    //Putting blank value to email
                    editor.putString(Config.EMAIL_SHARED_PREF, "");

                    //Saving the sharedpreferences
                    editor.commit();

                    //Starting login activity
                    Intent intent = new Intent(HightActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                }
            });``

    //Showing the alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
   }
 }

logcat的

  

04-04 13:41:38.433 31160-31160 / com.nectec.ProjectCoconut   E / AndroidRuntime:致命异常:主要                                                                              过程:com.nectec.ProjectCoconut,PID:31160                                                                              android.database.sqlite.SQLiteException:没有这样的列:highID   (Sqlite代码1):,编译时:Update High set udpateStatus =   'no'其中highID ='null',(操作系统错误 - 2:没有这样的文件或目录)                                                                                  在   android.database.sqlite.SQLiteConnection.nativePrepareStatement(母语   方法)                                                                                  在   android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:897)                                                                                  在   android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:508)                                                                                  在   android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)                                                                                  在android.database.sqlite.SQLiteProgram。(SQLiteProgram.java:63)                                                                                  在   android.database.sqlite.SQLiteStatement。(SQLiteStatement.java:31)                                                                                  在   android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1734)                                                                                  在   android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1660)                                                                                  在   com.nectec.ProjectCoconut.DatabaseCoconut.updateSyncStatus(DatabaseCoconut.java:139)                                                                                  在   com.nectec.ProjectCoconut.HightActivity $ 4.onSuccess(HightActivity.java:256)                                                                                  在   com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:232)                                                                                  在   com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:220)                                                                                  在   com.loopj.android.http.AsyncHttpResponseHandler.onSuccess(AsyncHttpResponseHandler.java:245)                                                                                  在   com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:365)                                                                                  在   com.loopj.android.http.AsyncHttpResponseHandler $ ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:135)                                                                                  在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                  在android.os.Looper.loop(Looper.java:150)                                                                                  在android.app.ActivityThread.main(ActivityThread.java:5546)                                                                                  at java.lang.reflect.Method.invoke(Native Method)                                                                                  在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:794)                                                                                  在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)04-04   13:41:38.433 359-359 /? W / qdhwcomposer:eglGpuPerfHintQCOM失败了   内置显示器

3 个答案:

答案 0 :(得分:0)

db.execSQL("CREATE_TABLE "+ TABLE_NAME_HIGH +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COL_CODE_TREE + " VARCHAR, " + COL_HIGH_TREE + " INTEGER, "+ COL_STATUS_HIGH + " TEXT, " + COL_DATE_HIGH + " DATE);");

这里你没有在create query中查看列名highId。查看它。

答案 1 :(得分:0)

使用KEY_ID代替highId

public static final String KEY_ID = "_id";

Update High set udpateStatus = 'no' where "+ KEY_ID +"='?'

答案 2 :(得分:0)

您正在onCreate()方法中创建列名为 _id 的表格, &安培;尝试在 highID 列中添加数据。

因此,此错误适用于列名称不匹配

更新db.execSQL中的onCreate()方法,如下所示:

db.execSQL("CREATE_TABLE "+ TABLE_NAME_HIGH +" (highID INTEGER PRIMARY KEY AUTOINCREMENT, "
        + COL_CODE_TREE + " VARCHAR, " + COL_HIGH_TREE + " INTEGER, "+ COL_STATUS_HIGH + " TEXT, " + COL_DATE_HIGH + " DATE);");