I need help with populating my different fragments with the relevant data from my helper class, before, I had separate helper classes for each of my database tables, but they each created a unique database name so I was creating a new instance of the database for each table without relating them, this was ok when I was only reading from and displaying data but now I need to relate my tables and display related data.
I have now put all of my database classes into the one databasehelper class and I need help figuring out how to create only one instance of the database and populate my fragments with the relevant data because although I am getting no android errors, the app will crash when I start any fragment with uses the database.
Here is my databasehelper class which creates all of the relevant sqlite database info.
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;
}
}
An example of the Vendors fragment which starts an instance of the vendors table information is shown here:
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;
}
}
此处显示了主 Activity 的 fragment 调用示例:
} 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();
如有任何帮助,我们将不胜感激。
最佳答案
可以创建存储库/DAO 模式。创建将处理所有数据库逻辑的类。拥有开放的 SQLite 实例不是一个好主意,而且没有任何意义。因此,您的 DAO 方法每次都会打开新实例 -> 进行事务 -> 关闭实例生命周期。 您可以阅读更多here 。祝你好运:)
关于java - Android SQLite 从 fragment 调用数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43684883/