Having an error connecting to my SQLite database - android

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

Related

Get all the data from one row in sqlitedatabase with the name_column and store it in listview

I have coded a RecyclerView where I search for data from my SQLiteDatabase with the SearchAdapter. The MaterialSearchBar (PlaceHolder) only shows the names of the data from the Database. Now I want to select one item, which i choose in the searchbar and get all the other columns of that one row and store the data in a listview in another activity.
So my first question is, how can i get all data from one row, if i only have the name? Should I do it with a cursor?
And my second question is, how should i store all the data from that one row in a listview in another activity?
Thank you for your help!
enter cclass SearchViewHolder extends RecyclerView.ViewHolder{
public TextView medid,name,menge,art,nummer;
public SearchViewHolder(View itemView) {
super(itemView);
medid = (TextView) itemView.findViewById(R.id.medid);
name = (TextView) itemView.findViewById(R.id.name);
menge = (TextView) itemView.findViewById(R.id.menge);
art = (TextView) itemView.findViewById(R.id.art);
nummer = (TextView) itemView.findViewById(R.id.nummer);
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Drugs> drugs;
public SearchAdapter(Context context, List<Drugs> drugs) {
this.context = context;
this.drugs = drugs;
}
public SearchAdapter() {
}
#Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater =LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.medikamentensuche,parent,false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(SearchViewHolder holder, int position) {
//String pharmaId,name,menge,art,preis,code,bezeichnung;
holder.medid.setText(toString().valueOf(drugs.get(position).getMedID()));
holder.name.setText(drugs.get(position).getName());
holder.menge.setText(drugs.get(position).getMenge());
holder.art.setText(drugs.get(position).getArt());
holder.nummer.setText(drugs.get(position).getNummer());
}
#Override
public int getItemCount() {
return drugs.size();
}
}
DataBaseOpenhelper class
public class DatabaseOpenHelper extends SQLiteAssetHelper {
private static final String DB_NAME = "medikamente.db";
private static final String TABLE = "Medikamente";
private static final int DB_VER = 1;
public static final String ID = "MedID";
public static final String NAME = "Handelsname";
public static final String MENGE = "Mengenangabe";
public static final String ART = "Mengenart";
public static final String NUMMER = "Pharmanummer";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
//neues Medikament hinzufügen
public boolean insertNewEntry (String name, String mengenangabe, String mengenart, String pharmanummer) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME,name);
values.put(MENGE,mengenangabe);
values.put(ART,mengenart);
values.put(NUMMER,pharmanummer);
long result = db.insert("Medikamente",null,values);
if (result == -1)
return false;
else
return true;
}
public List<Drugs> getDrug() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
Log.d("in der DrugDatabases", "SQLiteQueryBuilder successful");
//Kathi habe hier: "ATCCode", "BezeichnungATCCode" gelöscht
String [] sqlSelect = {"MedID", "Handelsname", "Mengenangabe", "Mengenart", "Pharmanummer"};
String tableName = "Medikamente";
Log.d("in der DrugDatabases", " successful" + sqlSelect);
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
public List<String> getNames() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"Handelsname" };
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, null, null, null, null, null);
List<String> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
result.add(cursor.getString(cursor.getColumnIndex("Handelsname" )));
}while (cursor.moveToNext());
}return result;
}
public List<Drugs> getDrugsByName(String name) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"MedID" ,"Handelsname" ,"Mengenangabe" ,"Mengenart" ,"Pharmanummer"};
String tableName = "Medikamente";
qb.setTables(tableName);
Cursor cursor = qb.query(db, sqlSelect, "Handelsname LIKE ?",new String[]{"%"+name+"%"}, null, null, null);
List<Drugs> result = new ArrayList<>();
if(cursor.moveToFirst()) {
do{
Drugs drug = new Drugs();
drug.setMedID(cursor.getInt(cursor.getColumnIndex("MedID")));
drug.setName(cursor.getString(cursor.getColumnIndex("Handelsname")));
drug.setMenge(cursor.getString(cursor.getColumnIndex("Mengenangabe")));
drug.setArt(cursor.getString(cursor.getColumnIndex("Mengenart")));
drug.setNummer(cursor.getString(cursor.getColumnIndex("Pharmanummer")));
result.add(drug);
}while (cursor.moveToNext());
}return result;
}
}
MedSucheActivity
public class MedSucheActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
TextView textView;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
DatabaseOpenHelper database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medsuchen);
Button button = (Button) findViewById(R.id.hinzufügen);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MedTableActivity.class);
TextView suche = (TextView) findViewById(R.id.SuchMedikament);
intent.putExtra("weitergabe",suche.getText().toString());
startActivityForResult(intent,1);
//wichtig wenn man Daten zurück geben will von der 2.Activity
}
});
textView = (TextView) findViewById(R.id.SuchMedikament);
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
//textView = (TextView) findViewById(R.id.versuch);
//Datenbank
database = new DatabaseOpenHelper(this);
//Searchbar
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for(String search:suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if(!enabled)
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
//init Adapter default set all result
adapter = new SearchAdapter(this,database.getDrug());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this,database.getDrugsByName(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getNames();
materialSearchBar.setLastSuggestions(suggestList);
}
public void onHinzuClick(View v) {
Log.d("msg","Auf Hinzufügen Button geklickt");
Intent intent = new Intent (getBaseContext(),MedikamentHinzufugenActivity.class);
startActivity(intent);
}
}
So my first question is, how can i get all data from one row, if i
only have the name?
And my second question is, how should i store all the data from that
one row in a listview in another activity?
If name is definitely going to be unique, which it appears that it may not be, then you can use that in conjunction with the getDrugsByName method to obtain a list of Drug objects (1 if the name is unique). So name is all that would be required and this can be passed to another activity via an Intent Extra and thus retrieved from that Intent Extra, you can then use the getDrugsbyName method in that activity to then get all the data for the row (for 2.). Of course you could also pass all values via Intent Extras.
If name isn't necessarily unique then you could use MedId (column ID) (assuming that it's the PRIMARY KEY of the table and thus unique) instead of the name. You would probably have a method getDrugById in the DatabaseHelper class along the lines of (for 2.) :-
public Drugs getDrugById(long id) {
SQLiteDatabase db = getReadableDatabase();
Drugs rv = new Drugs();
rv.setMedID(-1); // set so that drug not found can be determined
String whereclause = ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setMedID(id);
rv.setName(csr.getString(csr.getColumnIndex(NAME)));
rv.setMenge(csr.getString(csr.getColumnIndex(MENGE)));
rv.setArt(csr.getString(csr.getColumnIndex(ART)));
rv.setNummer(csr.getString(csr.getColumnIndex(NUMMER)));
}
csr.close();
return rv;
}
Notes
The returned value should be checked for the MedID being -1, this indicating that there is no such row that matches the passed id.
Rather than risking mistyping names the CONSTANTS defined in the class have been used (you may wish to adopt this throughout).
Cursors should ALWAYS be closed when done with, otherwise an exception can occur.
The above assumes that the ID column is the PRIMARY KEY and that it is an alias of the rowid column. That is you have ID INTEGER PRIMARY KEY or ID INTEGER,..other columns.., PRIMARY KEY (ID)
The above assumes the correct usage of the ID column i.e. that it is treated as a long not an int (int is ok as long as the rows are limited, however SQLite allows rowid's as high as 9223372036854775807, which cannot be handled by an int).
This is the usual method, as using an alias of rowid will likely be the most efficient.

Data repeating on restarting App in Android Database

I am facing this problem whenever i run the app 1st time data in database remain single time but when i close the App and restart again data goes twice(means two same row in table).Similarly for 3rd, 4th time and so on. How do i get rid of this problem? I even put datas.clear in DataList.java but don't whether i have add the datas.clear() line in correct place or not.
PLz help if there is any other problem in my code.
MainActivity.java code
public class MainActivity extends AppCompatActivity {
Button listButton, addButton;
DatabaseHelper df;
private final static String TAG = "TestActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
df = new DatabaseHelper(this);
addButton = (Button) findViewById(R.id.addbutton);
uploadList();
}
public void uploadList(){
DatabaseHelper df=new DatabaseHelper(this);
df.open();
try{
InputStream im=getResources().getAssets().open("testdata.csv");
BufferedReader br=new BufferedReader(new InputStreamReader(im));
String data=br.readLine();
while(data != null){
String t[]=data.split(",");
Product p=new Product();
p.setFirst(t[0]);
p.setSec(t[1]);
p.setThird(t[2]);
df.insert(p);
data=br.readLine();
}
}catch(Exception e){
}
}
}
DatabaseHelper.java code
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String FIRST="Name";
private static final String SECOND="Issn";
private static final String THIRD="ImpactFactor";
private static final String DATABASE="journal2016";
private static final String TABLENAME="journal";
private static final int VERSION=1;
SQLiteDatabase sd;
public void open(){
sd=getWritableDatabase();
}
public void close(){
sd.close();
}
public DatabaseHelper(Context context) {
super(context, DATABASE, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
sqLiteDatabase.execSQL("CREATE TABLE " + TABLENAME + " ( NAME TEXT, ISSN TEXT, IMPACTFACTOR REAL)");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME );
}
public long insert(Product p){
ContentValues cv=new ContentValues();
cv.put(FIRST, p.getFirst());
cv.put(SECOND, p.getSec());
cv.put(THIRD, p.getThird());
return sd.insertWithOnConflict(TABLENAME, null, cv,SQLiteDatabase.CONFLICT_REPLACE);
}
public List<Product> getAllProduct(){
ArrayList<Product> list=new ArrayList<Product>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c=db.rawQuery("SELECT * FROM " + TABLENAME, null);
while(c.moveToNext()){
Product p=new Product();
p.setFirst(c.getString(0));
p.setSec(c.getString(1));
p.setThird(c.getString(2));
list.add(p);
}
db.close();
return list;
}
}
DataList.java code
public class DataList extends Activity{
List<Product> datas = new ArrayList<Product>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
datas.clear();
DatabaseHelper d=new DatabaseHelper(this);
d.open();
datas = d.getAllProduct();
ListView lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, datas));
}
}
Product.java
public class Product {
private String first;
private String second;
private String third;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSec() {
return second;
}
public void setSec(String sec) {
this.second = sec;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
#Override
public String toString() {
return first + second + third;
}
}
Remove this line from your onCreate() method:
df = new DatabaseHelper(this);
as no need of it because you are create object of your DatabaseHelper class inside uploadList() method.
And also you are calling uploadList() method inside onCreate() thats why every time you launch the app, the onCreate() method executes and you uploadList() also execute. Try to put its calling statement in an onClickListener so it happens when you click a button or your choice of stuff.

Android CursorAdapter not updating all fields

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.

How to convert ListActivity to ListFragment?

i have a database which i created in Sqlite database browser and using a library to use that database for populating my lists in ListActivity. now to i want to convert my ListActivity to ListFragment...
here is the code...
code for DataBaseHelper
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class DataBaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "dictionary.db";
private static final int DATABASE_VERSION = 1;
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Cursor getDictionary() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"0 _id", "dream_title", "dream_meaning"};
String sqlTables = "dictionary";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
c.moveToFirst();
return c;
}
}
code for MainActivity
public class MainActivity extends ListActivity {
private Cursor dictionary;
private DataBaseHelper db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DataBaseHelper(this);
dictionary = db.getDictionary(); // you would not typically call this on the main thread
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
dictionary,
new String[] {"dream_title"},
new int[] {android.R.id.text1});
getListView().setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
dictionary.close();
db.close();
}
}
Any help will be appreciable
ListFragment uses setListAdapter. I think that's all you would need to change.

Android showing database in SwipeView

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();

Categories

Resources