2016-09-06 2 views
1

내가보고 있었다 데릭이 자습서를 banas 그가 데이터베이스를 작성 OpenOrCreate을 사용, 여기에 자바의 코드입니다 :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" /> 

제 문제는이 코드에서 아무것도 사용하지 않은 자습서 포인트 웹 사이트를 확인한 것입니다. 대신 데이터베이스 도우미 클래스를 사용하고 Insert 메서드를 사용하여 ... 만들고 다른 클래스에서 사용합니다.

derek banas 튜토리얼과 Tutorials 웹 사이트의 차이점은 무엇입니까? derek banas 코드가 데이터베이스에 누락되었을 때 "데이터베이스가 없습니다." 데이터베이스 버튼을 누를 때 ???

+0

안드로이드에서 SQLite 사용에 대한 훌륭한 자습서로 @vogella를 사용하십시오. 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로하고 당신이 스키마 변경을 통해 그들을 마이그레이션 할 수 있도록도 INTEGER

행운으로 정수

+0

'_id'는 표준이지만 필수는 아닙니다. 그리고 열 유형에 문제가 있다고 생각하지 않습니다. 따라서 –

+0

@ cricket_007 질문에 대한 답변을 확신 할 수 없습니다. 나는 내 안드로이드 코딩 경험과 그것을 사용한 방식대로 답변했습니다. 그러나 이것을 염두에 두셔도 좋습니다. –

0

SQLiteOpenHelper 버전의 데이터베이스 파일을 사용해야합니다. 또한 데이터베이스 파일을 엽니 다.

openOrCreateDatabase()은 데이터베이스 파일을 열거 나 만듭니다. SQLiteOpenHelper은 내부적으로이 파일을 사용합니다.

데이터베이스가 누락 된 이유는 MyContacts이라는 데이터베이스 파일을 만들거나 열지 만 다른 파일 MyContacts.db이 있는지 테스트했기 때문입니다.

+0

고마워요. 하지만 지금은 내 새로운 오류 삽입 문을 누르면 그것은 언제든지 연락처를 추가 버튼을 누르면 응용 프로그램을 중지합니다 – Marwan

관련 문제