Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了适用于Android的SQLite DB问题大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 Android的新手,并且一直在关注教程来创建应用程序.我在将数据插入数据库方面遇到了很大困难.我已经尝试了所有我无法想到的东西.数据库类是:

package com.mckallip.beerOnTheWall;

import android.content.ContentValues;
import android.content.Context;
import android.database.cursor;
import android.database.sqlException;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
import android.util.Log;

public class DatabaseUtil{

    private static final String TAG = "DatabaseUtil";

/**
 * Database Name
 */
private static final String DATABASE_NAME = "Beer_Database";

/**
 * Database Version
 */
private static final int DATABASE_VERSION = 1;

/**
 * Table Name
 */
private static final String DATABASE_TABLE = "Beer_List";

/**
 * Table columns
 */
public static final String KEY_BEER_NAME = "beer_name";
public static final String KEY_BEER_STYLE = "beer_style";
public static final String KEY_BREWERY = "beer_brewery";
public static final String KEY_ABV = "beer_abv";
public static final String KEY_BEER_score = "beer_score";
public static final String KEY_BEER_IMAGE = "beer_image";
public static final String KEY_BEER_COMMENTS = "beer_comments";
public static final String KEY_ROWID = "_id";

/**
 * Database creation sql statement
 */
private static final String CREATE_BEER_TABLE =
    "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_BEER_NAME + " TEXT," + KEY_BEER_STYLE + " TEXT," + KEY_BREWERY + " TEXT," + KEY_ABV + " TEXT," + KEY_BEER_score + "TEXT," + KEY_BEER_IMAGE + " TEXT," + KEY_BEER_COMMENTS + "TEXT );";

/**
 * Context
 */
private final Context mCtx;

private DatabaseHelper mDbHelper;
private sqliteDatabase mDb;


/**
 * Inner private class. Database Helper class for creaTing and updating database.
 */
private static class DatabaseHelper extends sqliteOpenHelper {
    DatabaseHelper(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_version);
    }
    /**
     * onCreate method is called for the 1st time when database doesn't exists.
     */
    @Override
    public void onCreate(sqliteDatabase db) {
        Log.i(tag,"CreaTing DataBase: " + CREATE_BEER_TABLE);
        db.execsql(CREATE_BEER_TABLE);
    }
    /**
     * onUpgrade method is called when database version changes.
     */
    @Override
    public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
        Log.w(tag,"Upgrading database from version " + oldVersion + " to "
                + newversion);
    }
}
protected sqliteDatabase getDataBase(){
    return mDb;
}
/**
 * Constructor - takes the context to allow the database to be
 * opened/created
 *
 * @param ctx the Context within which to work
 */
public DatabaseUtil(Context ctX) {
    this.mCtx = ctx;
}
/**
 * This method is used for creaTing/opening connection
 * @return instance of DatabaseUtil
 * @throws sqlException
 */
public DatabaseUtil open() throws sqlException {
    mDbHelper = new DatabaseHelper(mCtX);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}
/**
 * This method is used for closing the connection.
 */
public void close() {
    mDbHelper.close();
}

/**
 * This method is used to create/insert new record Beer record.
 * @param sbeer_name
 * @param sbeer_style
 * @param sbeer_score
 * @param sbrewery
 * @param sabv
 * @param simageLoc
 * @param scomments
 * @return long
 */
public long createBeer(String beer_name,String beer_style,String beer_score,String brewery,String abv,String imageLoc,String comments) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_BEER_NAME,beer_Name);
    initialValues.put(KEY_BEER_STYLE,beer_stylE);
    initialValues.put(KEY_BREWERY,brewery);
    initialValues.put(KEY_ABV,abv);
    initialValues.put(KEY_BEER_score,beer_score);
    initialValues.put(KEY_BEER_IMAGE,imageLoc);
    initialValues.put(KEY_BEER_COMMENTS,comments);
    return mDb.insert(DATABASE_TABLE,initialValues);
}
/**
 * This method will delete Beer record.
 * @param rowId
 * @return Boolean
 */
public Boolean deleteBeer(long rowId) {
    return mDb.delete(DATABASE_TABLE,KEY_ROWID + "=" + rowId,null) > 0;
}

/**
 * This method will return cursor holding all the Beer records.
 * @return cursor
 */
public cursor fetchAllBeers() {
    return mDb.query(DATABASE_TABLE,new String[] {KEY_ROWID,KEY_BEER_NAME,KEY_BEER_STYLE,KEY_BREWERY,KEY_ABV,KEY_BEER_score,KEY_BEER_IMAGE,KEY_BEER_COMMENTS},null);
}

/**
 * This method will return cursor holding the specific Beer record.
 * @param id
 * @return cursor
 * @throws sqlException
 */
public cursor fetchBeer(long id) throws sqlException {
    cursor mcursor =
        mDb.query(true,DATABASE_TABLE,KEY_BEER_COMMENTS
                    },KEY_ROWID + "=" + id,null);
    if (mcursor != null) {
        mcursor.moveToFirst();
    }
    return mcursor;
}

/**
 * This method will update Beer record.
 * @param id
 * @param name
 * @param standard
 * @return Boolean
 */
public Boolean updateBeer(int id,String beer_name,String comments) {
    ContentValues args = new ContentValues();
    args.put(KEY_BEER_NAME,beer_Name);
    args.put(KEY_BEER_STYLE,beer_stylE);
    args.put(KEY_BREWERY,brewery);
    args.put(KEY_BEER_score,beer_score);
    args.put(KEY_ABV,abv);
    args.put(KEY_BEER_IMAGE,imageLoc);
    args.put(KEY_BEER_COMMENTS,comments);
    return mDb.update(DATABASE_TABLE,args,null) > 0;
}
}

添加数据的类是:

package com.mckallip.beerOnTheWall;

    import android.content.Context;
    import android.content.Intent;
    import android.database.sqlite.sqliteDatabase;
    import android.os.bundle;
    import android.view.View;
    import android.view.View.onClickListener;
    import android.widget.button;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    public class AddBeerActivity extends BeerOnTheWallActivity {
        private EditText et1;
        private EditText et2;
        private EditText et3;
        private EditText et4;
        private Spinner score_spin;
        private EditText et5;

        @Override
        public void onCreate(Bundle savedInstanceStatE) {
            super.onCreate(savedInstanceStatE);
            setContentView(R.layout.add_beer);
            mDatabase.open();
            Context e = getApplicationContext();
            String test = "read only";
            if (mDatabase.getDataBase().isReadOnly()){
                test = "Not ReadOnly" + mDatabase.getDataBase().getPath();

            }
            Toast t = Toast.makeText(e,test,2);
            t.show();
            et1 = (EditText) findViewById(R.id.add_beer_Name);
            et2 = (EditText)findViewById(R.id.add_beer_stylE);
            et3 = (EditText) findViewById(R.id.add_brewery);
            et4 = (EditText) findViewById(R.id.add_abv);
            score_spin = (Spinner) findViewById(R.id.score_spinner);
            et5 = (EditText) findViewById(R.id.add_comments);

            ((Button)findViewById(R.id.add_submit)).setOnClickListener(new OnClickListener() {
                public void onClick( View v ){
                    if (mDatabase.getDataBase().isReadOnly())mDatabase.open();
                    long beer_Id = mDatabase.createBeer( et1.toString(),et2.toString(),score_spin.toString(),et3.toString(),et4.toString(),"image",et5.toString() );
                    Context context = getApplicationContext();
                    CharSequence text = "Your beer was added at database position " + beer_Id;
                    if ( beer_Id == -1 ){
                        text = "There was an error and the beer Could not be added.";
                    }
                    Toast toast = Toast.makeText(context,text,2);
                    toast.show();

                    // reset form
                    if ( beer_Id != -1 ){
                        et1.setText(null);
                        et2.setText(null);
                        et3.setText(null);
                        et4.setText(null);
                        et5.setText(null);
                    }
                }
            });

         // Handle Go to List button
            final Button gotoList = (Button) findViewById(R.id.beer_list);
            gotoList.setOnClickListener(new View.onClickListener() {
                public void onClick(View v) {

                    // Go to other activity that displays beer list
                    Intent intent = new Intent(AddBeerActivity.this,BeerListActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

添加了toast作为尝试和调试它的方法.第一个声称它是只读的,我无法弄清楚为什么或如何使它可写.

我还将BeerOnTheWallActivity中的DatabaseUtil实例化为静态变量,因此……

public class BeerOnTheWallActivity extends Activity {
    protected DatabaseUtil mDatabase = null; 
    //protected cursor mcursor = null;
    //protected sqliteDatabase mDB = null;

    @Override
    protected void onCreate(Bundle savedInstanceStatE) {
        super.onCreate(savedInstanceStatE);

        mDatabase = new DatabaseUtil(this.getApplicationContext());
        mDatabase.open();

    }

当我按下按钮添加数据时,错误日志指出:

我想这就是全部.任何帮助将非常感激.

解决方法

请检查下面

你的代码

private static final String CREATE_BEER_TABLE =
    "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_BEER_COMMENTS + "TEXT );";

改成使用了这个

private static final String CREATE_BEER_TABLE =
    "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_BEER_score + " TEXT," + KEY_BEER_COMMENTS + " TEXT );";

大佬总结

以上是大佬教程为你收集整理的适用于Android的SQLite DB问题全部内容,希望文章能够帮你解决适用于Android的SQLite DB问题所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。