在SQLiteDatabase中为我的一个列获取-1

时间:2017-12-25 18:02:45

标签: java android sqlite

创建一个应用程序,用于在商店中查看宠物,我在其中分别创建了一个数据库和一个名为shelter.db和pets的表。我创建了一个契约类来存储与数据库相关的所有常量,一个名为PetDbHelper的类扩展了SQLiteOpenHelper。我有两个活动CatalogActivity和EditorActivity。在CatalogActivity中,我正在尝试读取表格,在这里我尝试获取每列的列索引,但是名为“weight”的最后一列返回-1,这意味着您可能知道'没有列存在'并且在EditorActivity中,我我试图在桌子上插入宠物。我已经检查了所有内容,但不知道我的代码有什么问题。

这是PetContract类:

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;
}
}

这是扩展SQLiteOpenHelper类的PetDbHelper:

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代码:

/**
 * 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();
}

我知道这是很多代码,这里是EditorActivity.java类的最后一段代码:(排除了与spinner对象相关的代码)

**
 * 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);
}

}

1 个答案:

答案 0 :(得分:0)

在SQL中忽略前导空格但在地图键中很重要 - 列名称及其索引基本上存储在您可以使用getColumnIndex()访问的地图中。

public static final String COLUMN_PET_WEIGHT = " weight";

删除此处的前导空格。