2016-07-19 211 views
-1

我正在開發一個應用,在那裏我存儲的數據。操作,插入,更新和選擇他們都工作正常,除了更新。
雖然我更新數據庫,我的應用程序崩潰和它給了以下錯誤:
沒有這樣的列存在。
我檢查過很多次,但我無法找到問題。
在下面,我分享我的代碼,我至今寫的。無法更新的Android SQLite數據庫

Register.java

/** 
* Created by yadapras on 7/8/2016. 
*/ 
public class Register { 

    String phone_no; 
    String uname,password,re_password,name,email,imei_no,dev_model; 
    int os_version; 

    public void setUname(String uname) 
    { 
     this.uname = uname; 
    } 
    public String getUname() 
    { 
     return this.uname; 
    } 
    public void setPassword(String password) 
    { 
     this.password = password; 
    } 
    public String getPassword() 
    { 
     return this.password; 
    } 
    public void setRe_password(String re_password) 
    { 
     this.re_password = re_password; 
    } 
    public String getRe_password() 
    { 
     return this.re_password; 
    } 
    public void setName(String name) 
    { 
     this.name = name; 
    } 
    public String getName() 
    { 
     return this.name; 
    } 
    public void setEmail(String email) 
    { 
     this.email = email; 
    } 
    public String getEmail() 
    { 
     return this.email; 
    } 
    public void setPhone_no(String phone_no) 
    { 
     this.phone_no = phone_no; 
    } 
    public String getPhone_no() 
    { 
     return this.phone_no; 
    } 
    public void setImei_no(String imei_no) 
    { 
     this.imei_no = imei_no; 
    } 
    public String getImei_no() 
    { 
     return this.imei_no; 
    } 

    public void setDev_model(String dev_model) 
    { 
     this.dev_model=dev_model; 
    } 
    public String getDev_model() 
    { 
     return this.dev_model; 
    } 

    public void setOs_version(int os_version) 
    { 
     this.os_version = os_version; 
    } 
    public int getOs_version() 
    { 
     return this.os_version; 
    } 
} 

MainActivity.java

package com.example.yadapras.mobiltyemp; 

import android.content.Context; 
import android.content.Intent; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.VectorEnabledTintResources; 
import android.telephony.TelephonyManager; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

/** 
* Created by yadapras on 6/26/2016. 
*/ 
public class MainActivity extends AppCompatActivity { 


    EditText a,b; 
    String usr,pass; 
    DatabaseHelper helper = new DatabaseHelper(this); 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

    } 

    public void onButtonClick(View v) 
    { 
     if (v.getId() == R.id.BLogin) 
     { 
      a = (EditText)findViewById(R.id.userName); 
      usr = a.getText().toString(); 
      b = (EditText)findViewById(R.id.userPassword); 
      pass = b.getText().toString(); 



      String password = null; 

      if(a.getText().toString().length() == 0 || usr == "" || usr == null) 
       a.setError(" User name is required!"); 
      if(b.getText().toString().length() == 0 || pass =="" || pass == null) 
       b.setError("Password is required!"); 
      else{ 
       password = helper.searchPass(usr); 
      } 

      if (pass.equals(password) && password != null) 
      { 

       Intent intent = new Intent(getApplicationContext(), EmpDetail.class); 
       intent.putExtra("usr",usr); 

       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
       String uid = telephonyManager.getDeviceId(); 
       String manufacturer = Build.MANUFACTURER; // Not used in current scenario 
       String model = Build.MODEL; 
       int version = Build.VERSION.SDK_INT; 
       String versionRelease = Build.VERSION.RELEASE; // not used in current scenario 
       String msg = "IMEI No: "+uid+"\n"+"Manufacturer is :"+manufacturer+"\n"+"Model is :"+model+"\n"+"Os Version is :"+version+"\n"+"VersionRelease is :"+versionRelease; 
       Toast toast = Toast.makeText(MainActivity.this,msg,Toast.LENGTH_LONG); 
       toast.show(); 

       Register r = new Register(); 
       r.setImei_no(uid); 
       r.setDev_model(model); 
       r.setOs_version(version); 
       r.setUname(usr); 

       helper.updateTable(r); /*For updating table with new Coloumn*/ 

       startActivity(intent); 


      } 
      else 
      { 
       Toast err_pass = Toast.makeText(MainActivity.this,"UserName and Password don't Match",Toast.LENGTH_SHORT); 
       err_pass.show(); 
      } 

     } 
     if (v.getId() == R.id.BSignup) 
     { 
      Intent intent = new Intent(getApplicationContext(), Registration.class); 
      startActivity(intent); 
     } 
    } 

} 

DataBaseHelper.java

package com.example.yadapras.mobiltyemp; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.DatabaseUtils; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.ArrayMap; 
import android.util.Log; 

import org.json.JSONException; 
import org.json.JSONObject; 

/** 
* Created by yadapras on 7/8/2016. 
*/ 
public class DatabaseHelper extends SQLiteOpenHelper { 


    private static final int DATABASE_VERSION = 1; 
    private static final String DATABASE_NAME = "registrationDB.db"; 
    public static final String TABLE_NAME = "registrations"; 

    public static final String COLUMN_ID = "id"; 
    public static final String COLUMN_USERNAME = "username"; 
    public static final String COLUMN_PASSWORD= "password"; 
    public static final String COLUMN_RE_PASSWORD= "re_password"; 
    public static final String COLUMN_NAME= "name"; 
    public static final String COLUMN_EMAIL= "email"; 
    public static final String COLUMN_PHONE_NO= "phone_no"; 

    /*Adding three coloumn IMEI_NO,OS_Version,Model_Device Respectively*/ 

    public static final String COLUMN_IMEI_NO = "imei_no"; 
    public static final String COLUMN_DEV_MODEL = "dev_model"; 
    public static final String COLUMN_OS_VERSION = "os_version"; 


    SQLiteDatabase sqLiteDatabase; 
    private static final String TABLE_CREATE = "create table registrations(id integer primary key not null, " + 
      "username text not null, password text not null, re_password text not null, name text not null, email text not null," + 
      "phone_no number not null,imei_no text, dev_model text, os_version text);"; 


    public DatabaseHelper(Context context) { 
     super(context,DATABASE_NAME,null,DATABASE_VERSION); 
    } 


    @Override 
    public void onCreate(SQLiteDatabase sqLiteDatabase) { 
     sqLiteDatabase.execSQL(TABLE_CREATE); 
     this.sqLiteDatabase=sqLiteDatabase; 
     Log.d("#####Table Value",TABLE_CREATE); 

    } 

    @Override 
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { 
     String query = "DROP TABLE IF EXISTS " +TABLE_NAME ; 
     sqLiteDatabase.execSQL(query); 
     this.onCreate(sqLiteDatabase); 
    } 

    public void registerUser(Register r) { 
     /*Inserting anything in to the dataBase make sure it should be writable*/ 
     sqLiteDatabase = getWritableDatabase(); 
     ContentValues values = new ContentValues(); 

     String query = "select * from registrations"; 
     Cursor cursor = sqLiteDatabase.rawQuery(query,null); 

     int count = cursor.getCount(); 

     Log.d("##count",""+count); 
     values.put(COLUMN_ID,count); 
     Log.d("##id",r.getUname()); 
     values.put(COLUMN_USERNAME,r.getUname()); 
     values.put(COLUMN_PASSWORD,r.getPassword()); 
     values.put(COLUMN_RE_PASSWORD,r.getRe_password()); 
     values.put(COLUMN_NAME,r.getName()); 
     values.put(COLUMN_EMAIL, r.getEmail()); 
     values.put(COLUMN_PHONE_NO, r.getPhone_no()); 

     sqLiteDatabase.insert(TABLE_NAME, null,values); /*this will insert Register object in to the Database*/ 

     sqLiteDatabase.close(); 
    } 

    public String searchPass(String usr) { 
     sqLiteDatabase = this.getReadableDatabase(); 
     String query = "select username,password from "+TABLE_NAME; 
     Cursor cursor = sqLiteDatabase.rawQuery(query,null); 
     String a,b ; // a and b will be userName and Password respectively 
     b = "Not Found"; 
     if (cursor.moveToFirst()) 
     { 
      do { 
       a = cursor.getString(0); 
       Log.d("##username from db",a); 
       if (a.equals(usr)) 
       { 
        b = cursor.getString(1); 
        break; 
       } 
      }while (cursor.moveToNext()); 
     } 
     return b; 
    } 

    public JSONObject showDetail(String usr) { 
     sqLiteDatabase = this.getReadableDatabase(); 
     String query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p"; 
     Cursor cursor = sqLiteDatabase.rawQuery(query,null); 
     JSONObject data = new JSONObject(); 
     if (cursor.moveToFirst()){ 
      do { 

       int columnsQty = cursor.getColumnCount(); 
       for (int idx=0; idx<columnsQty; ++idx) { 
        try { 
         data.put(cursor.getColumnName(idx),cursor.getString(idx)); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }while (cursor.moveToNext()); 
     } 
     cursor.close(); 
     Log.d("###Data Value",data.toString()); 
     return data; 

    } 

    public void updateTable(Register r) { 
     SQLiteDatabase db = getWritableDatabase(); 

     ContentValues cv = new ContentValues(); 

     cv.put(COLUMN_IMEI_NO,r.getImei_no()); 
     Log.d("###Column_IMEI_NO",r.getImei_no()); 
     cv.put(COLUMN_DEV_MODEL,r.getDev_model()); 
     cv.put(COLUMN_OS_VERSION,r.getOs_version()); 
     db.update(TABLE_NAME,cv,"username = "+r.getUname(),null); 

    } 
} 

// LOG生成: -

07-19 18:21:20.246 15581-15581/com.example.yadapras.mobiltyemp D/##username from db: h 
07-19 18:21:20.256 15581-15581/com.example.yadapras.mobiltyemp D/###Column_IMEI_NO: 356619054923013 
07-19 18:21:20.257 15581-15581/com.example.yadapras.mobiltyemp E/SQLiteLog: (1) no such column: h 
07-19 18:21:20.259 15581-15581/com.example.yadapras.mobiltyemp D/AndroidRuntime: Shutting down VM 
07-19 18:21:20.260 15581-15581/com.example.yadapras.mobiltyemp E/AndroidRuntime: FATAL EXCEPTION: main 
                       Process: com.example.yadapras.mobiltyemp, PID: 15581 
                       java.lang.IllegalStateException: Could not execute method for android:onClick 
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) 
                        at android.view.View.performClick(View.java:4780) 
                        at android.view.View$PerformClick.run(View.java:19866) 
                        at android.os.Handler.handleCallback(Handler.java:739) 
                        at android.os.Handler.dispatchMessage(Handler.java:95) 
                        at android.os.Looper.loop(Looper.java:135) 
                        at android.app.ActivityThread.main(ActivityThread.java:5254) 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at java.lang.reflect.Method.invoke(Method.java:372) 
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
                        Caused by: java.lang.reflect.InvocationTargetException 
                        at java.lang.reflect.Method.invoke(Native Method) 
                        at java.lang.reflect.Method.invoke(Method.java:372) 
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                        at android.view.View.performClick(View.java:4780)  
                        at android.view.View$PerformClick.run(View.java:19866)  
                        at android.os.Handler.handleCallback(Handler.java:739)  
                        at android.os.Handler.dispatchMessage(Handler.java:95)  
                        at android.os.Looper.loop(Looper.java:135)  
                        at android.app.ActivityThread.main(ActivityThread.java:5254)  
                        at java.lang.reflect.Method.invoke(Native Method)  
                        at java.lang.reflect.Method.invoke(Method.java:372)  
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  
                        Caused by: android.database.sqlite.SQLiteException: no such column: h (code 1): , while compiling: UPDATE registrations SET imei_no=?,os_version=?,dev_model=? WHERE username = h 
                        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 
                        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889) 
                        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500) 
                        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 
                        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) 
                        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) 
                        at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1574) 
                        at android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1522) 
                        at com.example.yadapras.mobiltyemp.DatabaseHelper.updateTable(DatabaseHelper.java:146) 
                        at com.example.yadapras.mobiltyemp.MainActivity.onButtonClick(MainActivity.java:72) 
                        at java.lang.reflect.Method.invoke(Native Method)  
                        at java.lang.reflect.Method.invoke(Method.java:372)  
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  
                        at android.view.View.performClick(View.java:4780)  
                        at android.view.View$PerformClick.run(View.java:19866)  
                        at android.os.Handler.handleCallback(Handler.java:739)  
                        at android.os.Handler.dispatchMessage(Handler.java:95)  
                        at android.os.Looper.loop(Looper.java:135)  
                        at android.app.ActivityThread.main(ActivityThread.java:5254)  
                        at java.lang.reflect.Method.invoke(Native Method)  
                        at java.lang.reflect.Method.invoke(Method.java:372)  
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  
07-19 18:25:45.117 15581-15591/com.example.yadapras.mobiltyemp W/art: Suspending all threads took: 10.528ms 
07-19 18:26:20.304 15581-15581/com.example.yadapras.mobiltyemp I/Process: Sending signal. PID: 15581 SIG: 9 
+0

如果你可以發佈logcat的? – 7geeky

+0

爲什麼downVoted誰能告訴我理由? –

+0

我從給出的日誌中讀取,你的應用程序試圖寫入到一個表,聲稱該數據庫已經被認爲是不存在的列小時。 – Dilettant

回答

3

問題是您的更新查詢的語法,

您的版本:

db.update(TABLE_NAME,cv,"username = "+r.getUname(),null); 

更新它這樣。

db.update(TABLE_NAME,cv,"username = ?",new String[]{r.getUname()}); 

這將解決問題。

+0

它的工作謝謝 :) –

3

試試這個:

public void updateTable(Register r) { 
    SQLiteDatabase db = getWritableDatabase(); 

    ContentValues cv = new ContentValues(); 

    cv.put(COLUMN_IMEI_NO,r.getImei_no()); 
    Log.d("###Column_IMEI_NO",r.getImei_no()); 
    cv.put(COLUMN_DEV_MODEL,r.getDev_model()); 
    cv.put(COLUMN_OS_VERSION,r.getOs_version()); 
    String updateQuery = "Update registrations set " + COLUMN_IMEI_NO + " = '"+ r.getImei_no() +"' where " + COLUMN_USERNAME + "="+"'"+ r.getUname() +"'"; 
    database.execSQL(updateQuery); 
    database.close(); 

} 
+0

謝謝@Nidhin它的工作:) –

+0

可以把它標記爲正確的一個 –

+0

你能告訴我我的問題是投下來的..我犯了錯誤,如果我會得到答案,從下次我會留在我的腦海裏,在這裏詢問 –

0
Try Like This (this works for me) 


      public boolean rowIdExists(String StrId) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor cursor = db.rawQuery("select id from " + TABLE_Name 
      + " where id=?", new String[]{StrId}); 
    boolean exists = (cursor.getCount() > 0); 
    /*cursor.close(); 
    db.close();*/ 
    return exists; 
} 

public void insertuserrate(String Str[], Context cxt) { 

    // TODO Auto-generated method stub 
/* 
    Cursor c = null; 
*/ 
    String strId = ""; 
    //ArrayList<String> userRatepoit= new ArrayList<String>(); 
    try { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 
     { 
      values.put(KEY_RID, Str[0]); 
      values.put(ALL_name, Str[1]); 
      values.put(ALL_isbn, Str[2]); 
      values.put(ALL_catid, Str[3]); 

      if (rowIdExists(Str[0])) { 
       db.update(TABLE_Name, values, "id " + "=" + Str[0], null); 
       Log.d("update success", TABLE_Name); 
      } else { 
       db.insert(TABLE_Name, null, values); 
       Log.d("inserted success", TABLE_Name); 
      } 
      // Closing database connection 
     } 
     try { 
      db.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
0

//代碼更新一次接觸。接觸是在其上已經確立了自己的數據

吸氣二傳手
public int updateContact(Contact contact) { 
    SQLiteDatabase db = this.getWritableDatabase(); 

    ContentValues values = new ContentValues(); 
    values.put(KEY_NAME, contact.getName()); 
    values.put(KEY_PH_NO, contact.getPhoneNumber()); 

    // updating row 
    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", 
      new String[] { String.valueOf(contact.getID()) }); 
}