SQLite数据库不插入数据或查找项目(称为熊)

时间:2018-05-06 22:06:12

标签: java database android-studio android-sqlite

所以我一直在尝试使用预先存在的数据在Android Studio中创建一个sqlite数据库。我也试图向用户显示这些数据,虽然每次启动应用程序时它都会在我搜索数据库中的项目时崩溃,所以我不确定我是否正确创建了数据库。任何事都有帮助,非常感谢。

这是我的数据库助手

public class MyDBHandler {
myDbHelper myhelper;
public MyDBHandler(Context context)
{
    myhelper = new myDbHelper(context);
}

public void addBear(Bears bear)
{
    SQLiteDatabase dbb = myhelper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(myhelper.COLUMN_ID, bear.getID());
    values.put(myhelper.COLUMN_BEARNAME, bear.getbearname());
    values.put(myhelper.COLUMN_STUFFING, bear.getstuffing());
    values.put(myhelper.COLUMN_BEARHEALTH, bear.getbearhealth());
    values.put(myhelper.COLUMN_HEALTHCOST, bear.gethpcost());
    values.put(myhelper.COLUMN_HEALTHCOUNT, bear.gethpcount());
    values.put(myhelper.COLUMN_BEARATTACK, bear.getbearattack());

    dbb.insert(myDbHelper.TABLE_BEARS, null , values);
}

public Bears findBear(int bearID)
{
    SQLiteDatabase db = myhelper.getWritableDatabase();
    Bears bear = new Bears();
    String[] columns = 
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
            myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST, 
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};

    String query = myDbHelper.COLUMN_ID + " = ?";
    String[] selections = {String.valueOf(bearID)};

    Cursor cursor = 
    db.query(myDbHelper.TABLE_BEARS,columns,query,
    selections,null,null,null,null);

    if(null != cursor) {
            bear.setID(Integer.parseInt(cursor.getString(0)));
            bear.setbearname(cursor.getString(1));
            bear.setstuffing(Integer.parseInt(cursor.getString(2)));
            bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
            bear.sethpcost(Integer.parseInt(cursor.getString(4)));
            bear.sethpcount(Integer.parseInt(cursor.getString(5)));
            bear.setbearattack(Integer.parseInt(cursor.getString(6)));
        }
    db.close();
    return bear;
}


static class myDbHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME = "bearDB.db";    // Database 
    private static final String TABLE_BEARS = "bears";   // Table Name
    private static final int DATABASE_Version = 1;    // Database Version
    private static final String COLUMN_ID="_id";     // Column I (Primary Key)
    public static final String COLUMN_BEARNAME = "bearname";
    public static final String COLUMN_STUFFING = "stuffing";
    public static final String COLUMN_BEARHEALTH = "bearhealth";
    public static final String COLUMN_HEALTHCOST = "healthcost";
    public static final String COLUMN_HEALTHCOUNT = "healthcount";
    public static final String COLUMN_BEARATTACK = "bearattack";    // Column III
    String CREATE_BEARS_TABLE = "CREATE TABLE " +
            TABLE_BEARS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY," +
            COLUMN_BEARNAME + " TEXT," +
            COLUMN_STUFFING + " INTEGER," +
            COLUMN_BEARHEALTH + " INTEGER," +
            COLUMN_HEALTHCOST + " INTEGER, " +
            COLUMN_HEALTHCOUNT + " INTEGER, "+
            COLUMN_BEARATTACK + " INTEGER" +
            ")";
    private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_BEARS;
    private Context context;

    public myDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_Version);
        this.context=context;
    }

    public void onCreate(SQLiteDatabase db) {

        try {
            db.execSQL(CREATE_BEARS_TABLE);

            ContentValues beary = new ContentValues();
            beary.put(COLUMN_ID, 1 );
            beary.put(COLUMN_BEARNAME, "Beary");
            beary.put(COLUMN_STUFFING, 5);
            beary.put(COLUMN_BEARHEALTH, 10);
            beary.put(COLUMN_HEALTHCOST, 1);
            beary.put(COLUMN_HEALTHCOUNT, 0);
            beary.put(COLUMN_BEARATTACK,4);
            db.insert(TABLE_BEARS, null, beary);

            ContentValues honey = new ContentValues();
            honey.put(COLUMN_ID, 2 );
            honey.put(COLUMN_BEARNAME, "Honey");
            honey.put(COLUMN_STUFFING, 5);
            honey.put(COLUMN_BEARHEALTH, 8);
            honey.put(COLUMN_HEALTHCOST, 1);
            honey.put(COLUMN_HEALTHCOUNT, 0);
            honey.put(COLUMN_BEARATTACK, 3);
            db.insert(TABLE_BEARS, null, honey);

            ContentValues baobao = new ContentValues();
            baobao.put(COLUMN_ID, 3 );
            baobao.put(COLUMN_BEARNAME, "BaoBao");
            baobao.put(COLUMN_STUFFING, 5);
            baobao.put(COLUMN_BEARHEALTH,11);
            baobao.put(COLUMN_HEALTHCOST, 1);
            baobao.put(COLUMN_HEALTHCOUNT, 0);
            baobao.put(COLUMN_BEARATTACK, 3);
            db.insert(TABLE_BEARS, null, baobao);

        } catch (Exception e) {
           // do nothing
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            db.execSQL(DROP_TABLE);
            onCreate(db);
        }catch (Exception e) {
           // do nothing
        }
    }
}

这是我的活动页面,

public class BearSelectActivity extends AppCompatActivity {

TextView idBear, healthBear, hpcost, attackBear, abilityBear, stuffingBear;
public int hpcount;

EditText nameBear;

public int beartype = 1;
public String Fighter = "Fighter";
public String Healer = "Healer";
public String Tank = "Tank";
MyDBHandler helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bear_select);
    helper = new MyDBHandler(this);
    Button changeBear = (Button)findViewById(R.id.bearChange);
    idBear = (TextView) findViewById(R.id.bearID);
    nameBear = (EditText) findViewById(R.id.bearName);
    stuffingBear = (TextView) findViewById(R.id.bearStuffing);

    healthBear = (TextView) findViewById(R.id.bearHealth);
    hpcost = (TextView)findViewById(R.id.HPCOST);
    Button plushp = (Button)findViewById(R.id.plusbearhp);
    Button minushp = (Button)findViewById(R.id.minusbearhp);
    attackBear = (TextView) findViewById(R.id.bearAttack);


    abilityBear = (TextView) findViewById(R.id.bearAbility);


    abilityBear.setText(Fighter);

    Bears bear = helper.findBear(beartype);

    idBear.setText(String.valueOf(bear.getID()));
    nameBear.setText(String.valueOf(bear.getbearname()));
    healthBear.setText(String.valueOf(bear.getbearhealth()));
    attackBear.setText(String.valueOf(bear.getbearattack()));
    stuffingBear.setText(String.valueOf(bear.getstuffing()));
}

public void changeBearClick (View view){
    //MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
    ImageView image = (ImageView) findViewById(R.id.bearimage);
    //Bears bear;
    beartype++;
    beartype = bearmod(beartype, 3);
    if(beartype == 2) {
        image.setImageResource(R.drawable.bear2);
        abilityBear.setText(Healer);
    }
    else if(beartype == 3){
        image.setImageResource(R.drawable.bear3);
        abilityBear.setText(Tank);
    }
    else if(beartype == 1){
        image.setImageResource(R.drawable.bear1);
        abilityBear.setText(Fighter);
    }
    lookupBear(view);
}

public int bearmod(int a, int b){
    if (a < b && a > 0){
        return a;
    }
    else if(a == b){
        return a;
    }
    else if(a == 0 || a > b){
        a = 1;
    }
    return a;
}


public void lookupBear (View view) {
    Bears bear = helper.findBear(beartype);
    if(bear == null) {
        if (beartype == 1) {
            bear = new Bears(1, "Beary", 5, 10, 1, 0, 4);
            helper.addBear(bear);
        } else if (beartype == 2) {
            bear = new Bears(2, "Honey", 5, 8, 1, 0, 3);
            helper.addBear(bear);
        } else if (beartype == 3) {
            bear = new Bears(3, "Baobao", 5, 11, 1, 0, 2);
            helper.addBear(bear);
        }
    }
    if(bear != null) {
        idBear.setText(String.valueOf(bear.getID()));
        nameBear.setText(String.valueOf(bear.getbearname()));
        stuffingBear.setText(String.valueOf(bear.getstuffing()));
        healthBear.setText(String.valueOf(bear.getbearhealth()));
        hpcost.setText(String.valueOf(bear.gethpcost()));
        hpcount = bear.gethpcount();
        attackBear.setText(String.valueOf(bear.getbearattack()));
    }
}
}

1 个答案:

答案 0 :(得分:0)

我发现了很多问题。

定义列的以下行有一个额外的尾随逗号,所以: -

function req1() {
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(function (res) {return res.json()})
    .then(function (json) {
      var title = json.title;
      var body = json.body;
      var body = Math.ceil(str.length / 2);
      var s1 = str.slice(0, body);
      var s2 = str.slice(body);    
      document.getElementById("newsTitle").innerHTML = title;
      document.getElementById("newsContent").innerHTML = s1;
      document.getElementById("newsContent2").innerHTML = s2;
    });
}
req1();

应该是: -

String[] columns = 
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
            myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST, 
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};

返回Cursor时,它位于第一行(-1)之前。要从光标访问数据,您需要移动到光标内的一行。你不是这样做的。

此外,返回的Cursor不会为null。因此,检查null Cursor是没用的。

此外,使用硬编码偏移可能存在问题且不灵活。 Cursor有一个String[] columns = {myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING, myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST, myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK}; 方法,它将根据列名返回偏移量。

光标还有getColumnIndex以外的方法,可以直接提取其他类型的数据,例如getInt,getLong,getBlob ...... Cursor

我建议改变: -

getString

: -

if(null != cursor) {
        bear.setID(Integer.parseInt(cursor.getString(0)));
        bear.setbearname(cursor.getString(1));
        bear.setstuffing(Integer.parseInt(cursor.getString(2)));
        bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
        bear.sethpcost(Integer.parseInt(cursor.getString(4)));
        bear.sethpcount(Integer.parseInt(cursor.getString(5)));
        bear.setbearattack(Integer.parseInt(cursor.getString(6)));
    }
db.close();
return bear;
  

所以我不确定我是否正确创建数据库。

您可以添加的类here at :- Are there any methods that assist with resolving common SQLite issues? 包含一些可以帮助您了解数据库包含内容的方法。

您所要做的就是通过复制和粘贴代码(从第二个答案)添加该类,然后在 if(cursor.moveToFirst) { bear.setID(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_ID))); bear.setbearname(cursor.getString(cursor.getColumnIndex(myDbHelper.COLUMN_BEARNAME))); bear.setstuffing(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_STUFFING))); bear.setbearhealth(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_BEARHEALTH))); bear.sethpcost(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_HEALTHCOST))); bear.sethpcount(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_HEALTHCOUNT)))); bear.setbearattack(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_BEARATTACK)))); } cursor.close(); //<<< ADDED SHOULD ALWAYS CLOSE CURSORS WHEN DONE WITH THEM db.close(); return bear; 行之后添加以下内容: -

helper = new MyDBHandler(this);

运行应用程序时,请检查日志,它将在日志中显示DatabaseInformation。

  • 注意上面的代码是原则上的代码,尚未经过测试,因此可能包含简单错误。