I don't know what am I missing that I cannot populate my DrinkActivity from my Database!
here is my SQLiteOpenHelper class :
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "starbuzz"; // the name of our database
private static final int DB_VERSION = 2; // the version of the database
StarbuzzDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateMyDatabase(db, 0, DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
private static void insertDrink(SQLiteDatabase db, String name, String description,
int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam",
R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
}
}
and the other activity (DrinkCategoryActivity) which leads to DrinkActivity is here :
public class DrinkCategoryActivity extends AppCompatActivity {
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
ListView listDrinks = findViewById(R.id.list_drinks);
try {
db = starbuzzDatabaseHelper.getReadableDatabase();
cursor = db.query("DRINK",
new String[]{"_id", "NAME"},
null, null, null, null, null);
SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listDrinks.setAdapter(listAdapter);
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> listDrinks,
View itemView,
int position,
long id) {
//Pass the drink the user clicks on to DrinkActivity
Intent intent = new Intent(DrinkCategoryActivity.this,
DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINK_ID, (int) id);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
cursor.close();
db.close();
}
}
and finally here is DrinkActivity :
public class DrinkActivity extends Activity {
public static final String EXTRA_DRINK_ID = "drinkId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId = Objects.requireNonNull(getIntent().getExtras()).getInt("EXTRA_DRINK_ID");
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query ("DRINK",
new String[] {"NAME", "DESCRIPTION", "IMAGE_RESOURCE_ID"},
"_id = ?",
new String[] {Integer.toString(drinkId)},
null, null,null);
if (cursor.moveToFirst()) {
//Get the drink details from the cursor
String nameText = cursor.getString(0);
String descriptionText = cursor.getString(1);
int photoId = cursor.getInt(2);
//Populate the drink name
TextView name = findViewById(R.id.name1);
name.setText(nameText);
//Populate the drink description
TextView description = findViewById(R.id.description1);
description.setText(descriptionText);
//Populate the drink image
ImageView photo = findViewById(R.id.photo1);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
}
cursor.close();
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Database unavailable", Toast.LENGTH_LONG).show();
}
}
}
First off the DATABASE_NAME should be name.db, you are missing the extention of the file.
Reference: https://developer.android.com/training/data-storage/sqlite
Another important thing is how to retrieve data from the intent, you should not use:
getIntent().getExtras()).getInt("EXTRA_DRINK_ID")
Instead, once you have the intent, you can directly extract the data in this way:
Intent intent = getIntent();
int extraId = intent.getExtraInt(DrinkActivity.EXTRA_DRINK_ID);
Related
I am creating a contact application that works with SQLite database and I face a problem when I try to pass the id of the contact to another intent to use it in a query.
Here is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView contactsList;
DbContact dbContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactsList = findViewById(R.id.contactList);
dbContact = new DbContact(this);
contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, update_contact.class);
Contact selected_contact =(Contact) contactsList.getItemAtPosition(i);
Toast.makeText(MainActivity.this, "ths position is " +selected_contact.getId(), Toast.LENGTH_SHORT).show();
/*intent.putExtra("id", selected_contact.getId());
startActivity(intent);*/
}
});
}
}
update_contact.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_contact);
int id = getIntent().getIntExtra("id",0);
db = new DbContact(this);
editName = (EditText) findViewById(R.id.editName);
editPhone = (EditText) findViewById(R.id.editPhone);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
Contact contact = db.getContactById(id);
editName.setText(contact.getName());
editPhone.setText(contact.getPhone());
}
BdContact :
public DbContact(#Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String create_table = "create table "+TABLE_CONTACTS+"("+KEY_ID+" int primary key AUTOINCREMENT, "+KEY_NAME+" varchar(30), "+KEY_PHONE+" varchar(30))";
sqLiteDatabase.execSQL(create_table);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String delete_table = "DROP TABLE IF EXISTS "+TABLE_CONTACTS;
sqLiteDatabase.execSQL(delete_table);
onCreate(sqLiteDatabase);
}
public void addContact(Contact contact){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
db.insert(TABLE_CONTACTS, null, values);
}
public ArrayList<Contact> getAllContacts(){
ArrayList<Contact> contacts = new ArrayList<>();
String selectAll_query = "select * from "+ TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectAll_query, null);
if(cursor.moveToFirst()){
do{
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
Contact contact = new Contact(id,name, phone);
contacts.add(contact);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return contacts;
}
public Contact getContactById(int id_contact){
Contact contact = null;
SQLiteDatabase db = this.getReadableDatabase();
String select_query = "select * from "+TABLE_CONTACTS+" where id = " + id_contact;
Cursor cursor = db.rawQuery(select_query, null);
if(cursor.moveToFirst()){
int id = cursor.getInt(cursor.getColumnIndexOrThrow(KEY_ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(KEY_NAME));
String phone = cursor.getString(cursor.getColumnIndexOrThrow(KEY_PHONE));
contact = new Contact(id, name, phone);
}
return contact;
}
I think that the problem is in the database because I suspect the id didn't auto-incremented
Thank you guys for helping me solve this issue
Have you added the position?
listView.getItemAtPosition(position)
I want to insert a new record into a sqlite db.
My table is called words. It has the columns id, word, meaning, details, lesson, ticks.
When I try to insert a new record, it just saves details as word and lesson as meaning, whereas details and lesson are stored with a null value.
The autoincrement primary key id and ticks are stored correctly.
Code
Handler:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "wordDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE words " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"word TEXT, " +
"meaning TEXT, " +
"details TEXT, " +
"lesson TEXT, " +
"ticks INTEGER ) ";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS words";
db.execSQL(sql);
onCreate(db);
}
Object:
public class ObjectStudent {
int id;
String word;
String meaning;
String details;
String lesson;
int ticks;
public ObjectStudent(){
}
OnClickListener:
public class OnClickeListenerCreateStudent implements View.OnClickListener {
#Override
public void onClick(View view) {
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);
final EditText et_word = (EditText) formElementsView.findViewById(R.id.et_word);
final EditText et_meaning = (EditText) formElementsView.findViewById(R.id.et_meaning);
final EditText et_details = (EditText) formElementsView.findViewById(R.id.et_details);
final EditText et_lesson = (EditText) formElementsView.findViewById(R.id.et_lesson);
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Word")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String wordTitle = et_word.getText().toString();
String wordMeaning = et_meaning.getText().toString();
String wordDetails = et_details.getText().toString();
String wordLesson = et_lesson.getText().toString();
ObjectStudent objectStudent = new ObjectStudent();
/* objectStudent.word= wordTitle;
objectStudent.meaning= wordMeaning;
objectStudent.details= wordDetails;
objectStudent.lesson= wordLesson;*/
objectStudent.word = "word"; // et_word.getText().toString();
objectStudent.meaning = "meaning"; // et_meaning.getText().toString();
objectStudent.details = "details"; // et_details.getText().toString();
objectStudent.lesson = "lesson"; // et_lesson.getText().toString();
objectStudent.ticks= 1;
boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);
if(createSuccessful){
Toast.makeText(context, "Word information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save Word information.", Toast.LENGTH_SHORT).show();
}
((MainActivity) context).countRecords();
((MainActivity) context).readRecords();
dialog.cancel();
}
}).show();
}
Create method on TableControllerStudent class:
public class TableControllerStudent extends DatabaseHandler {
public TableControllerStudent(Context context) {
super(context);
}
public boolean create(ObjectStudent objectStudent) {
ContentValues values = new ContentValues();
/* values.put("word", objectStudent.word);
values.put("meaning", objectStudent.meaning);
values.put("details", objectStudent.details);
values.put("lesson", objectStudent.lesson);*/
values.put("word", "w");
values.put("meaning", "m");
values.put("details", "d");
values.put("lesson", "l");
values.put("ticks", objectStudent.ticks);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("INSERT INTO " + "words "+ "(word, meaning,details, lesson, ticks ) VALUES ('word','meaning','details','lesson',2)");
//boolean createSuccessful = db.insert("words", null, values) > 0;
db.close();
//return createSuccessful;
return true;
}
Just update Database version to higher version(instead of 1,use 5).And check it.before run the application ,please uninstall and then run.
Use
db.insert(YOUR_TABLE_NAME,values);
instead of
db.execSQL() function
I'm learning android programming and trying to delete data from database using a button in custom ListView but, unfortunately, my App is getting crashed when I hit Yes On Alert DialogBox.
FenceActivity
public class FenceActivity extends AppCompatActivity {
List<Fence> fenceList;
SQLiteDatabase sqLiteDatabase;
ListView listViewFences;
FenceAdapter fenceAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savedfences);
listViewFences = findViewById(R.id.fencesListView);
fenceList = new ArrayList<>();
showFencesFromDatabase();
}
public void showFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
public void reloadFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
fenceList.clear();
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
}
ShowFencesFromDatabase method I'm using to get Data from the database.
FenceAdapter
public class FenceAdapter extends ArrayAdapter<Fence> {
Context context;
int listLayoutRes;
List<Fence> fenceList;
DataBaseHelper dataBaseHelper;
FenceActivity fenceActivity;
public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList) {
super(context, listLayoutRes, fenceList);
this.context = context;
this.listLayoutRes = listLayoutRes;
this.fenceList = fenceList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_layout_fences, null);
}
final Fence fence = fenceList.get(position);
TextView textViewSno = convertView.findViewById(R.id.textViewSnoLabel);
TextView textViewLat = convertView.findViewById(R.id.textViewLatitudeValue);
TextView textViewLon = convertView.findViewById(R.id.textViewLongitudeValue);
TextView textViewRadi = convertView.findViewById(R.id.textViewRadiusValue);
textViewSno.setText(Integer.toString(fence.getSno()));
textViewLat.setText(String.valueOf(fence.getLat()));
textViewLon.setText(String.valueOf(fence.getLon()));
textViewRadi.setText(Integer.toString(fence.getRadius()));
Button buttonDel = convertView.findViewById(R.id.buttonDeleteFence);
buttonDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper = new DataBaseHelper(context);
fenceActivity = (FenceActivity)context;
dataBaseHelper.deleteDataById(fence);
fenceActivity.reloadFencesFromDatabase();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
return convertView;
}
DatabaseHelper Class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public static final String DB_NAME = "FenceDatabase";
private static final String TABLE_NAME = "FenceData";
private static final String col1 = "Sno";
private static final String col2 = "Latitude";
private static final String col3 = "Longitude";
private static final String col4 = "Radius";
Context context;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + col1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col2 + " REAL , " + col3 + " REAL , " + col4 + " INTEGER)";
sqLiteDatabase.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean addData(Double lat, Double lon, int radi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, lat);
contentValues.put(col3, lon);
contentValues.put(col4, radi);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
return true;
}
public Cursor getAllData() {
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
return cursor;
}
public void deleteDataById(Fence fence) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String sql = "DELETE FROM FenceData WHERE Sno = ?";
sqLiteDatabase.execSQL(sql, new Integer[]{fence.getSno()});
}
}
Fence class
public class Fence {
int radius,sno;
double lat,lon;
public Fence( int sno,double lat, double lon,int radius) {
this.radius = radius;
this.sno = sno;
this.lat = lat;
this.lon = lon;
}
public int getRadius() {
return radius;
}
public int getSno() {
return sno;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
}
Errors
2019-06-30 19:06:08.658 22783-22875/com.abhishakkrmalviya.fencetest E/LB: fail to open file: No such file or directory
2019-06-30 19:06:11.473 22783-22783/com.abhishakkrmalviya.fencetest E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted
What steps should I take to make App work properly, I mean to delete data from the database?
Initialise dataBaseHelper = new DataBaseHelper(context); before invoking dataBaseHelper.deleteDataById();
The problem is within FenceAdapter.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper.deleteDataById();
fenceActivity.showFencesFromDatabase();
}
});
The problem is that dataBaseHelper is not initialized before its usege.
It can be solve by adding a line dataBaseHelper = new DataBaseHelper(context); at the end of adapter's constructor.
i need to make custom layout for my list view where data source is a sqlite database
when i run this code my output Thus shows (name next to phone) but i need to display output like this (phone under
name)
this is my code
here public class MainActivity extends AppCompatActivity {
AlertDialog.Builder builder;
List<Todo> todos;
MyDataBase db = new MyDataBase(this);
String m,m1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.editText);
final EditText editText1 = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button);
ListView listView = (ListView) findViewById(R.id.listView);
todos = db.getallcontacts();
final ArrayAdapter adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,todos);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m = editText.getText().toString();
m1 = editText1.getText().toString();
db.AddnewContact(new Todo(m, m1));
adapter.add(new Todo(m, m1));
Toast.makeText(getApplicationContext(), "contact saved", Toast.LENGTH_LONG).show();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long rowId) {
AlertDialog.Builder adb = new AlertDialog.Builder(
MainActivity.this);
adb.setMessage("you need to delete this contact");
adb.setPositiveButton("delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Todo td = todos.get(position);
db.deleteContact(td);
adapter.remove(td);
}
});
adb.show();
adapter.notifyDataSetChanged();
}
});
listView.setAdapter(adapter);
}
my database calss
here public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
final String KEY_NAME = "name";
final String KEY_PH_NO = "phone_number";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void AddnewContact (Todo todo)// this method to add new contact
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME,todo.getName());
values.put(KEY_PH_NO, todo.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
public Todo getContact(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO },KEY_ID + "=?",new String[] { String.valueOf(id) },null,null,null,null);
cursor.moveToFirst();
Todo contact = new Todo(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
public List<Todo> getallcontacts()
{
List<Todo> contactList = new ArrayList<Todo>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Todo contact = new Todo();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
public void deleteContact(Todo contact) {
int id = contact.getID();
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID
+ " = " + id, null);
db.close();
}
public Cursor fetchAllCountries() {
SQLiteDatabase database = this.getWritableDatabase();
Cursor mCursor = database.query(TABLE_CONTACTS, new String[] {KEY_ID,
KEY_NAME,KEY_PH_NO},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
my todo calss
`enter public class Todo {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Todo(){
}
// constructor
public Todo(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Todo(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
#Override
public String toString() {
return _name+" "+_phone_number;
}
}
`
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.