How to adapt startManagingCursor() to a non-deprecated method? - java

I've been trying to stick with startManagingCursor() for my read-only SQLite database, but it's throwing a lot of errors even if I use stopManagingCursor() (yes, I know they're deprecated).
I'd like to have some help to know the steps to go from managing cursors to a better method without changing much since I've never used them and this code is somehow stable although random errors pop up from time to time because of startManagingCursor() (in a single activity app, it works fine, but when using it as a frament in a multifragment app, it gets really problematic).
However, when I simply change startManagingCursor() to getLoaderManager() it still works, but the documentation also tells it's deprecated and indicates getSupportLoaderManager() and, when I use this one, it gets crossed out as if it's also deprecated (Lint says "getSupportLoaderManager() is deprecated", but doesn't say the same for getLoaderManager()); and those may produce java.lang.NullPointerException what wasn't happening with startManagingCursor(cursor) although both are runnable.
So what should I do then?
The SQLite fragment is this:
public class SQLiteDatabaseActivity extends Fragment {
public static SQLiteDatabaseActivity newInstance() {
return new SQLiteDatabaseActivity();
}
ExpandableListView expandableListView;
Database mDatabase;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sqlite_database_activity, container, false);
mDatabase = new Database(getActivity());
mDatabase.open();
Cursor cursor = mDatabase.getDatabase();
getActivity().startManagingCursor(cursor);
String[] groupFrom = {
Database.DATABASE_GROUP_1,
Database.DATABASE_GROUP_2,
Database.DATABASE_GROUP_3,
Database.DATABASE_GROUP_4
};
int[] groupTo = {
R.id.group_number,
R.id.group_name,
R.id.group_path,
R.id.group_company
};
String[] childFrom = new String[]{
Database.DATABASE_CHILD_1,
Database.DATABASE_CHILD_2,
Database.DATABASE_CHILD_3,
Database.DATABASE_CHILD_4,
Database.DATABASE_CHILD_5,
Database.DATABASE_CHILD_6,
Database.DATABASE_CHILD_7,
Database.DATABASE_CHILD_8,
Database.DATABASE_CHILD_9,
Database.DATABASE_CHILD_10,
Database.DATABASE_CHILD_11,
Database.DATABASE_CHILD_12
};
int[] childTo = {
R.id.child1,
R.id.child2,
R.id.child_saturday_origin,
R.id.child_saturday_destiny,
R.id.child_sunday_origin,
R.id.child_sunday_destiny,
R.id.child_origin,
R.id.child_destiny,
R.id.child_saturday_origin_origin,
R.id.child_saturday_destiny_destiny,
R.id.child_sunday_origin_origin,
R.id.child_sunday_destiny_destiny
};
SimpleCursorTreeAdapter simplecursortreeAdapter = new ExpandableListViewAdapter(
getActivity(),
cursor,
R.layout.sqlite_database_list_group,
groupFrom,
groupTo,
R.layout.sqlite_database_list_child,
childFrom,
childTo
);
expandableListView = view.findViewById(R.id.expandableListview);
expandableListView.setAdapter(simplecursortreeAdapter);
getActivity().stopManagingCursor(cursor);
return view;
}
private class ExpandableListViewAdapter extends SimpleCursorTreeAdapter {
private ExpandableListViewAdapter(
Context context,
Cursor cursor,
int groupLayout,
String[] groupFrom,
int[] groupTo,
int childLayout,
String[] childFrom,
int[] childTo) {
super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom, childTo);
}
protected Cursor getChildrenCursor(Cursor groupCursor) {
return mDatabase.getID(groupCursor.getInt(groupCursor.getColumnIndex(Database.DATABASE_ID)));
}
}
public void onDestroy() {
super.onDestroy();
mDatabase.close();
}
}
The database is here:
public class Database {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "BusScheduleDatabase.db";
private static final String DATABASE_TABLE = "BusSchedule";
public static final String DATABASE_ID = "_id";
public static final String DATABASE_GROUP_1 = "Linha";
public static final String DATABASE_GROUP_2 = "Nome";
public static final String DATABASE_GROUP_3 = "Caminho";
public static final String DATABASE_GROUP_4 = "Empresa";
public static final String DATABASE_CHILD_1 = "SemanaIda";
public static final String DATABASE_CHILD_2 = "SemanaVolta";
public static final String DATABASE_CHILD_3 = "SabadoIda";
public static final String DATABASE_CHILD_4 = "SabadoVolta";
public static final String DATABASE_CHILD_5 = "DomingoIda";
public static final String DATABASE_CHILD_6 = "DomingoVolta";
public static final String DATABASE_CHILD_7 = "Origem";
public static final String DATABASE_CHILD_8 = "Destino";
public static final String DATABASE_CHILD_9 = "Origem";
public static final String DATABASE_CHILD_10 = "Destino";
public static final String DATABASE_CHILD_11 = "Origem";
public static final String DATABASE_CHILD_12 = "Destino";
private final Context mContext;
private DatabaseHelper mDatabaseHelper;
private SQLiteDatabase mDB;
public Database(Context context) {
mContext = context;
}
public void open() {
mDatabaseHelper = new DatabaseHelper(mContext, DATABASE_NAME, null, DATABASE_VERSION);
mDB = mDatabaseHelper.getReadableDatabase();
}
public void close() {
if (mDatabaseHelper != null) mDatabaseHelper.close();
}
public Cursor getDatabase() {
return mDB.query(DATABASE_TABLE, null, null, null, null, null, DATABASE_GROUP_1);
}
public Cursor getID(long rowID) {
return mDB.query(DATABASE_TABLE, null, "_id" + " = "
+ rowID, null, null, null, null);
}
public class DatabaseHelper extends SQLiteAssetHelper {
public DatabaseHelper(Context mContext, String DATABASE_NAME, SQLiteDatabase.CursorFactory factory, int DATABASE_VERSION) {
super(mContext, DATABASE_NAME, factory, DATABASE_VERSION);
super.setForcedUpgrade();
}
}
}
And the repetitive error is basically the following:
java.lang.IllegalStateException: this should only be called when the cursor is valid
Thank you very much in advance for the help!

Related

Remove more than one element from CursorAdapter/List View

I'm making a project in Android/Java. I have an activity with a listview that displays values from a database and a remove button. For the moment, each row of this list view consists of a checktextview. This last one displays the name of an element of the database. I want to select different elements (with the check text view) and then if I press the remove button, all the selected elements have to be removed from the list and from database. In the following I put the essential parts of my classes. I already done most of the work.
This is my activity:
public class ShoppingListActivity extends AppCompatActivity {
// Variables for the management of the database
private DBManagerShoppingList dbShoppingList;
private Cursor crs;
// List view for the shopping list elements
private ListView shoppingListListView;
private ShoppingListViewAdapter shoppingListViewAdapter;
// Generic variables
private String selectedShoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
// Find of the useful widgets
shoppingListListView = findViewById(R.id.listViewSelShoppingList);
shoppingListsSpinner = findViewById(R.id.spinnerShoppingLists);
selectedShoppingList = "List_1";
populateListView();
}
// Populate list view from database
public void populateListView() {
// Database management
dbShoppingList = new DBManagerShoppingList(this, selectedShoppingList);
crs = dbShoppingList.query();
new Handler().post(new Runnable() {
#Override
public void run() {
shoppingListViewAdapter = new ShoppingListViewAdapter(ShoppingListActivity.this, crs, 0);
shoppingListListView.setAdapter(shoppingListViewAdapter);
}
});
}
// Remove selected elements
public void removeSelectedElements(View btnRemove) {
// TODO
}
}
This is my custom adapter:
public class ShoppingListViewAdapter extends CursorAdapter {
private LayoutInflater layoutInflater;
private List<Integer> elementsPosArrayList = new ArrayList<>();
private HashMap<String, Integer> elementsMap = new HashMap<>();
public ShoppingListViewAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return layoutInflater.inflate(R.layout.list_view_row, viewGroup, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
elementsMap.put(elementName, cursor.getPosition());
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementsPosArrayList.add(elementsMap.get(checkBoxElementName.getText().toString()));
} else {
elementsPosArrayList.remove(elementsMap.get(checkBoxElementName.getText().toString()));
}
}
});
}
public long getElementId(Cursor crs, int position) {
crs.moveToPosition(position);
return crs.getLong(crs.getColumnIndex(DBFieldsShoppingList.FIELD_ID));
}
public List<Integer> getElementsPosArrayList() {
return elementsPosArrayList;
}
}
Classes for the database management are the following:
DBHelper:
public class DBHelperShoppingList extends SQLiteOpenHelper {
private String DBName;
public DBHelperShoppingList(#Nullable Context context, int dbVersion, String dbName) {
super(context, dbName, null, dbVersion);
this.DBName = dbName;
}
#Override
public void onCreate(SQLiteDatabase shoppingListDB) {
String q = "CREATE TABLE " + DBFieldsShoppingList.FIELD_TABLE_NAME +
" ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
DBFieldsShoppingList.FIELD_ELEMENT_NAME + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_TYPE + " TEXT," +
DBFieldsShoppingList.FIELD_ELEMENT_QUANT + " TEXT)";
shoppingListDB.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase shoppingListDB, int oldVersion, int newVersion) {}
}
Class for the fields of the database:
public class DBFieldsShoppingList {
public static final String FIELD_ID = "_Id";
public static final String FIELD_TABLE_NAME = "Shopping_List";
public static final String FIELD_ELEMENT_NAME = "Element_Name";
public static final String FIELD_ELEMENT_TYPE = "Element_Type";
public static final String FIELD_ELEMENT_QUANT = "Element_Quant";
}
Class database manager:
public class DBManagerShoppingList {
private DBHelperShoppingList dbHelperShoppingList;
public DBManagerShoppingList(Context ctx, String shoppingListName) {
dbHelperShoppingList = new DBHelperShoppingList(ctx, 1, shoppingListName);
}
public void dbSave(String elementName, String elementType, String elementQuantity) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_NAME, elementName);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_TYPE, elementType);
cv.put(DBFieldsShoppingList.FIELD_ELEMENT_QUANT, elementQuantity);
try {
db.insert(DBFieldsShoppingList.FIELD_TABLE_NAME, null, cv);
} catch (SQLiteException ignored) {}
}
public boolean deleteElement(long id) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ID + "=?", new String[]{Long.toString(id)})>0;
} catch(SQLiteException exc) {
return false;
}
}
public static void deleteDB(Context ctx, String DBName) {
ctx.deleteDatabase(DBName);
}
public Cursor query() {
Cursor crs;
try {
SQLiteDatabase db = dbHelperShoppingList.getReadableDatabase();
crs = db.query(DBFieldsShoppingList.FIELD_TABLE_NAME, null, null, null, null, null, null, null);
} catch (SQLiteException exc) {
return null;
}
return crs;
}
}
I tought, in bindView method of the adapter class, to save a map between element name and its position. Then, to create a list of the element names of the checked elements. In this way, I can know the positions of the checked elements, from the map. Now, I have to get indexes of the checked elements, in order to remove them from database, with delete method of the database manager class.
How can I solve this problem? If my structure is not correct, say me how to change.
Thank you very much in advance.
Marco
Hy to everybody,
I found the solution. In database manager class, I changed the delete method in the following way:
public boolean deleteElement(String elementName) {
SQLiteDatabase db = dbHelperShoppingList.getWritableDatabase();
try {
return db.delete(DBFieldsShoppingList.FIELD_TABLE_NAME, DBFieldsShoppingList.FIELD_ELEMENT_NAME + "=?", new String[]{(elementName)})>0;
} catch(SQLiteException exc) {
return false;
}
}
This allows, to search by name in database.
In adapter class, I removed the map, and I wrote an arraylist of string, where I put name of the checked elements:
#Override
public void bindView(View view, Context context, Cursor cursor) {
// CheckBox management
final CheckBox checkBoxElementName = view.findViewById(R.id.checkBoxElementName);
String elementName = cursor.getString(cursor.getColumnIndex(DBFieldsShoppingList.FIELD_ELEMENT_NAME));
checkBoxElementName.setText(elementName);
checkBoxElementName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
elementNamesArrayList.add(checkBoxElementName.getText().toString());
} else {
elementNamesArrayList.remove(checkBoxElementName.getText().toString());
}
}
});
}
Finally, in the activity class, the remove method is the following:
public void removeSelectedElements(View btnRemove) {
List<String> elementNamesArrayList = shoppingListViewAdapter.getElementNamesArrayList();
for (String item: elementNamesArrayList) {
dbShoppingList.deleteElement(item);
}
populateListView();
}
In this way I solved my problem.
Marco

Android SQLite data fetching

Every time I run a "select *" query from my SQLite, the app keeps stopping. I've deduced it to it calling the database helper every time, but I don't know how to fix it.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setStatusBarColor(Color.WHITE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayUsers();
}
public void displayUsers() {
Cursor cursor = databaseHelper.getAllUsers(); //here's where the error keeps on happening
if(cursor.getCount() == 0) {
Toast.makeText(this, "none", Toast.LENGTH_SHORT).show();
}
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "reminders.db";
public static final String T_1 = "tbl_users";
public static final String T1_COL_1 = "ID";
public static final String T1_COL_2 = "FIRST_NAME";
public static final String T1_COL_3 = "MIDDLE_INITIAL";
public static final String T1_COL_4 = "LAST_NAME";
public static final String T1_COL_5 = "PHONE";
public static final String T1_COL_6 = "EMAIL";
public static final String T1_COL_7 = "USERNAME";
public static final String T1_COL_8 = "PASSWORD";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase database = this.getWritableDatabase();
}
...//other functions
public Cursor getAllUsers() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + T_1, null);
return cursor;
}
}
Your DatabaseHelper class doesn’t create any object cause you didn’t call new DatabaseHelper (this). Thats why databasehelper return null.
You can try those line in onCreate method,
databaseHelper= new DatabaseHelper(this);
Before returning cursor close your database
public Cursor getAllUsers() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from " + T_1, null);
database.close(); // Added
return cursor;
}
In following function at first your have to initialize database to get WritableDatabase in DatabaseHelper class.
public void displayUsers() {
databaseHelper = DatabaseHelper(MainActivity.this)
Cursor cursor = databaseHelper.getAllUsers();
if(cursor.getCount() == 0) {
Toast.makeText(this, "none", Toast.LENGTH_SHORT).show();
}
}

Is it the correct way to initialize SQLite in MainActivity?

Im working on android studio and i encountered a problem, I cant initialize my sqlite instance in my DataHandler class but I can initialize it in my MainActivity class.
Example:
MainActivity class:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//valid
private SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("Database", Context.MODE_PRIVATE , null); //...
in datahandler class:
public class DataHandler {
public static String[] names,dates;
//invalid: cannot resolve method
SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("HMDB", Context.MODE_PRIVATE , null);
so, i did this
in main activity:
public SQLiteDatabase getSqLiteDatabase() {
return sqLiteDatabase;
}
in datahandler:
MainActivity mainActivity;
SQLiteDatabase sqLiteDatabase = mainActivity.getSqLiteDatabase();
is this the correct way? is there any better method? sry if hard to understand
Is this the correct way?
Did it throws any errors when project is running ?
This is how I normally do in DatabaseHandler (just sharing)
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DATA.db";
public static final String TABLE_NAME = "TITLE";
public static final String COL0 = "ID";
public static final String COL1 = "TODO";
public static final String COL2 = "DETAIL";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, TODO TEXT, DETAIL TEXT)";
db.execSQL(createTable); }
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop if database is exists" + TABLE_NAME);
onCreate(db);
}
}
In MainActivity, declare this line
DatabaseHandler db;
In onCreate method, initialize DatabaseHandler
db = new DatabaseHandler(this);
When you want to use SQLite database, make sure you have this line
SQLiteDatabase db = this.getWritableDatabase();
The best approach is to use Singleton Pattern as described here
https://github.com/codepath/android_guides/wiki/Local-Databases-with-SQLiteOpenHelper
public class PostsDatabaseHelper extends SQLiteOpenHelper {
private static PostsDatabaseHelper sInstance;
// ...
public static synchronized PostsDatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
if (sInstance == null) {
sInstance = new PostsDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
/**
* Constructor should be private to prevent direct instantiation.
* Make a call to the static method "getInstance()" instead.
*/
private PostsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
And in your MainActivity use it like
// In any activity just pass the context and use the singleton method
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(context);
// or
PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(getActivity());
// Do something with data via Cursor and
helper.close();
This approach perfect suits to get access to the database from different places of you app like Service, Fragment and etc...

Table is not found in SQLiteDatabase

I am facing this strange problem that I searched alot, but no use so far.
The following code I am using to retrieve SQLite database using a DBHelper that extends from openhelper class.
public class DBHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "cp.db";
public static final String DB_PATH = "/data/data/abdulla.com.test/databases/";
public static final String ID = "no";
public static final String NAME = "name";
public static final String FORMULA = "formula";
public static final String MW = "mw";
public static final String OMEGA = "omega";
public static final String TC = "tc";
public static final String PC = "pc";
SQLiteDatabase db;
Cursor cursor;
ArrayList<String> elementName;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists elements");
this.onCreate(db);
}
public List<Element> getAllElements() {
List<Element> elementList = new ArrayList<Element>();
// Select All Query
Cursor cursor = null;
String selectQuery = "SELECT * FROM elements";
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Element element = new Element();
element.setNo(Integer.parseInt(cursor.getString(0)));
element.setFormula(cursor.getString(1));
element.setName(cursor.getString(2));
// Adding contact to list
elementList.add(element);
} while (cursor.moveToNext());
}
// return contact list
return elementList;
}
}
This is capture from MainActivity class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper helper = new DBHelper(this);
List<Element> elementList = helper.getAllElements();
for(Element element : elementList){
String log = "no: "+element.getNo();
Log.d("No: ", log);
}
}
}
I am getting this error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{abdulla.com.test/abdulla.com.test.MainActivity}:
android.database.sqlite.SQLiteException: no such table: elements (code 1):
, while compiling: SELECT * FROM elements
I know that elements table is there
Any help?
Probably the issue is in your onUpgrade() method. If your database doesn't have version, application tries to upgrade it, and drops your table (db.execSQL("drop table if exists elements");).
Solution: set version to DB or change onUpgrade() method (delete DROP statement).

cannot bind data from sqlliteData-base to simplecursoradaptor

I don´t know how to connect the data my array String [] station = {"København", "Grenaa", "Hanstholm"}; in my MyListActivity to the simpleCursorAdaptor
I have made a SQLitedatabase, a Helperclass and anActivityclass - but I get the error " java.lang.IllegalArgumentException: column 'København' does not exist". I have additional code - but this code should be sufficient I think.
Any help would really be appreciated.
public class MyListActivity extends ListActivity {
String [] station = {"København", "Grenaa", "Hanstholm"};
Cursor stations;
SQLiteDatabase db;
SimpleCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DBAdapter dbaAdapter = new DBAdapter(this);
dbaAdapter.open();
Cursor stations = dbaAdapter.getStations();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
setListAdapter(cursorAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor) l.getItemAtPosition(position);
String value = station[(int)id];
Intent intent = new Intent();
intent.putExtra(TravelActivity.SELECTED_STATION_NAME, cursor.getString(cursor.getColumnIndexOrThrow("station")));
this.setResult(RESULT_OK,intent);
cursor.close();
finish();
}
#Override
protected void onDestroy() {
db.close();
}
}
public class MyHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "database";
String DESTINATION = "DESTINATION";
int version = 1;
public MyHelper(Context context) {
super(context, "travel.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String TRAVELS = ( "create table travels (_id integer primary key autoincrement, start text, slut text)");
String STATIONS = ( "create table stations (_id integer primary key autoincrement, start text)" );
db.execSQL(TRAVELS);
db.execSQL(STATIONS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS ");
onCreate(db);
}
}
public class DBAdapter {
MyHelper myHelper;
SQLiteDatabase db;
String TABLE_STATIONS = "stations";
String TABLE_TRAVELS = "travels";
String START = "start";
String SLUT = "slut";
String ID_COL = "_id";
Context context;
public static final int NUMBER_TRAVELS = 1;
public DBAdapter(Context context) {
this.context = context;
myHelper = new MyHelper(context);
}
public void open() {
db = myHelper.getWritableDatabase();
}
public void close() {
myHelper.close();
}
public Cursor getTravels() {
Cursor cursor = db.query(TABLE_TRAVELS,new String[]{ID_COL,START,SLUT},null,null,null,null,START);
return cursor;
}
public void saveTravels(String start, String slut) {
ContentValues values = new ContentValues();
values.put(START,start);
values.put(SLUT,slut);
db.insert(TABLE_TRAVELS,null,values);
}
public Cursor getStations() {
Cursor cursor = db.query(TABLE_STATIONS,new String[]{ID_COL,START},null,null,null,null,START);
return cursor;
}
public void saveStations(String start) {
ContentValues values = new ContentValues();
values.put(START,start);
db.insert(TABLE_TRAVELS,null,values);
}
}
The error is generated by your SimpleCursorAdapter constructor :
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,stations,station,new int [] {
android.R.id.text1
});
The 4td parameter is the column names, so a String array with START and/or SLUT values in your case.

Categories

Resources