2017-12-25 11 views
0

데이터베이스와 shelter.db 및 pets라는 테이블을 각각 작성한 상점에서 애완 동물을 볼 수있는 앱 만들기. SQLiteOpenHelper를 확장 한 PetDbHelper라는 클래스 인 데이터베이스와 관련된 모든 상수를 저장하는 계약 클래스를 만들었습니다. CatalogActivity와 EditorActivity의 두 가지 활동이 있습니다. CatalogActivity에서 테이블을 읽으려고하는데 여기서 각 열의 열 인덱스를 가져 오려고했지만 'weight'라는 마지막 열은 -1을 반환합니다. 이는 '열이 없습니다.'라는 것을 알 수 있으며 EditorActivity에서 테이블에 애완 동물을 넣으 려합니다. 모든 것을 검사했지만 내 코드에 어떤 문제가 있는지 전혀 알지 못합니다.SQLiteDatabase의 내 열 중 하나에 대해 -1을 얻는 중

/** 
* Displays list of pets that were entered and stored in the app. 
*/ 
public class CatalogActivity extends AppCompatActivity { 

private PetDbHelper mDbHelper; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_catalog); 
mDbHelper = new PetDbHelper(this); 

    private void displayDatabaseInfo() { 
    // To access our database, we instantiate our subclass of 
SQLiteOpenHelper 
    // and pass the context, which is the current activity. 
    // CREATE AND/OR OPEN A DATABASE TO READ FROM IT 
    SQLiteDatabase db = mDbHelper.getReadableDatabase(); 

    // String[] projection = {PetEntry._ID, PetEntry.COLUMN_PET_NAME, PetEntry.COLUMN_PET_BREED, PetEntry.COLUMN_PET_GENDER, PetEntry.COLUMN_PET_WEIGHT}; 
    Cursor cursor = db.query(PetEntry.TABLE_NAME, null, null, null, null, null, null); 
    //Cursor cursor = db.rawQuery("SELECT * FROM pets", null); 
    TextView displayView = (TextView) findViewById(R.id.text_view_pet); 

    try { 
     // Create a header in the Text View that looks like this: 
     // 
     // The pets table contains <number of rows in Cursor> pets. 
     // _id - name - breed - gender - weight 
     // 
     // In the while loop below, iterate through the rows of the cursor and display 
     // the information from each column in this order. 
     displayView.setText("The pets table contains " + cursor.getColumnCount() + " pets.\n\n"); 
     displayView.append(PetEntry._ID + " - " + 
       PetEntry.COLUMN_PET_NAME + " - " + 
       PetEntry.COLUMN_PET_BREED + " - " + 
       PetEntry.COLUMN_PET_GENDER + " - " + 
       PetEntry.COLUMN_PET_WEIGHT); 

     // Figure out the index of each column 
     int idColumnIndex = cursor.getColumnIndex(PetEntry._ID); 
     int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME); 
     int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED); 
     int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER); 
     int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT); 

     Toast.makeText(this, 
       "weight_index ?" + weightColumnIndex + "\n" 
       + "id_index" + idColumnIndex + "\n" 
       + "name_index" + nameColumnIndex + "\n" 
       + "breed_index" + breedColumnIndex + "\n" 
       + "gender_index" + genderColumnIndex , Toast.LENGTH_LONG).show(); 

} finally { 
     // Always close the cursor when you're done reading from it. This releases all its 
     // resources and makes it invalid. 
     cursor.close(); 
    } 

} 


@Override 
protected void onStart() { 
    super.onStart(); 
    displayDatabaseInfo(); 
} 
: 여기
package com.example.android.pets.data; 

import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

public class PetDbHelper extends SQLiteOpenHelper { 

private static final String DATABASE_NAME = "shelter.db"; 
private static final int DATABASE_VERSION = 1; 

public PetDbHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    String CREATE_TABLE = "CREATE TABLE " + PetsContract.PetEntry.TABLE_NAME 
      + " (" + PetsContract.PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
      + PetsContract.PetEntry.COLUMN_PET_NAME + " TEXT NOT NULL, " 
      + PetsContract.PetEntry.COLUMN_PET_BREED + " TEXT, " 
      + PetsContract.PetEntry.COLUMN_PET_GENDER + " INTEGER NOT NULL, " 
      + PetsContract.PetEntry.COLUMN_PET_WEIGHT + " INTEGER NOT NULL DEFAULT 0);"; 
    db.execSQL(CREATE_TABLE); 
} 

@Override 
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { 
} 
} 

데이터베이스와 관련된 CatalogActivity.java의 코드입니다 : 여기 SQLiteOpenHelper 클래스를 확장 PetDbHelper이야

package com.example.android.pets.data; 

import android.provider.BaseColumns; 

public final class PetsContract { 

public static final class PetEntry implements BaseColumns { 
    // CONSTANTS FOR TABLE AND COLUMN NAMES 
    public static final String TABLE_NAME = "pets"; 
    public static final String _ID = BaseColumns._ID; 
    public static final String COLUMN_PET_NAME = "name"; 
    public static final String COLUMN_PET_BREED = "breed"; 
    public static final String COLUMN_PET_GENDER = "gender"; 
    public static final String COLUMN_PET_WEIGHT = " weight"; 

    // CONSTANTS FOR GENDER 
    public static final int GENDER_UNKNOWN = 0; 
    public static final int GENDER_MALE = 1; 
    public static final int GENDER_FEMALE = 2; 
} 
} 

:

다음은 PetContract 클래스의

나는 그것이 많은 코드라는 것을 알고 있으며, 여기 EditorAct의 마지막 코드가있다. ivity.java 클래스 : 선도 공백이 SQL에서 무시됩니다

** 
* Allows user to create a new pet or edit an existing one. 
*/ 
public class EditorActivity extends AppCompatActivity { 

/** EditText field to enter the pet's name */ 
private EditText mNameEditText; 

/** EditText field to enter the pet's breed */ 
private EditText mBreedEditText; 

/** EditText field to enter the pet's weight */ 
private EditText mWeightEditText; 

/** EditText field to enter the pet's gender */ 
private Spinner mGenderSpinner; 

/** 
* Gender of the pet. The possible values are: 
* 0 for unknown gender, 1 for male, 2 for female. 
*/ 
private int mGender = 0; 

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

    // Find all relevant views that we will need to read user input from 
    mNameEditText = (EditText) findViewById(R.id.edit_pet_name); 
    mBreedEditText = (EditText) findViewById(R.id.edit_pet_breed); 
    mWeightEditText = (EditText) findViewById(R.id.edit_pet_weight); 
    mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender); 

} 

private void addPet() { 
    String name = mNameEditText.getText().toString().trim(); 
    String breed = mBreedEditText.getText().toString().trim(); 
    int weight = Integer.parseInt(mWeightEditText.getText().toString().trim()); 

    ContentValues values = new ContentValues(); 
    values.put(COLUMN_PET_NAME, name); 
    values.put(COLUMN_PET_BREED, breed); 
    values.put(COLUMN_PET_GENDER, mGender); 
    values.put(COLUMN_PET_WEIGHT, weight); 

    PetDbHelper mDbHelper = new PetDbHelper(this); 
    SQLiteDatabase db = mDbHelper.getWritableDatabase(); 

    long result = db.insert(TABLE_NAME, null, values); 

    if (result != -1) { 
     Toast.makeText(this, "Pet saved with id: " + result, Toast.LENGTH_SHORT).show(); 
    } else {Toast.makeText(this, "Error with saving pet", Toast.LENGTH_SHORT).show();} 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu options from the res/menu/menu_editor.xml file. 
    // This adds menu items to the app bar. 
    getMenuInflater().inflate(R.menu.menu_editor, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // User clicked on a menu option in the app bar overflow menu 
    switch (item.getItemId()) { 
     // Respond to a click on the "Save" menu option 
     case R.id.action_save: 
      // Save pet into the database 
      addPet(); 
      // Exit the activity 
      finish(); 
      return true; 
     // Respond to a click on the "Delete" menu option 
     case R.id.action_delete: 
      // Do nothing for now 
      return true; 
     // Respond to a click on the "Up" arrow button in the app bar 
     case android.R.id.home: 
      // Navigate back to parent activity (CatalogActivity) 
      NavUtils.navigateUpFromSameTask(this); 
      return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

}

+2

'COLUMN_PET_WEIGHT = "weight"'에 빈 공간이 있습니다. 아마도 그게 문제입니까? –

+0

도움을 주신데 감사드립니다. 다음 번에는 모든 집중력으로 코드를 작성하겠습니다. –

답변

0

(회 전자 개체와 관련된 코드를 제외)하지만지도 키에 중요한 - 열 이름과 인덱스는 기본적으로지도에 저장된다 getColumnIndex()으로 액세스 할 수 있습니다.

여기에 선행 공백을 제거하십시오.

+0

도와 주셔서 감사합니다. –