I have a swipeview with two different views(fragments) via a viewpager. I now want these two pages to show different data from an sqllite database. The Problem is i cant figure out how to do this, from the main activity i am not able to access the views (TableLayout) on my fragments and from the fragments sourcecode i cant access the database because the adapter wont open (context of adapter is super.getActivity()). Is there any way to do this?
Code of the Fragment:
DBAdapter adapter = new DBAdapter(getActivity());
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if(container==null){
return null;
}
layout=(RelativeLayout)inflater.inflate(R.layout.layout_morning, container, false);
adapter.open();
adapter.close();
Code of DBAdapter:
private static String DB_NAME = "database.dat";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
public void close() {
if (db!=null){
db.close();
}
DBHelper.close();
}
Error is a NullPointerException
of course you can access a database inside a fragment, you just need to use getActivity(); instead of this.
Example to save an image file inside a fragment class:
db = new DatabaseHandler(getActivity());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
db.updateUser(imageInByte);
db.close();
Related
I have strange problem with my android app. I have some data and I saved that data in SQLite Database. And in this fragment I try to read my data from table using SimpleCursorAdapter
public class LogFragment extends Fragment{
private static SQLiteDatabase db;
private static SQLiteOpenHelper helper;
private static Context context;
private static ListView listView;
private static String senderOrReceiver;
private static SimpleCursorAdapter adapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
adapter = new SimpleCursorAdapter(context, R.layout.log_message, null,
new String[]{Constants.COMMAND, Constants.VALUE, Constants.TIME_STAMP, Constants.MESSAGE_ID, Constants.SESSION_ID, Constants.PARAMS},
new int[]{R.id.command, R.id.value, R.id.time_stamp, R.id.message_id, R.id.session_id, R.id.params}, 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_log, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
listView = (ListView) view.findViewById(R.id.listView);
}
#Override
public void onDestroy() {
super.onDestroyView();
if(db != null){
db.close();
}
}
public static void readFromDatabase(String sender){
senderOrReceiver = sender;
new DatabaseTalker().execute();
}
private static class DatabaseTalker extends AsyncTask <Void, Void, Cursor>{
#Override
protected Cursor doInBackground(Void... params) {
helper = new Database(context);
db = helper.getReadableDatabase();
return db.query(Constants.TABLE_NAME, null, null, null, null, null, null);
}
#Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
adapter.changeCursor(cursor);
listView.setAdapter(adapter);
}
}
}
and here's what I got in my ListView . I have six fields (Command, Value, Time Stamp, MessageID, SessionID, Params) and as you can see only one field is filled (for example) Command: On, Value: , Time Stamp: , MessageID: , SessionID: , Params: . and so on... Why I get this result?
EDIT:
Here how I write my data to database
public void addInfo(Information info){
SQLiteDatabase db = this.getWritableDatabase();
addToTable(db, Constants.COMMAND, info.getCommand());
addToTable(db, Constants.VALUE, info.getValue());
addToTable(db, Constants.TIME_STAMP, info.getTimeStamp());
addToTable(db, Constants.MESSAGE_ID, info.getMessageID());
addToTable(db, Constants.SESSION_ID, info.getSessionID());
addToTable(db, Constants.PARAMS, info.getParams());
db.close();
}
private static void addToTable(SQLiteDatabase db, final String TAG, String value){
ContentValues values = new ContentValues();
values.put(TAG, value);
db.insert(Constants.TABLE_NAME, null, values);
}
Your each addToTable() call inserts a new row that contains just one column value.
To insert a row with all the values, add the values to the same ContentValues and call insert() once.
I have a spinner. I want to load data from sqlite. I have try to load data with Activity class, it work but i want to load it in Fragment class and i got the method is undefined. There is any wrong ? What should i do ??
Sorry for my bad english..
This is Fragment class
public class InfoJadwal extends Fragment {
private DatabaseHandler dbhelper;
private SQLiteDatabase db = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbhelper = new DatabaseHandler(getActivity());
db = dbhelper.getWritableDatabase();
dbhelper.delAllData(db);
dbhelper.generateData(db);
View rootView = inflater.inflate(R.layout.info_jadwal, container,
false);
loadDataSpinner();
return rootView;
}
private void loadDataSpinner() {
Cursor wisataCursor;
Spinner colourSpinner = (Spinner) getView().findViewById(
R.id.spin_tujuan);
wisataCursor = dbhelper.fetchAllWisata(db);
startManagingCursor(wisataCursor);
String[] from = new String[] { dbhelper.TUJUAN };
int[] to = new int[] { R.id.tvDBViewRow };
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,
R.layout.db_view_row, wisataCursor, from, to);
colourSpinner.setAdapter(wisataAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
db.close();
} catch (Exception e) {
}
}
}
And this is class for DatabaseHandler.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "medantrain";
public static final String TUJUAN = "tujuan";
public static final String KEY_ID = "_id";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
// method createTable untuk membuat table WISATA
public void createTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS KOTA");
db.execSQL("CREATE TABLE if not exists KOTA (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "TUJUAN TEXT);");
}
// method generateData untuk mengisikan data ke table Wisata.
public void generateData(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(TUJUAN, "Binjai");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Rantau Prapat");
db.insert("KOTA", TUJUAN, cv);
cv.put(TUJUAN, "Tebing Tinggi");
db.insert("KOTA", TUJUAN, cv);
}
// method delAllAdata untuk menghapus data di table Wisata.
public void delAllData(SQLiteDatabase db) {
db.delete("KOTA", null, null);
}
public Cursor fetchAllWisata(SQLiteDatabase db) {
return db.query("KOTA", new String[] { KEY_ID, TUJUAN }, null, null,
null, null, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
createTable(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
replace
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(this,R.layout.db_view_row, wisataCursor, from, to);
with
SimpleCursorAdapter wisataAdapter = new SimpleCursorAdapter(getActivity(),R.layout.db_view_row, wisataCursor, from, to);
and replace
startManagingCursor(wisataCursor);
with
getActivity().startManagingCursor(wisataCursor);
but startManagingCursor(Cursor) in Activity is deprecated. see docs for more info http://developer.android.com/reference/android/app/Activity.html#startManagingCursor%28android.database.Cursor%29
SimpleCursorAdapter requires a Context reference but you are passing this which means a Fragment reference.
I have created DBAdapter class which is responsible for making a connection to a Database and does any query and finally close the connection.
I have another class which it is not inherited from Activity class(ReminderBeep), but i have to use my DBAdapter in this class.
Actually i don't know how can i manipulate the DBAdapter constructor to make the connection.*
The error is: The constructor DBAdapter(ReminderBeep) is undefined
DBAdapter is:
public class DBAdapter {
static final String DATABASE_NAME = "MyDB";
static final int DATABASE_VERSION = 2;
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void insert(String sql)
{
db.execSQL(sql);
}
}
BeepReminder is:
public class ReminderBeep
{
public void DeleteDailyActivities()
{
DBAdapter db=new DBAdapter(this);
db.open();
String sql="delete from DailyWorks";
db.insert(sql);
db.close();
}
}
ReminderBeep is not extendig Activity. But DBAdapter want a Context as paramter,
DBAdapter db=new DBAdapter(this);
this refers to ReminderBeep
I'm trying to create table in the sqlite, but it is showing error that table cannot be created. I have a same code but the database and table name are different. the fields are same. Also one doubt. Can't i create the different table in the same database containing the same fields.
DbAdapter.java
the code is as below.
public class DbAdapter {
private static final String DATABASE_NAME="bible1";
private static final String DATABASE_TABLE="test1";
private static final int DATABASE_VERSION=1;
public static final String KEY_ID="_id";
public static final String UNITS="units";
public static final String CHAPTERS="chapters";
private static final String CREATE_DATABASE="create table test1 (_id integer primary key autoincrement, units text not null, chapters text not null);";
private SQLiteHelper sqLiteHelper;
private static SQLiteDatabase sqLiteDatabase;
private Context context;
//constructor
public DbAdapter(Context c){
context = c;
}
private static class SQLiteHelper extends SQLiteOpenHelper{
public SQLiteHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_DATABASE);
MakeUnits();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public DbAdapter open() throws SQLException{
try{
sqLiteHelper = new SQLiteHelper(context);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}catch(NullPointerException ne){
Log.e("error in creating the table", "bye");
}
return this;
}
public void close(){
sqLiteHelper.close();
}
public static long MakeUnits()
{
ContentValues insert1 = new ContentValues();
insert1.put(UNITS, "Unit1");
insert1.put(CHAPTERS, "CHAPTER1");
return sqLiteDatabase.insert(DATABASE_TABLE,null,insert1);
}
public Cursor fetchAllNotes(){
return sqLiteDatabase.query(DATABASE_TABLE, new String[]{KEY_ID,UNITS,CHAPTERS}, null, null, null, null, null);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private DbAdapter Database;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listContent = (ListView) findViewById(android.R.id.list);
Database= new DbAdapter(this);
Database.open();
Cursor c = Database.fetchAllNotes();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It is giving error when the open() method is called. Couldn't figure it out.
in the logcat the error in the tag is that "error in creating the table"
You're trying to call sqLiteDatabase.insert inside MakeUnits, but this sqLiteDatabase variable is null until after you call getWritableDatabase. You should pass db to MakeUnits and call insert on db, not on sqLiteDatabase.
database will be created only when you make a call to
getWritableDatabase()/getReadableDatabase()
If you do not have permissions for a writable db, you will get a readable
db.
public SQLiteDatabase getWritableDB() {
try {
return helper.getWritableDatabase();
} catch (Exception e) {
return getReadableDB();
}
}
public SQLiteDatabase getReadableDB() {
return helper.getReadableDatabase();
}
The user is looking at a list LibraryFragment and clicks one of the options (Item1 or Item2), from there I wanted to show another list (GFragment) that is created dynamically from the items received from the database. In the logCat I get this error:
08-30 13:56:54.087: E/SqliteDatabaseCpp(22622): sqlite3_open_v2("/data/data/j.j.l.library.v11/databases/library_dev.db", &handle, 1, NULL) failed
Failed to open the database. Closing it.
Does anyone know what is wrong with the code or why it is doing this?
The code I am using for the database is:
public class DatabaseHelper {
private static String DB_PATH = "/data/data/j.j.l.library.v11/databases/";
private static String DB_NAME = "library_dev.db";
private SQLiteDatabase myDataBase;
public DatabaseHelper(){
}
//Open the database.
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
//Return the columns we want.
public List<String> getQueryColumn(String tableName, String[] columns){
Cursor cursor;
List<String> info = new ArrayList<String>();
cursor = myDataBase.query(tableName, columns, null, null, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
info.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return info;
}
//Close the Database.
public void closeDatabase() throws SQLException{
myDataBase.close();
}
}
Another List I am trying to create dynamically from the database:
public class GFragment extends ListFragment {
private DatabaseHelper gList;
public static final String GROLE = "role";
public static final String[] ROLENAME = {"name"};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
gList = new DatabaseHelper();
gList.openDatabase();
List<String> values = gList.getQueryColumn(GROLE, ROLENAME);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values));
gList.closeDatabase();
}
}
This is the list the user is looking at right before there is a call to retrieve the dynamic list from the database:
public class LibraryFragment extends ListFragment{
String[] libraryList = {"Item1", "Item2"};
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, libraryList));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
//Get the position the user clicked.
Fragment newFragment = null;
String listPosition = libraryList[position];
getListView().setItemChecked(position, true);
if(listPosition.equals("Item1")){
newFragment = new GFragment();
}else if (listPosition.equals("Item2")){
newFragment = new ITFragment();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.myFragments, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
}
It's because you don't create this database library_dev.db, so it's empty, resulting in a NULL reference; a closing operation is taken afterward.
You need to handle the creation/upgrade/remove of the database in a class which should extends from SQLiteOpenHelper first. Then use this class to get your database:
public class MyDatabaseHelper extends SQLiteOpenHelper { // blah...database create/upgrade handling }
MyDatabaseHelper myHelper = new MyDatabaseHelper(yourContext);
SQLiteDatabase myDatabase = myHelper.getReadableDatabase(); // now you can use `myDatabase` freely
You can refer to a proper guideline for this at: http://www.vogella.com/articles/AndroidSQLite/article.html