2011-12-09 4 views
0

글쎄 SQLite DB에 관한 질문이 있습니다. 목록보기로 항목을 클릭하면 다음 활동을 표시하는 활동을 만들었습니다. 이것은 앱이 시작될 때 처음 표시되는 주요 활동입니다. 액티비티는 초기화하는 동안 테이블에 값을 삽입하는 것과 같습니다. DB의 테이블에는 기본 키와 고유 필드가있는 필드가 있습니다. 중복 필드가 다음 행에 추가되지 않도록 필드를 고유하게 선언했습니다. 새 행에 동일한 값을 삽입하지 않아야합니다. 값의 초기화 및 삽입은 첫 x ​​째 활동 자체의 onCreate에 선언됩니다. 하지만 여기서 문제는이 응용 프로그램을 닫았다가 다시 열면 Logcat에 "ButterflyDB에 값을 삽입하는 중 오류가 발생했습니다"라는 오류 메시지가 기록된다는 것입니다. 이 문제는 이미 데이터베이스가 있고 필드가 고유 한 것으로 선언되어 있다는 것을 알고 있습니다. 또한 첫 번째 활동에서 삽입 기능을 호출 할 때 활동을 표시하는 데 많은 시간이 걸립니다. 지연 시간이 거의 없으면 첫 번째 화면이 나타날 때마다 응용 프로그램이 DB에 값을 삽입하는 첫 번째 화면이 나타납니다.데이터베이스를 처리하는 방법 안드로이드에서 올바른 방법

다음과
package com.myambitionconsultants.butterflyworld; 

import android.app.ListActivity; 
import android.content.ContentValues; 
import android.content.Intent; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

public class ButterflyWorldActivity extends ListActivity { 
    private static final String TAG = ButterflyWorldActivity.class.getSimpleName(); 
    /** 
    * Declare the variables and objects. 
    * ButterflyDBAdapter - To initialize the DB, create the tables and store the values in it. 
    * ImageIDStorage - To store the Image drawable IDs into the table. 
    * String[], int[] - To access the arrays declared in the data.xml file. 
    * String - SQL statements to run when this activity is displayed. 
    * Cursor - To access the records in the row of the table to display. 
    */ 
    ButterflyDBAdapter dbAdapter; 
    ImageIDStorage imgIDStorage; 
    ButterflyDetailsStorage detailsStorage; 
    String[] levels, butterfly_common_names, butterfly_scientific_names, image_path, cat_id; 
    int [] drawableID; 
    int [] butterfly_id; 
    String sql_butterfly_cat, sql_drawable_id; 
    Cursor cur; 




    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     /** 
     * Initialize the declared variables. 
     * dbAdapter - Initialize with ButterflyDBAdapter object. 
     * imgIDStorage - Initialize with ImageIDStorage object. 
     * 
     * levels, butterfly_common_names, butterfly_scientific_names, image_path, butterfly_id, cat_id 
     * - Use the getStringArray() method to load each and every value from the XML. 
     */ 

     dbAdapter = new ButterflyDBAdapter(this); 
     imgIDStorage = new ImageIDStorage(this); 
     detailsStorage = new ButterflyDetailsStorage(this); 
     dbAdapter.createTable(); 
     levels = getResources().getStringArray(R.array.butterfly_categories); 
     butterfly_common_names = getResources().getStringArray(R.array.butterfly_common_names); 
     butterfly_scientific_names = getResources().getStringArray(R.array.butterfly_scientific_names); 
     //image_path = getResources().getStringArray(R.array.image_path); 
     butterfly_id = getResources().getIntArray(R.array.butterfly_id); 
     cat_id = getResources().getStringArray(R.array.category_id); 
     //drawables = getResources().getStringArray(R.array.drawable_array); 

     /** 
     * Method Calls. 
     * Insert the Butterfly Categories, Butterflies, ImageIDs in the database. 
     */ 
     insertButterflyCategory(); 
     insertButterfly(); 
     imgIDStorage.insertImageID_1(); 
     imgIDStorage.insertImageID_2(); 
     detailsStorage.insertButterflyDetails(); 
     /** 
     * SQL statement to select the Category Name from the ButterflyCategory Table. 
     * Initialize the cursor to execute the query from the table. 
     */ 
     sql_butterfly_cat = "Select " + ButterflyDBAdapter.COL_CATEGORY_NAME + " from " + ButterflyDBAdapter.BUTTERFLY_CATEGORY; 
     cur = dbAdapter.getSQLiteDB().rawQuery(sql_butterfly_cat, null); 


     /** 
     * After retrieving the rows from the cursor, store the category name values in the array. 
     * Move the cursor to the first. 
     * Till the last row value in the table, keep on adding the category names in the array. 
     */ 

     //After retrieving the rows from the cursor, store the category name values in the array. 
     String[] category = new String[cur.getCount()]; 
     Log.i(TAG, "Count: " + cur.getCount()); 

     cur.moveToFirst(); //Move the cursor to the first row. 
     for(int i = 0; i < cur.getCount(); i++){ 
      //Till the last row value in the table, keep on adding the category names in the array. 
      category[i] =cur.getString(cur.getColumnIndex(ButterflyDBAdapter.COL_CATEGORY_NAME)); 
      //Move the cursor to the next row 
      cur.moveToNext(); 
     } 

     /** 
     * Use the setListAdapter() method to display the category names in the list. 
     */ 
     setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, category)); 

     /** 
     * Use the getListView() method. 
     */ 
     ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 

     /** 
     * Manage the cursor 
     */ 
     startManagingCursor(cur); 

     /** 
     * Determine which category was clicked in the list. 
     * Pass the category name as extra in the bundle. 
     * Display the next activity with the values passed through the bundle. 
     */ 
     lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 

      String category_name = ((TextView) view).getText().toString(); 
      Intent i = new Intent(ButterflyWorldActivity.this, ShowCategory.class); 
      //Intent i2 = new Intent(ButterflyWorldActivity.this, .class); 
      i.putExtra("category_name", category_name); 
      Bundle bundle = new Bundle(); 

      switch(position){ 
      case 0: 
       bundle.putString("category_name", category_name); 
       //bundle.putInt("drawable1", R.drawable.tailed_jay_1); 
       //bundle.putInt("drawable2", R.drawable.blue_bottle_1); 
       //bundle.putInt("drawable3", R.drawable.common_raven_1); 
       i.putExtras(bundle); 
       startActivity(i); 
       break; 
      case 1: 
       bundle.putString("category_name", category_name); 
       //bundle.putInt("drawable1", R.drawable.common_wanderer_1); 
       //bundle.putInt("drawable2", R.drawable.common_jezabel_1); 
       //bundle.putInt("drawable3", R.drawable.psyche_1); 
       i.putExtras(bundle); 
       startActivity(i); 
       break; 
      case 2: 
       bundle.putString("category_name", category_name); 
       //bundle.putInt("drawable1", R.drawable.common_silverline_1); 
       //bundle.putInt("drawable2", R.drawable.grass_jewel_1); 
       //bundle.putInt("drawable3", R.drawable.monkey_puzzle_1); 
       i.putExtras(bundle); 
       startActivity(i); 
       break; 
      case 3: 
       bundle.putString("category_name", category_name); 
       //bundle.putInt("drawable1", R.drawable.leopard_1); 
       //bundle.putInt("drawable1", R.drawable.common_silverline_1); 
       //bundle.putInt("drawable2", R.drawable.peacock_pansy_1); 
       //bundle.putInt("drawable3", R.drawable.blue_oakleaf_1); 
       i.putExtras(bundle); 
       startActivity(i); 
       break; 
      case 4: 
       bundle.putString("category_name", category_name); 
       //bundle.putInt("drawable1", R.drawable.chestnut_bob_1); 
       //bundle.putInt("drawable2", R.drawable.golden_angle_1); 
       //bundle.putInt("drawable3", R.drawable.grass_demon_1); 
       //bundle.putInt("drawable3", R.drawable.psyche_1); 
       i.putExtras(bundle); 
       startActivity(i); 
       break; 
      }   
     } 

     }); 

    } 


    /** 
    * Insert the butterfly category names into the database. 
    * The number of values in the levels[] determines the number of 
    * rows to be put in the ButterflyCategory table. 
    */ 
    public void insertButterflyCategory(){ 

     for(int i = 0; i<levels.length;i++){ 
      ContentValues cv = new ContentValues(); 
      //cv.put(ButterflyDBAdapter.COL_CATEGORY_ID, i+1); 
      cv.put(ButterflyDBAdapter.COL_CATEGORY_NAME, levels[i]); 

      try{ 
       dbAdapter.getSQLiteDB().insert(ButterflyDBAdapter.BUTTERFLY_CATEGORY, null, cv); 
       //dbAdapter.getSQLiteDB().insertWithOnConflict(ButterflyDBAdapter.BUTTERFLY_CATEGORY, null, cv,SQLiteDatabase.CONFLICT_IGNORE); 
       //dbAdapter.getSQLiteDB().insertOrThrow(ButterflyDBAdapter.BUTTERFLY_CATEGORY, null, cv); 
      }catch(SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
     Log.i(TAG, "Category Values inserted in " + ButterflyDBAdapter.BUTTERFLY_CATEGORY); 
    } 
    /** 
    * Insert the butterfly details such as category id, common name, scientific name and detailed info into the database. 
    * The number of values in the butterfly_common_names[] determines the number of 
    * rows to be put in the Butterfly table. 
    */ 
    public void insertButterfly(){ 
     for(int i = 0; i<butterfly_common_names.length;i++){ 
      ContentValues cv = new ContentValues(); 

      cv.put(ButterflyDBAdapter.COL_BUTTERFLY_COMMON_NAME, butterfly_common_names[i]); 
      cv.put(ButterflyDBAdapter.COL_CAT_ID, Integer.parseInt(cat_id[i])); 
      cv.put(ButterflyDBAdapter.COL_BUTTERFLY_SCIENTIFIC_NAME, butterfly_scientific_names[i]); 
      try{ 
       dbAdapter.getSQLiteDB().insert(ButterflyDBAdapter.BUTTERFLY, null, cv); 
       //dbAdapter.getSQLiteDB().insertWithOnConflict(ButterflyDBAdapter.BUTTERFLY_CATEGORY, null, cv,SQLiteDatabase.CONFLICT_IGNORE); 
       //dbAdapter.getSQLiteDB().insertOrThrow(ButterflyDBAdapter.BUTTERFLY_CATEGORY, null, cv); 
      }catch(SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
     Log.i(TAG, "Butterfly Values inserted in " + ButterflyDBAdapter.BUTTERFLY); 
    } 

    /** 
    * Close the database and cursor on finish of activity. 
    */ 
    @Override 
    protected void onDestroy() { 
     // TODO Auto-generated method stub 
     super.onDestroy(); 
     dbAdapter.getSQLiteDB().close(); 
     cur.close(); 
     imgIDStorage.closeDB(); 
     detailsStorage.closeDB(); 
     //super.onDestroy(); 
    } 

    /** 
    * Close the database and cursor on finish of activity. 
    */ 
    @Override 
    protected void onPause() { 
     // TOD Auto-generated method stub 
     super.onPause(); 
     dbAdapter.getSQLiteDB().close(); 
     cur.close(); 
     imgIDStorage.closeDB(); 
     detailsStorage.closeDB(); 
     //super.onPause(); 
    } 
} 

이의 DDMS가 될 때 :

12-09 11:38:53.299: E/Database(1375): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 
12-09 11:38:53.299: E/Database(1375): at android.database.sqlite.SQLiteStatement.native_execute(Native Method) 
12-09 11:38:53.299: E/Database(1375): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55) 
12-09 11:38:53.299: E/Database(1375): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549) 
12-09 11:38:53.299: E/Database(1375): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410) 
12-09 11:38:53.299: E/Database(1375): at com.myambitionconsultants.butterflyworld.ButterflyWorldActivity.insertButterflyCategory(ButterflyWorldActivity.java:204) 
12-09 11:38:53.299: E/Database(1375): at com.myambitionconsultants.butterflyworld.ButterflyWorldActivity.onCreate(ButterflyWorldActivity.java:78) 
12-09 11:38:53.299: E/Database(1375): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
12-09 11:38:53.299: E/Database(1375): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 
12-09 11:38:53.299: E/Database(1375): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 
12-09 11:38:53.299: E/Database(1375): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 
12-09 11:38:53.299: E/Database(1375): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 
12-09 11:38:53.299: E/Database(1375): at android.os.Handler.dispatchMessage(Handler.java:99) 
12-09 11:38:53.299: E/Database(1375): at android.os.Looper.loop(Looper.java:123) 
12-09 11:38:53.299: E/Database(1375): at android.app.ActivityThread.main(ActivityThread.java:4627) 
12-09 11:38:53.299: E/Database(1375): at java.lang.reflect.Method.invokeNative(Native Method) 
12-09 11:38:53.299: E/Database(1375): at java.lang.reflect.Method.invoke(Method.java:521) 
12-09 11:38:53.299: E/Database(1375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
12-09 11:38:53.299: E/Database(1375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
12-09 11:38:53.299: E/Database(1375): at dalvik.system.NativeStart.main(Native Method) 
12-09 11:38:53.369: E/Database(1375): Error inserting CategoryName=Pieridae 
12-09 11:38:53.369: E/Database(1375): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 
12-09 11:38:53.369: E/Database(1375): at android.database.sqlite.SQLiteStatement.native_execute(Native Method) 
12-09 11:38:53.369: E/Database(1375): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55) 
12-09 11:38:53.369: E/Database(1375): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549) 
12-09 11:38:53.369: E/Database(1375): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410) 
12-09 11:38:53.369: E/Database(1375): at com.myambitionconsultants.butterflyworld.ButterflyWorldActivity.insertButterflyCategory(ButterflyWorldActivity.java:204) 
12-09 11:38:53.369: E/Database(1375): at com.myambitionconsultants.butterflyworld.ButterflyWorldActivity.onCreate(ButterflyWorldActivity.java:78) 
12-09 11:38:53.369: E/Database(1375): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
12-09 11:38:53.369: E/Database(1375): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 
12-09 11:38:53.369: E/Database(1375): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 
12-09 11:38:53.369: E/Database(1375): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 
12-09 11:38:53.369: E/Database(1375): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 
12-09 11:38:53.369: E/Database(1375): at android.os.Handler.dispatchMessage(Handler.java:99) 
12-09 11:38:53.369: E/Database(1375): at android.os.Looper.loop(Looper.java:123) 
12-09 11:38:53.369: E/Database(1375): at android.app.ActivityThread.main(ActivityThread.java:4627) 
12-09 11:38:53.369: E/Database(1375): at java.lang.reflect.Method.invokeNative(Native Method) 
12-09 11:38:53.369: E/Database(1375): at java.lang.reflect.Method.invoke(Method.java:521) 
12-09 11:38:53.369: E/Database(1375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 
12-09 11:38:53.369: E/Database(1375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 
12-09 11:38:53.369: E/Database(1375): at dalvik.system.NativeStart.main(Native Method) 

어떻게 오류의 같은 종류를 처리하기 위해 다음과 같이 이에 대한

내 코드는?

답변

0

데이터베이스를 채우기위한 모든 코드, 리소스에서 데이터베이스로 데이터를 전송하는 모든 메소드를 실제 ButterflyDBAdapter로 이동해야합니다. 어댑터의 onCreate() 메소드 내에서 데이터베이스가 이미 존재하는지 확인하고, 존재하지 않으면 기본 데이터 세트로 채 웁니다. 그런 다음 데이터베이스에서 데이터를 삽입하고 검색하는 몇 가지 메소드를 노출 할 수 있습니다. 그런 다음 ButterflyWorldActivity 내에서 해당 메소드를 통해 데이터베이스와 상호 작용하면됩니다.

0

Activity.onCreate()에서 데이터베이스를 만들고 채우는 이유를 알지 못합니다. 이것은 처음 출시 될 때 한 번만 수행하면됩니다.

ButterflyDBAdapter에서 SQLiteOpenHelper를 확장하는 클래스가 있습니까? 그렇다면 SQLiteOpenHelper의 onCreate() 핸들러에서 데이터베이스를 만들고 채워야합니다. ButterflyDBAdapter 코드를 게시 할 수 있습니까?

1

로그를 볼 때 오류는 "제약 조건 실패"입니다. 이는 null 값이 아닌 열 또는 기본 키가있는 열에 null 값을 삽입하려고 함을 의미합니다.

아니면 중복 된 값을 기본 키 또는 고유 키가있는 열에 삽입하려고합니다.

그런 다음 값을 삽입하기 전에 표를 삭제할 수 있습니다. 앱이 처음 시작될 때 값이 삽입되기 때문에 다음에 앱에서 동일한 값을 삽입하려고합니다.

관련 문제