SQLiteException:没有名为'photo'的列

时间:2011-12-27 17:52:46

标签: android sqlite

为什么我会收到此错误:

               12-27 20:37:57.039: E/AndroidRuntime(3798): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=1, data=Intent { (has extras) }} to activity {org.example.dbcontactconsole/org.example.dbcontactconsole.DbContactConsole}: android.database.sqlite.SQLiteException: table contactTest1 has no column named photo: , while compiling: INSERT INTO contactTest1(phone, photo, email, name) VALUES(?, ?, ?, ?);
               12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.app.ActivityThread.deliverResults(ActivityThread.java:2536)
                12-27 20:37:57.039: E/AndroidRuntime(3798):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:2578)
                12-27 20:37:57.039: E/AndroidRuntime(3798):     at android.app.ActivityThread.access$2000(ActivityThread.java:117) 
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
                  12-27 20:37:57.039: E/AndroidRuntime(3798):   at android.os.Handler.dispatchMessage(Handler.java:99)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.os.Looper.loop(Looper.java:123)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.app.ActivityThread.main(ActivityThread.java:3687)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at java.lang.reflect.Method.invokeNative(Native Method)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at java.lang.reflect.Method.invoke(Method.java:507)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at dalvik.system.NativeStart.main(Native Method)
                   12-27 20:37:57.039: E/AndroidRuntime(3798): Caused by: android.database.sqlite.SQLiteException: table contactTest1 has no column named photo: , while compiling: INSERT INTO contactTest1(phone, photo, email, name) VALUES(?, ?, ?, ?);
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
                     12-27 20:37:57.039: E/AndroidRuntime(3798):    at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
                      12-27 20:37:57.039: E/AndroidRuntime(3798):   at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
                        12-27 20:37:57.039: E/AndroidRuntime(3798):     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1149)
                    12-27 20:37:57.039: E/AndroidRuntime(3798):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1569)
                   12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.database.sqlite.SQLiteDatabase.insertOrThrow(SQLiteDatabase.java:1452)
                    12-27 20:37:57.039: E/AndroidRuntime(3798):     at org.example.dbcontactconsole.DbContactConsole.addContact(DbContactConsole.java:175)
                    12-27 20:37:57.039: E/AndroidRuntime(3798):     at org.example.dbcontactconsole.DbContactConsole.onActivityResult(DbContactConsole.java:136)
                    12-27 20:37:57.039: E/AndroidRuntime(3798):     at android.app.Activity.dispatchActivityResult(Activity.java:3908)
                       12-27 20:37:57.039: E/AndroidRuntime(3798):  at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)

它对我说,我没有名为照片的专栏,但我有:

public void onCreate(SQLiteDatabase db) { 
      db.execSQL("CREATE TABLE " + DbConstants.TABLE_NAME + " " +
            "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
                  DbConstants.NAME + " TEXT NOT NULL," + 
                  DbConstants.PHONE + " TEXT NOT NULL," +
                  DbConstants.PHOTO + "TEXT NOT NULL," +
                  DbConstants.EMAIL +"TEXT NOT NULL,"+");");
   }

这是我的db常量.java:

    public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String EMAIL = "email";
public static final String PHOTO="photo";

当我尝试添加联系人时按下保存按钮时出现错误。

这是我的.java,我添加了方法:

 @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main); 
      showDatabaseContent();
      lv1 = getListView();

      lv1.setTextFilterEnabled(true);

       lv1.setOnItemClickListener(new OnItemClickListener() {

       public void onItemClick(AdapterView<?> a, View v, int position, long id) { 
           cursor = (Cursor) a.getItemAtPosition(position);
           itemId = cursor.getString(0);
           openOptionsMenu();
           }
       });

       lv1.setOnItemSelectedListener(new OnItemSelectedListener() {

           public void onItemSelected(AdapterView<?> parent, View view, int position, long id){

        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

       });
   }

   //selected item index from ListView
   public void showDialogItemId(long itemId){
       Toast.makeText(this, "Menu item selected index is" + Long.toString(itemId), Toast.LENGTH_LONG).show();
   }

   @Override
   public boolean onCreateOptionsMenu(Menu menu){
       MenuInflater inflater = getMenuInflater();
       inflater.inflate(R.menu.menu, menu);
       return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item){
       switch (item.getItemId()){
           case R.id.modifyitem:
               if(null != itemId){
                   Bundle contactToModify = new Bundle();
                   contactToModify.putString("cFirstName", cursor.getString(1));
                   contactToModify.putString("cMobilePhone", cursor.getString(2));
                   contactToModify.putString("cEmail", cursor.getString(3));
                   contactToModify.putString("mod_type", "modifyPerson");
                   Intent intent = new Intent(this, ContactDetails.class);
                   intent.setClass(this, ContactDetails.class);
                   intent.putExtras(contactToModify);
                   startActivityForResult(intent, CONTACT_MODIFIED);
               }else{
                   Toast.makeText(this, "Select Contact to modify", Toast.LENGTH_LONG).show();
               }
               break;
           case R.id.additem:

               Intent i = new Intent(this, ContactDetails.class);
               Bundle bun = new Bundle();
               bun.putString("mod_type", "addPerson");
               i.setClass(this, ContactDetails.class);
               i.putExtras(bun);
               startActivityForResult(i, CONTACT_ADDED);
               break;

           case R.id.removeitem:
               if(null != itemId){
                   removeContact(itemId);
                   showDatabaseContent();
               }
               else{
                   Toast.makeText(this, "Select Contact to delete", Toast.LENGTH_LONG).show();
               }
               break;
           case R.id.search:
               Intent j =new Intent(this,Search.class);
               j.setClass(this, Search.class);
               startActivity(j);
               break;
       }
       return true;
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent intent){
       // See which child activity is calling us back.
       switch (resultCode) {
           case CONTACT_ADDED:
               // This is the standard resultCode that is sent back if the
               // activity crashed or didn't doesn't supply an explicit result.
               if (resultCode == RESULT_FIRST_USER){
                   Bundle bundle = new Bundle();
                   bundle = intent.getBundleExtra("contactData");
                   addContact(bundle);
                   showDatabaseContent();
               } 
               else{
                   Toast.makeText(this, "CANCEL CONTACT BUTTON PRESSED", Toast.LENGTH_LONG).show();
               }
               break;
           case CONTACT_MODIFIED:
               if (resultCode == 2){
                   Bundle bundle = new Bundle();
                   bundle = intent.getBundleExtra("contactData");
                   modifyContact(bundle);
                   showDatabaseContent();
               }
               else{
                   Toast.makeText(this, "MODIFY CONTACT FAILED", Toast.LENGTH_LONG).show();
               }
               break;
           default:
               break;
       }
   }

 //method removes item from database
   private void removeContact(String itemId){
       db = contacts.getWritableDatabase();
       db.delete(DbConstants.TABLE_NAME, "_ID=" + itemId, null);

   }

   private void addContact(Bundle bundle) {
          // Insert a new record into the Events data source.
          // You would do something similar for delete and update.
          db = contacts.getWritableDatabase();
          ContentValues vals = new ContentValues();
          vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
          vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
          vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
          vals.put(DbConstants.PHOTO,bundle.getString("poza"));
          db.insertOrThrow(DbConstants.TABLE_NAME, null, vals);
       }

 //method should modify existing Contact
   private void modifyContact(Bundle bundle){
       db = contacts.getWritableDatabase();
       ContentValues vals = new ContentValues();
       vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
       vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
       vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
       db.update(DbConstants.TABLE_NAME, vals, _ID+"="+itemId, null);
   }

   private Cursor getContacts() {
          db = contacts.getReadableDatabase();
          cursor = db.query(DbConstants.TABLE_NAME, FROM, null, null, null,
                null,DbConstants.NAME);
          startManagingCursor(cursor);
          return cursor;
   }

   public void showDatabaseContent(){
       contacts = new DbCreate(this); 
       try {
           cursor = getContacts(); 
           showContacts(cursor); 
       } finally {
           contacts.close(); 
           db.close();
       }
   }

   private void showContacts(Cursor cursor) {
       //set up data binding
       SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
       setListAdapter(adapter);
       }
}

这是我的.java,我已经实现了保存按钮的方法:

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contactdetails);
     Button sButton = (Button) findViewById(R.id.button1);
     sButton.setOnClickListener(new OnClickListener() {

          public void onClick(View arg0) {
              // in onCreate or any event where your want the user to
              // select a file
              Intent intent = new Intent();
              intent.setType("image/*");
              intent.setAction(Intent.ACTION_GET_CONTENT);
              startActivityForResult(Intent.createChooser(intent,
                      "Select Picture"), SELECT_PICTURE);
          }
      });

    Bundle incomingActionType = getIntent().getExtras();
    operationType = incomingActionType.getString("mod_type");

    if (operationType.equals("addPerson")){

        nameField = (EditText) findViewById(R.id.contactName); 
        mobilePhoneField = (EditText) findViewById(R.id.contactmobile);
        emailField = (EditText) findViewById(R.id.contactemail);

    }

    else if (operationType.equals("modifyPerson")){

        String modifyFirstName = incomingActionType.getString("cFirstName");
        nameField = (EditText) findViewById(R.id.contactName);
        nameField.setText(modifyFirstName);


        String modifyPhoneNumber = incomingActionType.getString("cMobilePhone");
        mobilePhoneField = (EditText) findViewById(R.id.contactmobile);
        mobilePhoneField.setText(modifyPhoneNumber);

        String modifyEmail = incomingActionType.getString("cEmail");
        emailField = (EditText) findViewById(R.id.contactemail);
        emailField.setText(modifyEmail);    
    }


cancelButton = (Button) findViewById(R.id.cancelcontactbutton);
saveContactButton = (Button) findViewById(R.id.savecontactbutton);

saveContactButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        Intent resultIntent = new Intent();
        Bundle contactData = new Bundle();

            if (nameField.getText().toString().length() == 0){
                new AlertDialog.Builder(ContactDetails.this).setTitle("Error").setMessage("First name field cannot be empty!").setNeutralButton("Close", null).show();
            } else if (mobilePhoneField.getText().toString().length() == 0){
                new AlertDialog.Builder(ContactDetails.this).setTitle("Error").setMessage("Mobile Phone field cannot be empty!").setNeutralButton("Close", null).show();
            } else if (emailField.getText().toString().length() == 0){
                new AlertDialog.Builder(ContactDetails.this).setTitle("Error").setMessage("Email field cannot be empty!").setNeutralButton("Close", null).show();
            } else{
                contactData.putString("contactFirstName", nameField.getText().toString());
                contactData.putString("contactMobilePhone", mobilePhoneField.getText().toString());
                contactData.putString("contactEmail", emailField.getText().toString());
                contactData.putString("poza",poza.getText().toString());
                resultIntent.putExtra("contactData", contactData);

                if (operationType.equals("addPerson")){
                    setResult(RESULT_FIRST_USER, resultIntent);
                }else if (operationType.equals("modifyPerson")){
                    setResult(RESULT_MODIFY_USER, resultIntent);
                }               
                finish();
            }
    }
});

cancelButton.setOnClickListener(new View.OnClickListener(){


    public void onClick(View v) {
        Intent resultIntent = new Intent();
        setResult(RESULT_CANCELED, resultIntent);
        finish();


    }
});

}
public void onActivityResult(int requestCode, int resultCode, Intent data) {  
       if (resultCode == RESULT_OK) {
           if (requestCode == 1) {
               // currImageURI is the global variable I'm using to hold the content:// URI of the image

Uri          currImageURI = data.getData();
               getRealPathFromURI(currImageURI);

           }
         }
       }


    public String getRealPathFromURI(Uri currImageURI) {
       // can post image
       String [] proj={MediaStore.Images.Media.DATA};
       Cursor cursor = managedQuery( currImageURI,
               proj, // Which columns to return
               null,       // WHERE clause; which rows to return (all rows)
               null,       // WHERE clause selection arguments (none)
               null); // Order-by clause (ascending by name)
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();


          poza=(EditText)findViewById(R.id.editText1);
           poza.setText(currImageURI.toString());
          return cursor.getString(column_index);

        }
}

我认为错误在这里:db.insertOrThrow(DbConstants.TABLE_NAME, null, vals); 但不知道原因。

3 个答案:

答案 0 :(得分:3)

public void onCreate(SQLiteDatabase db) { 
      db.execSQL("CREATE TABLE " + DbConstants.TABLE_NAME + " " +
            "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
                  DbConstants.NAME + " TEXT NOT NULL," + 
                  DbConstants.PHONE + " TEXT NOT NULL," +
                  DbConstants.PHOTO+
                  DbConstants.EMAIL + ");");

创建数据库时,您没有为照片列(以及后续电子邮件地址)指定数据类型。最有可能的是,这会导致错误,从而阻止色谱柱的产生。在这里指定一个数据类型,你应该很好。

答案 1 :(得分:0)

未定义用于创建数据库的脚本中的PHOTO和EMAIL类型。另外别忘了把逗号。

答案 2 :(得分:0)

修复上述错误。如果不能正常工作从连接的设备或模拟器卸载您的应用程序,然后运行您的应用程序。