2012-03-03 2 views
1

여러 데이터베이스를 사용하는 앱이 있습니다. 현재 나는 그 중 하나만 가지고 문제가 있습니다. 달력에 대한 이벤트를 데이터베이스에 저장합니다. 그 SQLiteOpenHelper는 다음과 같습니다Android SQLiteDatabase를 삽입하거나 쿼리 할 수 ​​없습니다.

public class PlanSQLiteHelper extends SQLiteOpenHelper { 

//The database version. 
public static final int VERSION = 1; 

//The String keys of the database name and columns. 
public static final String DB_NAME = "plans_db.sqlite"; 
public static final String PLANS_TABLE = "plans"; 
public static final String PLAN_ID = "id"; 
public static final String PLAN_NAME = "name"; 
public static final String PLAN_YEAR = "year"; 
public static final String PLAN_MONTH = "month"; 
public static final String PLAN_DAY = "day"; 
public static final String PLAN_PRIORITY = "priority"; 
public static final String PLAN_TIME = "time"; 
public static final String PLAN_END = "end"; 
public static final String SET_APPT = "set_appt"; 
public static final String PLAN_ALARM = "alarm"; 


public PlanSQLiteHelper(Context context) { 
    super(context, DB_NAME, null, VERSION); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    createTable(db); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } 

private void createTable(SQLiteDatabase db) { 

    db.execSQL(
      "create table " + PLANS_TABLE + " (" + 
      PLAN_ID + " integer primary key autoincrement not null, " + 
      PLAN_NAME + " text, " + 
      PLAN_YEAR + " integer, " + 
      PLAN_MONTH + " integer, " + 
      PLAN_DAY + " integer, " + 
      PLAN_PRIORITY + " integer, " + 
      PLAN_TIME + " integer, " + 
      PLAN_END + " integer, " + 
      SET_APPT + " integer, " + 
      PLAN_ALARM + " integer);"); 
} 
} 

이는 과정이다 : 사용자는 (A PlanItem라는) 새로운 일정 항목을 만들 수있는 화면으로 이동합니다. 특정 옵션이 있으며, 원하는 옵션을 선택하고 "ok"를 누르십시오. PlanItem이 만든처럼 보이는 응용 프로그램에 대한 응용 프로그램 클래스의 메소드에 전달됩니다 항목을 작성하거나 편집 된 경우 부울 인 newItem 그냥 방법을 알려줍니다

/** 
* Called to save a PlanItem to the SQLiteDatabase. 
* @param item = the item to save to the database. 
* @param newItem = true if the item is new, false if it exists but was edited. 
* @return true if successful, false otherwise. 
*/ 
public boolean savePlanItem(PlanItem item, boolean newItem) { 

    try { 

     //Create the ContentValues. 
     ContentValues values = new ContentValues(); 

     //Put the values in. 
     values.put(PLAN_NAME, item.getName()); 
     values.put(PLAN_YEAR, item.getYear()); 
     values.put(PLAN_MONTH, item.getMonth()); 
     values.put(PLAN_DAY, item.getDay()); 
     values.put(PLAN_TIME, item.getTime()); 
     values.put(PLAN_END, item.getEnd()); 
     values.put(SET_APPT, item.isSetAppt() ? 1 : 0); 
     values.put(PLAN_PRIORITY, item.getPriorityInt()); 
     values.put(PLAN_ALARM, item.isAlarm() ? 1 : 0); 

     if (newItem) { 

      //Put into the database. 
      long id = plansDatabase.insert(PLANS_TABLE, null, values); 

      if (id == -1) { 
       return false; 
      } 
     } 
     else { 

      //Update the database. 
      String where = String.format("%s = ?", PLAN_ID); 
      plansDatabase.update(PLANS_TABLE, values, where, new String[] { item.getId() + "" }); 
     } 

    } 
    catch (Exception e) { 
     return false; 
    } 

    //Since it succeeded, return true. 
    return true; 
} 

. 내 문제는 창조에 있습니다. 보시다시피 SQLiteDatabase.insert() 메서드를 사용합니다. 심지어 새로운 행의 id를 잡고 -1과 비교하여 테스트합니다 (Android 설명서에 따라 오류가있는 경우 -1을 반환 함). 그렇더라도이 메서드는 true를 반환하므로 올바르게 저장됩니다. 그런 다음 저장되는 즉시 사용자가 항목을 만들 수있는 활동이 끝나고 활동을 표시하는 활동으로 돌아갑니다. onResume()에서 Application 클래스를 호출하여 해당 일에 대한 PlanItem을 가져옵니다. 모양은 다음과 같습니다.

/** 
* Called to get the agenda items for a particular day. 
* @param date = the date to get agenda items for. 
* @return the ArrayList of PlanItems for the day. 
*/ 
public ArrayList<PlanItem> getDailyAgenda(Date d) { 

    //Make a new date. 
    Date date = new Date(d.getDay(), d.getMonth(), d.getYear()); 

    //Create the ArrayList. 
    ArrayList<PlanItem> items = new ArrayList<PlanItem>(); 

    //Set up a query. 
    Cursor cursor = plansDatabase.query(PLANS_TABLE, new String[] {PLAN_ID, PLAN_NAME, PLAN_YEAR, 
      PLAN_MONTH, PLAN_DAY, PLAN_PRIORITY, PLAN_TIME, PLAN_END, SET_APPT, PLAN_ALARM}, 
      String.format(" %s = ? AND %s = ? AND %s = ? ", PLAN_YEAR, PLAN_MONTH, PLAN_DAY), 
      new String[] {String.valueOf(date.getYear()), String.valueOf(date.getMonth()), 
      String.valueOf(date.getDay())}, null, null, null); 

    //Move the cursor to the first position. 
    cursor.moveToFirst(); 

    //If there are items... 
    if (!cursor.isAfterLast()) { 

     //Initialize variables. 
     long id; 
     String name; 
     int year, month, day, time, end, priority; 
     boolean setAppt, alarm; 
     PlanItem item; 


     //Go through the database and get everything. 
     do { 

      //Get the values. 
      id = cursor.getLong(0); 
      name = cursor.getString(1); 
      year = cursor.getInt(2); 
      month = cursor.getInt(3); 
      day = cursor.getInt(4); 
      priority = cursor.getInt(5); 
      time = cursor.getInt(6); 
      end = cursor.getInt(7); 
      setAppt = cursor.getInt(8) == 1; 
      alarm = cursor.getInt(9) == 1; 

      //Create a PlanItem and add it to the ArrayList. 
      item = new PlanItem(id, name, year, month, day, 
        priority, time, end, setAppt, alarm); 
      items.add(item); 

     } while (cursor.moveToNext()); 
    } 

    //Close the cursor. 
    cursor.close(); 

    //Return the items. 
    return items; 
} 

개체 날짜는 Java 개체가 아닌 내 자신의 개체입니다. 그것은 내가 필요한 것을위한 방법만을 포함합니다.

디버거에서 쿼리를 확인하고 다시 검사했습니다. SQLite 규칙을 따릅니다. 하지만 그날 새 항목을 만든 후에도 데이터베이스에서 아무 것도 꺼내지 않습니다. return items; 행으로 이동하여 빈 ArrayList를 리턴합니다. 항목이 잘못된 날과 함께 저장되었는지 주위의 시절로 이동했지만 그렇지는 않습니다. 또한 데이터베이스에 일, 월 및 연도를 삽입하는 것을 확인했습니다. 그들은 옳다.

나는 stackoverflow 여기에 왔고 대답을 찾을 수 없었다.

나는 내 삶에 대해 이것을 이해할 수 없다. 도와주세요.

내 첫 번째 질문이므로 내 질문을 개선하는 방법에 대한 의견을 보내 주시면 감사하겠습니다.

답변

0

좋습니다. 여기 있습니다. 나는 지금 어리 석다. 문제가 해결되었습니다. 그것이 작동하지 않는 이유는 특정 장소에서 MY OWN Date 객체 생성자에서 연대와 일을 뒤집었기 때문입니다. 나는 년, 월, 일을 질의 (그리고 물음표가 아닌)에 직접 넣은 후에 그것을 발견했다. 어쨌든, 이것이 좋은 학습 경험 이었기를 바랍니다.

0

삽입이 완료되었는지 확인하기 위해 savePlanItem() 함수에 예외를 기록해야합니다.

그냥 질문,이 함수에서 데이터베이스를 어디에서 열 수 있습니까?

+0

응용 프로그램 클래스의 onCreate() 메서드에서 엽니 다. 또한 -1에 대해 반환 된 ID를 확인하여 savePlanItem() 메서드에서 오류를 확인합니다 (오류가 발생하면 -1에 대한 -1이 반환 됨). 즉, 어쨌든 로그를 추가하여 다른 것이 있는지 확인하기 만하면됩니다. –

+0

나는 당신의 답변에 투표를 할 것이지만, 나는 충분한 평판이 없습니다. 도와 줘서 고마워. 내가 왜 문제가 있었는지 알고 싶다면 질문 페이지를보십시오. 꽤 당황 스럽네. 당신의 도움을 주셔서 감사합니다! –

관련 문제