从片段调用Android SQLite数据库

时间:2017-04-28 16:26:38

标签: java android sqlite android-sqlite

  

我需要帮助用我的助手类中的相关数据填充我的不同片段,之前我有单独的助手   我的每个数据库表的类,但它们每个都创建了一个唯一的   数据库名称,所以我正在创建一个新的数据库实例   每张桌子没有关联它们,当我只是阅读时这是好的   从显示数据,但现在我需要关联我的表和   显示相关数据。

     

我现在已将所有数据库类放入一个databasehelper类中,我需要帮助找出如何仅创建   数据库的一个实例,并使用。填充我的片段   相关数据,因为虽然我没有得到Android错误,该应用程序   当我使用数据库启动任何片段时会崩溃。

     

这是我的databasehelper类,它创建了所有相关的sqlite数据库信息。

    public class DatabaseHelper extends SQLiteOpenHelper {

        // Logcat tag
        private static final String LOG = "DatabaseHelper";

        public static final int DATABASE_VERSION = 1;

        //Database name
        public static final String DATABASE_NAME = "XXX.db";

        //Table names
        public static final String TABLE_USERS = "users_tbl";
        public static final String TABLE_EVENTS = "events_tbl";
        public static final String TABLE_VENDORS = "vendors_tbl";
        public static final String TABLE_MYEVENTS = "myevents_tbl";

        //Users table Columns
        public static final String COLUMN_USER_ID = "_id";
        public static final String COLUMN_USER_FNAME = "fname";
        public static final String COLUMN_USER_SNAME = "sname";
        public static final String COLUMN_USER_EMAIL = "email";
        public static final String COLUMN_USER_PASSWORD= "password";
        public static final String COLUMN_USER_USERNAME = "username";

        //Events table Columns
        public static final String COLUMN_EVENTS_ID = "_id";
        public static final String COLUMN_EVENTS_NAME = "event_name";
        public static final String COLUMN_EVENTS_DESCRIPTION = "event_description";
        public static final String COLUMN_EVENTS_DAY = "event_day";
        public static final String COLUMN_EVENTS_TIME = "event_time";
        public static final String COLUMN_EVENTS_DURATION = "event_duration";
        public static final String COLUMN_EVENTS_CAPACITY= "event_capacity";
        public static final String COLUMN_EVENTS_VENDORS_ID_FK = "vendor_ID";

        //Vendors table Columns
        public static final String COLUMN_VENDORS_ID = "_id";
        public static final String COLUMN_VENDORS_NAME = "vendor_name";
        public static final String COLUMN_VENDORS_DAY = "vendor_day";
        public static final String COLUMN_VENDORS_CUISINE = "vendor_cuisine";

        //MyEvents table Columns
        public static final String COLUMN_MYEVENTS_ID = "_id";
        public static final String COLUMN_MYEVENTS_EVENTS_ID_FK = "event_ID";
        public static final String COLUMN_MYEVENTS_USERS_USERNAME_FK = "username";

    //    SQLiteDatabase db; //declaring database variable

        //Table create statements
        public static final String TABLE_CREATE_USERS = "create table " +
                TABLE_USERS + "(" +
                COLUMN_USER_ID + " integer primary key not null," +
               COLUMN_USER_FNAME + " text not null," +
                COLUMN_USER_SNAME + " text not null," +
                COLUMN_USER_EMAIL + " text not null," +
                COLUMN_USER_PASSWORD + " text not null," +
                COLUMN_USER_USERNAME + " text not null);";

    //    public static final String TABLE_CREATE_EVENTS = "create table events_tbl (event_ID integer primary key not null," +
    //            "event_name text not null, event_description text not null, event_day text not null, event_time text not null, event_duration text not null, event_capacity integer not null, vendor_id integer not null);";

        public static final String TABLE_CREATE_EVENTS = "create table " +
                TABLE_EVENTS + "(" +
                COLUMN_EVENTS_ID + " integer primary key not null," +
                COLUMN_EVENTS_NAME + " text not null," +
                COLUMN_EVENTS_DESCRIPTION + " text not null," +
                COLUMN_EVENTS_DAY + " text not null," +
                COLUMN_EVENTS_TIME + " text not null," +
                COLUMN_EVENTS_DURATION + " text not null," +
                COLUMN_EVENTS_CAPACITY + " integer not null," +
                COLUMN_EVENTS_VENDORS_ID_FK + " integer not null);";

        public static final String TABLE_CREATE_VENDORS = "create table " +
                TABLE_VENDORS + "(" +
                COLUMN_VENDORS_ID + " integer primary key not null," +
                COLUMN_VENDORS_NAME + " text not null," +
                COLUMN_VENDORS_DAY + " text not null," +
                COLUMN_VENDORS_CUISINE + " text not null);";

        public static final String TABLE_CREATE_MYEVENTS = "create table " +
                TABLE_MYEVENTS + "(" +
                COLUMN_MYEVENTS_ID + " integer primary key not null" +
                COLUMN_MYEVENTS_EVENTS_ID_FK + " integer not null" +
                COLUMN_MYEVENTS_USERS_USERNAME_FK + " text not null);";

        //DatabaseHelper class constructor
        public DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // creating required tables
            db.execSQL(TABLE_CREATE_USERS);
            db.execSQL(TABLE_CREATE_EVENTS);
            db.execSQL(TABLE_CREATE_VENDORS);
            db.execSQL(TABLE_CREATE_MYEVENTS);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // on upgrade drop older tables
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_VENDORS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_MYEVENTS);

            // create new tables
            onCreate(db);
        }

        public void insertUsers(Users u)
        {
            SQLiteDatabase db = DatabaseHelper.this.getWritableDatabase();
            ContentValues values = new ContentValues();

            //Get the count of the users that are already present and passing the count as the ID
            String query = "SELECT * FROM users_tbl";
            Cursor cursor = db.rawQuery(query, null);
            int count = cursor.getCount();

            values.put(COLUMN_USER_ID, count);
            values.put(COLUMN_USER_FNAME, u.getFname());
            values.put(COLUMN_USER_SNAME, u.getSname());
            values.put(COLUMN_USER_EMAIL, u.getEmail());
            values.put(COLUMN_USER_PASSWORD, u.getPassword());
            values.put(COLUMN_USER_USERNAME, u.getUsername());

            db.insert(TABLE_USERS, null, values);
            db.close();
        }

        public void EventsInsert() {

            SQLiteDatabase db = DatabaseHelper.this.getWritableDatabase();

            ContentValues insertValues = new ContentValues();

            String query = "SELECT * FROM events_tbl";
            Cursor cursor = db.rawQuery(query, null);
            int count = cursor.getCount();

            if (cursor.getCount() == 0) {

                insertValues.put(COLUMN_EVENTS_ID, count++);
                insertValues.put(COLUMN_EVENTS_NAME, "Italian Pizza Making");
                insertValues.put(COLUMN_EVENTS_DESCRIPTION, "This event is perfect for pizza lovers! Learn how to make fresh Italian pizza dough, fresh marinara sauce, and what really makes an authentic Italian pizza!");
                insertValues.put(COLUMN_EVENTS_DAY, "Day: Saturday");
                insertValues.put(COLUMN_EVENTS_TIME, "Event Time: 1pm");
                insertValues.put(COLUMN_EVENTS_DURATION, "Event Duration: 1 Hour");
                insertValues.put(COLUMN_EVENTS_CAPACITY, 20);
                insertValues.put(COLUMN_EVENTS_VENDORS_ID_FK, 10);

                db.insert("events_tbl", null, insertValues);    

            }

        }

        //Get all Queries

        public Cursor getallEvents() {

            SQLiteDatabase db = this.getReadableDatabase();
            String query = "select " + COLUMN_EVENTS_ID + "_id,*" + " from " + TABLE_EVENTS;
            Cursor cursor = db.rawQuery(query, null);

            if (cursor != null) {
                cursor.moveToFirst();
            }

            return cursor;
        }

        public Cursor getallVendors() {

            SQLiteDatabase  db = this.getReadableDatabase();
            String query = "select " + COLUMN_VENDORS_ID + " from " + TABLE_VENDORS + "";
            Cursor cursor = db.rawQuery(query, null);

            if (cursor != null) {
                cursor.moveToFirst();
            }

            return cursor;
        }

        //Insert statements

        public void VendorsInsert() {

            SQLiteDatabase db = DatabaseHelper.this.getWritableDatabase();

            ContentValues insertValues = new ContentValues();

            String query = "SELECT * FROM vendors_tbl";
            Cursor cursor = db.rawQuery(query, null);
            int count = cursor.getCount();

            if (cursor.getCount() == 0) {

                //European Vendors

                insertValues.put(COLUMN_VENDORS_ID, count++);
                insertValues.put(COLUMN_VENDORS_NAME, "Villa Italia");
                insertValues.put(COLUMN_VENDORS_DAY, "Day: Saturday");
                insertValues.put(COLUMN_VENDORS_CUISINE, "Cuisine: Italian");

                db.insert("vendors_tbl", null, insertValues);

            }

        }

        public String searchPass(String username)
        {
            SQLiteDatabase db = this.getReadableDatabase();
            String query = "select username, password from " + TABLE_USERS + ";";
            Cursor cursor = db.rawQuery(query, null);
            String a, b; //a is username, b is password
            b = "not found";

            if(cursor.moveToFirst())
            {
                do {
                    a = cursor.getString(0);


                    if (a.equals(username))
                    {
                        b = cursor.getString(1);
                        break;
                    }
                }

                while(cursor.moveToNext());
            }

            return b;
        }

    }
  

此处显示了启动供应商表信息实例的供应商分片示例:

public class VendorsFragment extends Fragment {
    DatabaseHelper db;

    public static VendorsFragment newInstance() {
        VendorsFragment fragment = new VendorsFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_vendors, null, false);

        db = new DatabaseHelper(getActivity());

        db.VendorsInsert();

        Cursor cursor = db.getallVendors(); //gets all rows from database

        //these 2 arrays take data from database and place them within our listview

        String[] fromfieldnames = new String[]{DatabaseHelper.COLUMN_VENDORS_NAME, DatabaseHelper.COLUMN_VENDORS_CUISINE, DatabaseHelper.COLUMN_VENDORS_DAY};

        int[] toViewIDs = new int[]{R.id.vendorname, R.id.vendorday, R.id.vendorcuisine};

        SimpleCursorAdapter myCursorAdapter;

        myCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.listview_layout1, cursor, fromfieldnames, toViewIDs, 0);
        ListView myList = (ListView) view.findViewById(R.id.vendors_listview);
        myList.setAdapter(myCursorAdapter);

        myList.setDivider(new ColorDrawable(getContext().getResources().getColor(R.color.colorPrimary)));
        myList.setDividerHeight(1);

        return view;

    }
}

主要活动的片段调用示例如下所示:

} else if (id == R.id.nav_caterers) {

    VendorsFragment fragment = new VendorsFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

任何有关此的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

那么可以创建Repository / DAO模式。创建将处理所有数据库逻辑的类。拥有SQLite的开放实例并不是一个好主意,没有任何意义。所以你的DAO方法将打开新实例 - >进行交易 - >每次关闭实例生命周期。 您可以阅读更多here。祝你好运:)