2016-09-06 55 views
1

我看着德里克巴尼亚斯教程,他用OpenOrCreate创建数据库,这里是java的代码:OpenOrCreateDatabse与使用数据库辅助类的区别?

public class MainActivity extends ActionBarActivity { 

SQLiteDatabase contactsDB = null; 

Button createDBButton, addContactButton, deleteContactButton, getContactsButton, 
     deleteDBButton; 
EditText nameEditText, emailEditText, contactListEditText, idEditText; 

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

    createDBButton = (Button) findViewById(R.id.createDBButton); 
    addContactButton = (Button) findViewById(R.id.addContactButton); 
    deleteContactButton = (Button) findViewById(R.id.deleteContactButton); 
    getContactsButton = (Button) findViewById(R.id.getContactsButton); 
    deleteDBButton = (Button) findViewById(R.id.deleteDBButton); 
    nameEditText = (EditText) findViewById(R.id.nameEditText); 
    emailEditText = (EditText) findViewById(R.id.emailEditText); 
    contactListEditText = (EditText) findViewById(R.id.contactListEditText); 
    idEditText = (EditText) findViewById(R.id.idEditText); 

} 

public void createDatabase(View view) { 

    try{ 

     // Opens a current database or creates it 
     // Pass the database name, designate that only this app can use it 
     // and a DatabaseErrorHandler in the case of database corruption 

     SQLiteDatabase contactsDB= this.openOrCreateDatabase("MyContacts", MODE_PRIVATE, null); 

     // Execute an SQL statement that isn't select 
     contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " + 
       "(id integer primary key, name VARCHAR, email VARCHAR);"); 

     // The database on the file system 
     File database = getApplicationContext().getDatabasePath("MyContacts.db"); 

     // Check if the database exists 
     if (database.exists()) { 
      Toast.makeText(this, "Database Created", Toast.LENGTH_SHORT).show(); 
     } else { 
      Toast.makeText(this, "Database Missing", Toast.LENGTH_SHORT).show(); 
     } 

    } 

    catch(Exception e){ 

     Log.e("CONTACTS ERROR", "Error Creating Database"); 

    } 

    // Make buttons clickable since the database was created 
    addContactButton.setClickable(true); 
    deleteContactButton.setClickable(true); 
    getContactsButton.setClickable(true); 
    deleteDBButton.setClickable(true); 

} 

public void addContact(View view) { 

    // Get the contact name and email entered 
    String contactName = nameEditText.getText().toString(); 
    String contactEmail = emailEditText.getText().toString(); 

    // Execute SQL statement to insert new data 
    contactsDB.execSQL("INSERT INTO contacts (name, email) VALUES ('" + 
      contactName + "', '" + contactEmail + "');"); 

} 

public void getContacts(View view) { 

    // A Cursor provides read and write access to database results 
    Cursor cursor = contactsDB.rawQuery("SELECT * FROM contacts", null); 

    // Get the index for the column name provided 
    int idColumn = cursor.getColumnIndex("id"); 
    int nameColumn = cursor.getColumnIndex("name"); 
    int emailColumn = cursor.getColumnIndex("email"); 

    // Move to the first row of results 
    cursor.moveToFirst(); 

    String contactList = ""; 

    // Verify that we have results 
    if(cursor != null && (cursor.getCount() > 0)){ 

     do{ 
      // Get the results and store them in a String 
      String id = cursor.getString(idColumn); 
      String name = cursor.getString(nameColumn); 
      String email = cursor.getString(emailColumn); 

      contactList = contactList + id + " : " + name + " : " + email + "\n"; 

      // Keep getting results as long as they exist 
     }while(cursor.moveToNext()); 

     contactListEditText.setText(contactList); 

    } else { 

     Toast.makeText(this, "No Results to Show", Toast.LENGTH_SHORT).show(); 
     contactListEditText.setText(""); 

    } 

} 

public void deleteContact(View view) { 

    // Get the id to delete 
    String id = idEditText.getText().toString(); 

    // Delete matching id in database 
    contactsDB.execSQL("DELETE FROM contacts WHERE id = " + id + ";"); 

} 

public void deleteDatabase(View view) { 

    // Delete database 
    this.deleteDatabase("MyContacts"); 

} 

@Override 
protected void onDestroy() { 

    contactsDB.close(); 

    super.onDestroy(); 
} 

} 

但是当我运行这段代码,它让我看到一个举杯消息数据库缺少,我会告诉你的XML也:

我的XML ...

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Create Database" 
    android:id="@+id/createDBButton" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:onClick="createDatabase"/> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Add Contact" 
    android:id="@+id/addContactButton" 
    android:layout_alignParentTop="true" 
    android:layout_toRightOf="@+id/createDBButton" 
    android:layout_toEndOf="@+id/createDBButton" 
    android:layout_marginLeft="10dp" 
    android:onClick="addContact" 
    android:clickable="false" /> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Delete Contact" 
    android:id="@+id/deleteContactButton" 
    android:layout_below="@+id/createDBButton" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:onClick="deleteContact" 
    android:clickable="false"/> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Get Contacts" 
    android:id="@+id/getContactsButton" 
    android:layout_below="@+id/createDBButton" 
    android:layout_toRightOf="@+id/deleteContactButton" 
    android:layout_toEndOf="@+id/deleteContactButton" 
    android:layout_marginLeft="10dp" 
    android:onClick="getContacts" 
    android:clickable="false"/> 

<EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/nameEditText" 
    android:layout_below="@+id/deleteContactButton" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:hint="Name" 
    android:layout_marginTop="5dp"/> 

<EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/emailEditText" 
    android:layout_below="@+id/nameEditText" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:hint="Email" 
    android:layout_marginTop="5dp" 
    android:inputType="textEmailAddress"/> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:inputType="number" 
    android:ems="10" 
    android:id="@+id/idEditText" 
    android:layout_below="@+id/emailEditText" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:hint="ID to Delete" 
    android:layout_marginTop="5dp"/> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Delete Database" 
    android:id="@+id/deleteDBButton" 
    android:onClick="deleteDatabase" 
    android:layout_below="@+id/idEditText" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:clickable="false" /> 

<EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:inputType="textMultiLine" 
    android:ems="10" 
    android:id="@+id/contactListEditText" 
    android:lines="8" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" /> 

我的问题也是,我检查了网站的教程点,他们没有使用任何代码。相反,他们使用数据库辅助类,他们使用插入方法并创建....并在其他类中使用它们。

那么什么是德里克之间的区别巴尼亚斯教程和教程点的网站,为什么德里克巴尼亚斯的代码给了我这个错误“数据库丢失”当我按在创建数据库按钮???

+0

@vogella作为一个在Android上使用SQLite的优秀教程,也许你应该看看它:http://www.vogella.com/tutorials/AndroidSQLite/article.html通常避免使用'openOrCreateDatabase'并且更喜欢使用解决方案SQLiteOpenHelper – orip

回答

-1

一切看起来不错,但你在数据库中创建表的查询是错误的,因为你正在执行它的每个操作,显示错误

contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " + 
       "(id integer primary key, name VARCHAR, email VARCHAR);"); 

,而不是使用使用这种

contactsDB.execSQL("CREATE TABLE IF NOT EXISTS contacts " + 
       "(_id INTEGER primary key, name VARCHAR, email VARCHAR);"); 

作为你通过id的方式是错误的。应根据标准像_id,还可以使用整数作为INTEGER

好运

+0

'_id'是一个标准,但没有必要。而且我不认为案例在列类型上很重要,所以我不确定你是否已经回答了 –

+0

@ cricket_007感谢您的指导。我已经根据我的android编码经验和我使用它的方式回答了它。但是请记住这一点,谢谢。 –

0

SQLiteOpenHelper版本的数据库文件,这样你就可以在架构更改迁移它们。它也为你打开数据库文件。

openOrCreateDatabase()只是打开/创建数据库文件,而SQLiteOpenHelper在内部使用。

为什么你得到“数据库丢失”是因为你创建/打开名为MyContacts的数据库文件,但测试是否存在另一个文件MyContacts.db

+0

感谢它的工作。但是现在我的新错误是插入语句,只要按下添加联系人按钮就会停止应用程序 – Marwan